Update dependencies to add service fabric mesh via new azure-sdk-go

This commit is contained in:
Jeremy Rickard
2018-08-03 11:57:00 -06:00
parent bcea8b955b
commit 636b4120f1
130 changed files with 9430 additions and 9975 deletions

75
Gopkg.lock generated
View File

@@ -4,11 +4,13 @@
[[projects]]
name = "github.com/Azure/azure-sdk-for-go"
packages = [
"profiles/preview/preview/servicefabricmesh/mgmt/servicefabricmesh",
"services/batch/2017-09-01.6.0/batch",
"services/preview/servicefabricmesh/mgmt/2018-07-01-preview/servicefabricmesh",
"version"
]
revision = "51228ee60b238eaa5a9d53adc82ebd8b321bca4f"
version = "v15.1.1"
revision = "4e8cbbfb1aeab140cd0fa97fd16b64ee18c3ca6a"
version = "v19.1.0"
[[projects]]
branch = "master"
@@ -25,12 +27,15 @@
"autorest",
"autorest/adal",
"autorest/azure",
"autorest/azure/auth",
"autorest/date",
"autorest/to",
"autorest/validation"
"autorest/validation",
"logger",
"version"
]
revision = "eaa7994b2278094c904d31993d26f56324db3052"
version = "v10.8.1"
revision = "dd94e014aaf16d1df746762e392aa201c1b4c461"
version = "v10.15.0"
[[projects]]
name = "github.com/BurntSushi/toml"
@@ -238,6 +243,15 @@
revision = "1ee720e18fe98dceda6039bdd005ffbcb359d343"
version = "v0.5.6"
[[projects]]
branch = "master"
name = "github.com/docker/spdystream"
packages = [
".",
"spdy"
]
revision = "bc6354cbbc295e925e4c611ffe90c1f287ee54db"
[[projects]]
branch = "master"
name = "github.com/flynn/go-shlex"
@@ -391,6 +405,12 @@
revision = "53c1911da2b537f792e7cafcb446b05ffe33b996"
version = "v1.6.1"
[[projects]]
name = "github.com/gorilla/websocket"
packages = ["."]
revision = "ea4d1f681babbce9545c9c5f3d5194a789c89f5b"
version = "v1.2.0"
[[projects]]
branch = "master"
name = "github.com/hashicorp/hcl"
@@ -577,6 +597,12 @@
packages = ["specs-go"]
revision = "1c7c27d043c2a5e513a44084d2b10d77d1402b8c"
[[projects]]
name = "github.com/pborman/uuid"
packages = ["."]
revision = "e790cca94e6cc75c7064b1332e63811d4aae1a53"
version = "v1.1"
[[projects]]
name = "github.com/pelletier/go-toml"
packages = ["."]
@@ -756,7 +782,7 @@
"pkg/vsphere/session",
"pkg/vsphere/sys"
]
revision = "24e7742b481d328dc0d5b68c992750b7aef4550d"
revision = "0fd01769dd5f4077763f3426a830709a9e986f1e"
[[projects]]
branch = "master"
@@ -792,6 +818,8 @@
name = "golang.org/x/crypto"
packages = [
"nacl/secretbox",
"pkcs12",
"pkcs12/internal/rc2",
"poly1305",
"salsa20/salsa",
"ssh/terminal"
@@ -811,7 +839,8 @@
"internal/socks",
"internal/timeseries",
"proxy",
"trace"
"trace",
"websocket"
]
revision = "f73e4c9ed3b7ebdd5f699a16a880c2b1994e50dd"
@@ -942,6 +971,7 @@
"pkg/api/errors",
"pkg/api/meta",
"pkg/api/resource",
"pkg/apis/meta/internalversion",
"pkg/apis/meta/v1",
"pkg/apis/meta/v1/unstructured",
"pkg/apis/meta/v1beta1",
@@ -962,22 +992,36 @@
"pkg/util/clock",
"pkg/util/errors",
"pkg/util/framer",
"pkg/util/httpstream",
"pkg/util/httpstream/spdy",
"pkg/util/intstr",
"pkg/util/json",
"pkg/util/net",
"pkg/util/remotecommand",
"pkg/util/runtime",
"pkg/util/sets",
"pkg/util/uuid",
"pkg/util/validation",
"pkg/util/validation/field",
"pkg/util/wait",
"pkg/util/yaml",
"pkg/version",
"pkg/watch",
"third_party/forked/golang/netutil",
"third_party/forked/golang/reflect"
]
revision = "302974c03f7e50f16561ba237db776ab93594ef6"
version = "kubernetes-1.10.0"
[[projects]]
branch = "master"
name = "k8s.io/apiserver"
packages = [
"pkg/server/httplog",
"pkg/util/wsstream"
]
revision = "25e79651c7e569b0ebcd97affc0fe7f1ffcbee94"
[[projects]]
name = "k8s.io/client-go"
packages = [
@@ -1056,8 +1100,11 @@
"tools/clientcmd/api/v1",
"tools/metrics",
"tools/reference",
"tools/remotecommand",
"transport",
"transport/spdy",
"util/cert",
"util/exec",
"util/flowcontrol",
"util/homedir",
"util/integer"
@@ -1067,13 +1114,23 @@
[[projects]]
name = "k8s.io/kubernetes"
packages = ["pkg/kubelet/apis/cri/runtime/v1alpha2"]
packages = [
"pkg/apis/core",
"pkg/kubelet/apis/cri/runtime/v1alpha2",
"pkg/kubelet/server/remotecommand"
]
revision = "81753b10df112992bf51bbc2c2f85208aad78335"
version = "v1.10.2"
[[projects]]
branch = "master"
name = "k8s.io/utils"
packages = ["exec"]
revision = "045dc31ee5c40e8240241ce28dc24d7b56130373"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
inputs-digest = "8f3ca80656c580339bc7105912693cf126c4952c476e7052cbd9de4ef73d9e75"
inputs-digest = "92f9554609e1a532f5f4a2dd5f9e77ca4a1b342f6808b9423f961ce9dfc8095d"
solver-name = "gps-cdcl"
solver-version = 1

View File

@@ -57,7 +57,7 @@
[[constraint]]
name = "github.com/Azure/azure-sdk-for-go"
version = "15.1.1"
version = "19.1.0"
[[constraint]]
name = "github.com/lawrencegripper/pod2docker"

View File

@@ -49,7 +49,7 @@ type VicProvider struct {
client *client.PortLayer
imageStore proxy.ImageStore
isolationProxy proxy.IsolationProxy
systemProxy vicproxy.VicSystemProxy
systemProxy *vicproxy.VicSystemProxy
}
const (

View File

@@ -0,0 +1,233 @@
// +build go1.9
// Copyright 2018 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This code was auto-generated by:
// github.com/Azure/azure-sdk-for-go/tools/profileBuilder
package servicefabricmesh
import original "github.com/Azure/azure-sdk-for-go/services/preview/servicefabricmesh/mgmt/2018-07-01-preview/servicefabricmesh"
type ApplicationClient = original.ApplicationClient
const (
DefaultBaseURI = original.DefaultBaseURI
)
type BaseClient = original.BaseClient
type CodePackageClient = original.CodePackageClient
type ApplicationResourceStatus = original.ApplicationResourceStatus
const (
Creating ApplicationResourceStatus = original.Creating
Deleting ApplicationResourceStatus = original.Deleting
Failed ApplicationResourceStatus = original.Failed
Invalid ApplicationResourceStatus = original.Invalid
Ready ApplicationResourceStatus = original.Ready
Upgrading ApplicationResourceStatus = original.Upgrading
)
type DiagnosticsSinkKind = original.DiagnosticsSinkKind
const (
DiagnosticsSinkKindAzureInternalMonitoringPipeline DiagnosticsSinkKind = original.DiagnosticsSinkKindAzureInternalMonitoringPipeline
DiagnosticsSinkKindInvalid DiagnosticsSinkKind = original.DiagnosticsSinkKindInvalid
)
type HealthState = original.HealthState
const (
HealthStateError HealthState = original.HealthStateError
HealthStateInvalid HealthState = original.HealthStateInvalid
HealthStateOk HealthState = original.HealthStateOk
HealthStateUnknown HealthState = original.HealthStateUnknown
HealthStateWarning HealthState = original.HealthStateWarning
)
type IngressQoSLevel = original.IngressQoSLevel
const (
Bronze IngressQoSLevel = original.Bronze
)
type Kind = original.Kind
const (
KindAzureInternalMonitoringPipeline Kind = original.KindAzureInternalMonitoringPipeline
KindDiagnosticsSinkProperties Kind = original.KindDiagnosticsSinkProperties
)
type OperatingSystemTypes = original.OperatingSystemTypes
const (
Linux OperatingSystemTypes = original.Linux
Windows OperatingSystemTypes = original.Windows
)
type ServiceResourceStatus = original.ServiceResourceStatus
const (
ServiceResourceStatusActive ServiceResourceStatus = original.ServiceResourceStatusActive
ServiceResourceStatusCreating ServiceResourceStatus = original.ServiceResourceStatusCreating
ServiceResourceStatusDeleting ServiceResourceStatus = original.ServiceResourceStatusDeleting
ServiceResourceStatusFailed ServiceResourceStatus = original.ServiceResourceStatusFailed
ServiceResourceStatusUnknown ServiceResourceStatus = original.ServiceResourceStatusUnknown
ServiceResourceStatusUpgrading ServiceResourceStatus = original.ServiceResourceStatusUpgrading
)
type ApplicationProperties = original.ApplicationProperties
type ApplicationResourceDescription = original.ApplicationResourceDescription
type ApplicationResourceDescriptionList = original.ApplicationResourceDescriptionList
type ApplicationResourceDescriptionListIterator = original.ApplicationResourceDescriptionListIterator
type ApplicationResourceDescriptionListPage = original.ApplicationResourceDescriptionListPage
type ApplicationResourceProperties = original.ApplicationResourceProperties
type AvailableOperationDisplay = original.AvailableOperationDisplay
type AzureInternalMonitoringPipelineSinkDescription = original.AzureInternalMonitoringPipelineSinkDescription
type ContainerCodePackageProperties = original.ContainerCodePackageProperties
type ContainerEvent = original.ContainerEvent
type ContainerInstanceView = original.ContainerInstanceView
type ContainerLabel = original.ContainerLabel
type ContainerLogs = original.ContainerLogs
type ContainerState = original.ContainerState
type ContainerVolume = original.ContainerVolume
type DiagnosticsDescription = original.DiagnosticsDescription
type DiagnosticsRef = original.DiagnosticsRef
type BasicDiagnosticsSinkProperties = original.BasicDiagnosticsSinkProperties
type DiagnosticsSinkProperties = original.DiagnosticsSinkProperties
type EndpointProperties = original.EndpointProperties
type EnvironmentVariable = original.EnvironmentVariable
type ErrorModel = original.ErrorModel
type ImageRegistryCredential = original.ImageRegistryCredential
type IngressConfig = original.IngressConfig
type Layer4IngressConfig = original.Layer4IngressConfig
type ManagedProxyResource = original.ManagedProxyResource
type NetworkProperties = original.NetworkProperties
type NetworkRef = original.NetworkRef
type NetworkResourceDescription = original.NetworkResourceDescription
type NetworkResourceDescriptionList = original.NetworkResourceDescriptionList
type NetworkResourceDescriptionListIterator = original.NetworkResourceDescriptionListIterator
type NetworkResourceDescriptionListPage = original.NetworkResourceDescriptionListPage
type NetworkResourceProperties = original.NetworkResourceProperties
type OperationListResult = original.OperationListResult
type OperationListResultIterator = original.OperationListResultIterator
type OperationListResultPage = original.OperationListResultPage
type OperationResult = original.OperationResult
type ProvisionedResourceProperties = original.ProvisionedResourceProperties
type ProxyResource = original.ProxyResource
type Resource = original.Resource
type ResourceLimits = original.ResourceLimits
type ResourceRequests = original.ResourceRequests
type ResourceRequirements = original.ResourceRequirements
type ServiceList = original.ServiceList
type ServiceListIterator = original.ServiceListIterator
type ServiceListPage = original.ServiceListPage
type ServiceReplicaDescription = original.ServiceReplicaDescription
type ServiceReplicaList = original.ServiceReplicaList
type ServiceReplicaListIterator = original.ServiceReplicaListIterator
type ServiceReplicaListPage = original.ServiceReplicaListPage
type ServiceReplicaProperties = original.ServiceReplicaProperties
type ServiceResourceDescription = original.ServiceResourceDescription
type ServiceResourceProperties = original.ServiceResourceProperties
type Setting = original.Setting
type TrackedResource = original.TrackedResource
type VolumeProperties = original.VolumeProperties
type VolumeProviderParametersAzureFile = original.VolumeProviderParametersAzureFile
type VolumeResourceDescription = original.VolumeResourceDescription
type VolumeResourceDescriptionList = original.VolumeResourceDescriptionList
type VolumeResourceDescriptionListIterator = original.VolumeResourceDescriptionListIterator
type VolumeResourceDescriptionListPage = original.VolumeResourceDescriptionListPage
type VolumeResourceProperties = original.VolumeResourceProperties
type NetworkClient = original.NetworkClient
type OperationsClient = original.OperationsClient
type ReplicaClient = original.ReplicaClient
type ServiceClient = original.ServiceClient
type VolumeClient = original.VolumeClient
func NewApplicationClient(subscriptionID string) ApplicationClient {
return original.NewApplicationClient(subscriptionID)
}
func NewApplicationClientWithBaseURI(baseURI string, subscriptionID string) ApplicationClient {
return original.NewApplicationClientWithBaseURI(baseURI, subscriptionID)
}
func New(subscriptionID string) BaseClient {
return original.New(subscriptionID)
}
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {
return original.NewWithBaseURI(baseURI, subscriptionID)
}
func NewCodePackageClient(subscriptionID string) CodePackageClient {
return original.NewCodePackageClient(subscriptionID)
}
func NewCodePackageClientWithBaseURI(baseURI string, subscriptionID string) CodePackageClient {
return original.NewCodePackageClientWithBaseURI(baseURI, subscriptionID)
}
func PossibleApplicationResourceStatusValues() []ApplicationResourceStatus {
return original.PossibleApplicationResourceStatusValues()
}
func PossibleDiagnosticsSinkKindValues() []DiagnosticsSinkKind {
return original.PossibleDiagnosticsSinkKindValues()
}
func PossibleHealthStateValues() []HealthState {
return original.PossibleHealthStateValues()
}
func PossibleIngressQoSLevelValues() []IngressQoSLevel {
return original.PossibleIngressQoSLevelValues()
}
func PossibleKindValues() []Kind {
return original.PossibleKindValues()
}
func PossibleOperatingSystemTypesValues() []OperatingSystemTypes {
return original.PossibleOperatingSystemTypesValues()
}
func PossibleServiceResourceStatusValues() []ServiceResourceStatus {
return original.PossibleServiceResourceStatusValues()
}
func NewNetworkClient(subscriptionID string) NetworkClient {
return original.NewNetworkClient(subscriptionID)
}
func NewNetworkClientWithBaseURI(baseURI string, subscriptionID string) NetworkClient {
return original.NewNetworkClientWithBaseURI(baseURI, subscriptionID)
}
func NewOperationsClient(subscriptionID string) OperationsClient {
return original.NewOperationsClient(subscriptionID)
}
func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {
return original.NewOperationsClientWithBaseURI(baseURI, subscriptionID)
}
func NewReplicaClient(subscriptionID string) ReplicaClient {
return original.NewReplicaClient(subscriptionID)
}
func NewReplicaClientWithBaseURI(baseURI string, subscriptionID string) ReplicaClient {
return original.NewReplicaClientWithBaseURI(baseURI, subscriptionID)
}
func NewServiceClient(subscriptionID string) ServiceClient {
return original.NewServiceClient(subscriptionID)
}
func NewServiceClientWithBaseURI(baseURI string, subscriptionID string) ServiceClient {
return original.NewServiceClientWithBaseURI(baseURI, subscriptionID)
}
func UserAgent() string {
return original.UserAgent() + " profiles/preview"
}
func Version() string {
return original.Version()
}
func NewVolumeClient(subscriptionID string) VolumeClient {
return original.NewVolumeClient(subscriptionID)
}
func NewVolumeClientWithBaseURI(baseURI string, subscriptionID string) VolumeClient {
return original.NewVolumeClientWithBaseURI(baseURI, subscriptionID)
}

View File

@@ -0,0 +1,439 @@
package servicefabricmesh
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// ApplicationClient is the service Fabric Mesh Management Client
type ApplicationClient struct {
BaseClient
}
// NewApplicationClient creates an instance of the ApplicationClient client.
func NewApplicationClient(subscriptionID string) ApplicationClient {
return NewApplicationClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewApplicationClientWithBaseURI creates an instance of the ApplicationClient client.
func NewApplicationClientWithBaseURI(baseURI string, subscriptionID string) ApplicationClient {
return ApplicationClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Create creates an application resource with the specified name and description. If an application with the same name
// already exists, then its description is updated to the one indicated in this request.
//
// Use network resources to provide public connectivity to the services of an application.
// Parameters:
// resourceGroupName - azure resource group name
// applicationName - the identity of the application.
// applicationResourceDescription - description for creating an application resource.
func (client ApplicationClient) Create(ctx context.Context, resourceGroupName string, applicationName string, applicationResourceDescription ApplicationResourceDescription) (result ApplicationResourceDescription, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: applicationResourceDescription,
Constraints: []validation.Constraint{{Target: "applicationResourceDescription.ApplicationResourceProperties", Name: validation.Null, Rule: true, Chain: nil}}}}); err != nil {
return result, validation.NewError("servicefabricmesh.ApplicationClient", "Create", err.Error())
}
req, err := client.CreatePreparer(ctx, resourceGroupName, applicationName, applicationResourceDescription)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "Create", nil, "Failure preparing request")
return
}
resp, err := client.CreateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "Create", resp, "Failure sending request")
return
}
result, err = client.CreateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "Create", resp, "Failure responding to request")
}
return
}
// CreatePreparer prepares the Create request.
func (client ApplicationClient) CreatePreparer(ctx context.Context, resourceGroupName string, applicationName string, applicationResourceDescription ApplicationResourceDescription) (*http.Request, error) {
pathParameters := map[string]interface{}{
"applicationName": applicationName,
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/applications/{applicationName}", pathParameters),
autorest.WithJSON(applicationResourceDescription),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateSender sends the Create request. The method will close the
// http.Response Body if it receives an error.
func (client ApplicationClient) CreateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// CreateResponder handles the response to the Create request. The method always
// closes the http.Response Body.
func (client ApplicationClient) CreateResponder(resp *http.Response) (result ApplicationResourceDescription, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes the application resource identified by the name.
// Parameters:
// resourceGroupName - azure resource group name
// applicationName - the identity of the application.
func (client ApplicationClient) Delete(ctx context.Context, resourceGroupName string, applicationName string) (result autorest.Response, err error) {
req, err := client.DeletePreparer(ctx, resourceGroupName, applicationName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "Delete", resp, "Failure responding to request")
}
return
}
// DeletePreparer prepares the Delete request.
func (client ApplicationClient) DeletePreparer(ctx context.Context, resourceGroupName string, applicationName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"applicationName": applicationName,
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/applications/{applicationName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client ApplicationClient) DeleteSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client ApplicationClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get gets the information about the application resource with a given name. The information includes the information
// about the application's services and other runtime properties.
// Parameters:
// resourceGroupName - azure resource group name
// applicationName - the identity of the application.
func (client ApplicationClient) Get(ctx context.Context, resourceGroupName string, applicationName string) (result ApplicationResourceDescription, err error) {
req, err := client.GetPreparer(ctx, resourceGroupName, applicationName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client ApplicationClient) GetPreparer(ctx context.Context, resourceGroupName string, applicationName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"applicationName": applicationName,
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/applications/{applicationName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client ApplicationClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client ApplicationClient) GetResponder(resp *http.Response) (result ApplicationResourceDescription, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListByResourceGroup gets the information about all application resources in a given resource group. The information
// includes the information about the application's services and other runtime properties.
// Parameters:
// resourceGroupName - azure resource group name
func (client ApplicationClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ApplicationResourceDescriptionListPage, err error) {
result.fn = client.listByResourceGroupNextResults
req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "ListByResourceGroup", nil, "Failure preparing request")
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.ardl.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "ListByResourceGroup", resp, "Failure sending request")
return
}
result.ardl, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "ListByResourceGroup", resp, "Failure responding to request")
}
return
}
// ListByResourceGroupPreparer prepares the ListByResourceGroup request.
func (client ApplicationClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/applications", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the
// http.Response Body if it receives an error.
func (client ApplicationClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always
// closes the http.Response Body.
func (client ApplicationClient) ListByResourceGroupResponder(resp *http.Response) (result ApplicationResourceDescriptionList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByResourceGroupNextResults retrieves the next set of results, if any.
func (client ApplicationClient) listByResourceGroupNextResults(lastResults ApplicationResourceDescriptionList) (result ApplicationResourceDescriptionList, err error) {
req, err := lastResults.applicationResourceDescriptionListPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "listByResourceGroupNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required.
func (client ApplicationClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result ApplicationResourceDescriptionListIterator, err error) {
result.page, err = client.ListByResourceGroup(ctx, resourceGroupName)
return
}
// ListBySubscription gets the information about all application resources in a given subscription. The information
// includes the information about the application's services and other runtime properties.
func (client ApplicationClient) ListBySubscription(ctx context.Context) (result ApplicationResourceDescriptionListPage, err error) {
result.fn = client.listBySubscriptionNextResults
req, err := client.ListBySubscriptionPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "ListBySubscription", nil, "Failure preparing request")
return
}
resp, err := client.ListBySubscriptionSender(req)
if err != nil {
result.ardl.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "ListBySubscription", resp, "Failure sending request")
return
}
result.ardl, err = client.ListBySubscriptionResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "ListBySubscription", resp, "Failure responding to request")
}
return
}
// ListBySubscriptionPreparer prepares the ListBySubscription request.
func (client ApplicationClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ServiceFabricMesh/applications", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListBySubscriptionSender sends the ListBySubscription request. The method will close the
// http.Response Body if it receives an error.
func (client ApplicationClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always
// closes the http.Response Body.
func (client ApplicationClient) ListBySubscriptionResponder(resp *http.Response) (result ApplicationResourceDescriptionList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listBySubscriptionNextResults retrieves the next set of results, if any.
func (client ApplicationClient) listBySubscriptionNextResults(lastResults ApplicationResourceDescriptionList) (result ApplicationResourceDescriptionList, err error) {
req, err := lastResults.applicationResourceDescriptionListPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListBySubscriptionSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "listBySubscriptionNextResults", resp, "Failure sending next results request")
}
result, err = client.ListBySubscriptionResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ApplicationClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request")
}
return
}
// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required.
func (client ApplicationClient) ListBySubscriptionComplete(ctx context.Context) (result ApplicationResourceDescriptionListIterator, err error) {
result.page, err = client.ListBySubscription(ctx)
return
}

View File

@@ -0,0 +1,51 @@
// Package servicefabricmesh implements the Azure ARM Servicefabricmesh service API version 2018-07-01-preview.
//
// Service Fabric Mesh Management Client
package servicefabricmesh
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"github.com/Azure/go-autorest/autorest"
)
const (
// DefaultBaseURI is the default URI used for the service Servicefabricmesh
DefaultBaseURI = "https://management.azure.com"
)
// BaseClient is the base client for Servicefabricmesh.
type BaseClient struct {
autorest.Client
BaseURI string
SubscriptionID string
}
// New creates an instance of the BaseClient client.
func New(subscriptionID string) BaseClient {
return NewWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewWithBaseURI creates an instance of the BaseClient client.
func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient {
return BaseClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
SubscriptionID: subscriptionID,
}
}

View File

@@ -0,0 +1,117 @@
package servicefabricmesh
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// CodePackageClient is the service Fabric Mesh Management Client
type CodePackageClient struct {
BaseClient
}
// NewCodePackageClient creates an instance of the CodePackageClient client.
func NewCodePackageClient(subscriptionID string) CodePackageClient {
return NewCodePackageClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewCodePackageClientWithBaseURI creates an instance of the CodePackageClient client.
func NewCodePackageClientWithBaseURI(baseURI string, subscriptionID string) CodePackageClient {
return CodePackageClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// GetContainerLog get the logs for the container of a given code package of an application.
// Parameters:
// resourceGroupName - azure resource group name
// applicationName - the identity of the application.
// serviceName - the identity of the service.
// replicaName - the identity of the service replica.
// codePackageName - the name of the code package.
// tail - number of lines to show from the end of the logs. Default is 100.
func (client CodePackageClient) GetContainerLog(ctx context.Context, resourceGroupName string, applicationName string, serviceName string, replicaName string, codePackageName string, tail *int32) (result ContainerLogs, err error) {
req, err := client.GetContainerLogPreparer(ctx, resourceGroupName, applicationName, serviceName, replicaName, codePackageName, tail)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.CodePackageClient", "GetContainerLog", nil, "Failure preparing request")
return
}
resp, err := client.GetContainerLogSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.CodePackageClient", "GetContainerLog", resp, "Failure sending request")
return
}
result, err = client.GetContainerLogResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.CodePackageClient", "GetContainerLog", resp, "Failure responding to request")
}
return
}
// GetContainerLogPreparer prepares the GetContainerLog request.
func (client CodePackageClient) GetContainerLogPreparer(ctx context.Context, resourceGroupName string, applicationName string, serviceName string, replicaName string, codePackageName string, tail *int32) (*http.Request, error) {
pathParameters := map[string]interface{}{
"applicationName": applicationName,
"codePackageName": codePackageName,
"replicaName": replicaName,
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"serviceName": serviceName,
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
if tail != nil {
queryParameters["tail"] = autorest.Encode("query", *tail)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/applications/{applicationName}/services/{serviceName}/replicas/{replicaName}/codePackages/{codePackageName}/logs", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetContainerLogSender sends the GetContainerLog request. The method will close the
// http.Response Body if it receives an error.
func (client CodePackageClient) GetContainerLogSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetContainerLogResponder handles the response to the GetContainerLog request. The method always
// closes the http.Response Body.
func (client CodePackageClient) GetContainerLogResponder(resp *http.Response) (result ContainerLogs, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}

View File

@@ -0,0 +1,441 @@
package servicefabricmesh
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// NetworkClient is the service Fabric Mesh Management Client
type NetworkClient struct {
BaseClient
}
// NewNetworkClient creates an instance of the NetworkClient client.
func NewNetworkClient(subscriptionID string) NetworkClient {
return NewNetworkClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewNetworkClientWithBaseURI creates an instance of the NetworkClient client.
func NewNetworkClientWithBaseURI(baseURI string, subscriptionID string) NetworkClient {
return NetworkClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Create creates a network resource with the specified name and description. If a network with the same name already
// exists, then its description is updated to the one indicated in this request.
//
// Use network resources to create private network and configure public connectivity for services within your
// application.
// Parameters:
// resourceGroupName - azure resource group name
// networkName - the identity of the network.
// networkResourceDescription - description for creating a network resource.
func (client NetworkClient) Create(ctx context.Context, resourceGroupName string, networkName string, networkResourceDescription NetworkResourceDescription) (result NetworkResourceDescription, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: networkResourceDescription,
Constraints: []validation.Constraint{{Target: "networkResourceDescription.NetworkResourceProperties", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "networkResourceDescription.NetworkResourceProperties.AddressPrefix", Name: validation.Null, Rule: true, Chain: nil}}}}}}); err != nil {
return result, validation.NewError("servicefabricmesh.NetworkClient", "Create", err.Error())
}
req, err := client.CreatePreparer(ctx, resourceGroupName, networkName, networkResourceDescription)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "Create", nil, "Failure preparing request")
return
}
resp, err := client.CreateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "Create", resp, "Failure sending request")
return
}
result, err = client.CreateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "Create", resp, "Failure responding to request")
}
return
}
// CreatePreparer prepares the Create request.
func (client NetworkClient) CreatePreparer(ctx context.Context, resourceGroupName string, networkName string, networkResourceDescription NetworkResourceDescription) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkName": networkName,
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/networks/{networkName}", pathParameters),
autorest.WithJSON(networkResourceDescription),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateSender sends the Create request. The method will close the
// http.Response Body if it receives an error.
func (client NetworkClient) CreateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// CreateResponder handles the response to the Create request. The method always
// closes the http.Response Body.
func (client NetworkClient) CreateResponder(resp *http.Response) (result NetworkResourceDescription, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes the network resource identified by the name.
// Parameters:
// resourceGroupName - azure resource group name
// networkName - the identity of the network.
func (client NetworkClient) Delete(ctx context.Context, resourceGroupName string, networkName string) (result autorest.Response, err error) {
req, err := client.DeletePreparer(ctx, resourceGroupName, networkName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "Delete", resp, "Failure responding to request")
}
return
}
// DeletePreparer prepares the Delete request.
func (client NetworkClient) DeletePreparer(ctx context.Context, resourceGroupName string, networkName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkName": networkName,
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/networks/{networkName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client NetworkClient) DeleteSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client NetworkClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get gets the information about the network resource with a given name. This information includes the network
// description and other runtime information.
// Parameters:
// resourceGroupName - azure resource group name
// networkName - the identity of the network.
func (client NetworkClient) Get(ctx context.Context, resourceGroupName string, networkName string) (result NetworkResourceDescription, err error) {
req, err := client.GetPreparer(ctx, resourceGroupName, networkName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client NetworkClient) GetPreparer(ctx context.Context, resourceGroupName string, networkName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"networkName": networkName,
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/networks/{networkName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client NetworkClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client NetworkClient) GetResponder(resp *http.Response) (result NetworkResourceDescription, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListByResourceGroup gets the information about all network resources in a given resource group. The information
// includes the network description and other runtime properties.
// Parameters:
// resourceGroupName - azure resource group name
func (client NetworkClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result NetworkResourceDescriptionListPage, err error) {
result.fn = client.listByResourceGroupNextResults
req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "ListByResourceGroup", nil, "Failure preparing request")
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.nrdl.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "ListByResourceGroup", resp, "Failure sending request")
return
}
result.nrdl, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "ListByResourceGroup", resp, "Failure responding to request")
}
return
}
// ListByResourceGroupPreparer prepares the ListByResourceGroup request.
func (client NetworkClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/networks", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the
// http.Response Body if it receives an error.
func (client NetworkClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always
// closes the http.Response Body.
func (client NetworkClient) ListByResourceGroupResponder(resp *http.Response) (result NetworkResourceDescriptionList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByResourceGroupNextResults retrieves the next set of results, if any.
func (client NetworkClient) listByResourceGroupNextResults(lastResults NetworkResourceDescriptionList) (result NetworkResourceDescriptionList, err error) {
req, err := lastResults.networkResourceDescriptionListPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "listByResourceGroupNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required.
func (client NetworkClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result NetworkResourceDescriptionListIterator, err error) {
result.page, err = client.ListByResourceGroup(ctx, resourceGroupName)
return
}
// ListBySubscription gets the information about all network resources in a given subscription. The information
// includes the network description and other runtime properties.
func (client NetworkClient) ListBySubscription(ctx context.Context) (result NetworkResourceDescriptionListPage, err error) {
result.fn = client.listBySubscriptionNextResults
req, err := client.ListBySubscriptionPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "ListBySubscription", nil, "Failure preparing request")
return
}
resp, err := client.ListBySubscriptionSender(req)
if err != nil {
result.nrdl.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "ListBySubscription", resp, "Failure sending request")
return
}
result.nrdl, err = client.ListBySubscriptionResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "ListBySubscription", resp, "Failure responding to request")
}
return
}
// ListBySubscriptionPreparer prepares the ListBySubscription request.
func (client NetworkClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ServiceFabricMesh/networks", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListBySubscriptionSender sends the ListBySubscription request. The method will close the
// http.Response Body if it receives an error.
func (client NetworkClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always
// closes the http.Response Body.
func (client NetworkClient) ListBySubscriptionResponder(resp *http.Response) (result NetworkResourceDescriptionList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listBySubscriptionNextResults retrieves the next set of results, if any.
func (client NetworkClient) listBySubscriptionNextResults(lastResults NetworkResourceDescriptionList) (result NetworkResourceDescriptionList, err error) {
req, err := lastResults.networkResourceDescriptionListPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListBySubscriptionSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "listBySubscriptionNextResults", resp, "Failure sending next results request")
}
result, err = client.ListBySubscriptionResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.NetworkClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request")
}
return
}
// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required.
func (client NetworkClient) ListBySubscriptionComplete(ctx context.Context) (result NetworkResourceDescriptionListIterator, err error) {
result.page, err = client.ListBySubscription(ctx)
return
}

View File

@@ -0,0 +1,126 @@
package servicefabricmesh
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// OperationsClient is the service Fabric Mesh Management Client
type OperationsClient struct {
BaseClient
}
// NewOperationsClient creates an instance of the OperationsClient client.
func NewOperationsClient(subscriptionID string) OperationsClient {
return NewOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewOperationsClientWithBaseURI creates an instance of the OperationsClient client.
func NewOperationsClientWithBaseURI(baseURI string, subscriptionID string) OperationsClient {
return OperationsClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// List lists all the available operations provided by Service Fabric SeaBreeze resource provider.
func (client OperationsClient) List(ctx context.Context) (result OperationListResultPage, err error) {
result.fn = client.listNextResults
req, err := client.ListPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.OperationsClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.olr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.OperationsClient", "List", resp, "Failure sending request")
return
}
result.olr, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.OperationsClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client OperationsClient) ListPreparer(ctx context.Context) (*http.Request, error) {
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/providers/Microsoft.ServiceFabricMesh/operations"),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client OperationsClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client OperationsClient) ListResponder(resp *http.Response) (result OperationListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listNextResults retrieves the next set of results, if any.
func (client OperationsClient) listNextResults(lastResults OperationListResult) (result OperationListResult, err error) {
req, err := lastResults.operationListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "servicefabricmesh.OperationsClient", "listNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "servicefabricmesh.OperationsClient", "listNextResults", resp, "Failure sending next results request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.OperationsClient", "listNextResults", resp, "Failure responding to next results request")
}
return
}
// ListComplete enumerates all values, automatically crossing page boundaries as required.
func (client OperationsClient) ListComplete(ctx context.Context) (result OperationListResultIterator, err error) {
result.page, err = client.List(ctx)
return
}

View File

@@ -0,0 +1,210 @@
package servicefabricmesh
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// ReplicaClient is the service Fabric Mesh Management Client
type ReplicaClient struct {
BaseClient
}
// NewReplicaClient creates an instance of the ReplicaClient client.
func NewReplicaClient(subscriptionID string) ReplicaClient {
return NewReplicaClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewReplicaClientWithBaseURI creates an instance of the ReplicaClient client.
func NewReplicaClientWithBaseURI(baseURI string, subscriptionID string) ReplicaClient {
return ReplicaClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Get gets the information about the specified replica of a given service of an application. The information includes
// the runtime properties of the replica instance.
// Parameters:
// resourceGroupName - azure resource group name
// applicationName - the identity of the application.
// serviceName - the identity of the service.
// replicaName - the identity of the service replica.
func (client ReplicaClient) Get(ctx context.Context, resourceGroupName string, applicationName string, serviceName string, replicaName string) (result ServiceReplicaDescription, err error) {
req, err := client.GetPreparer(ctx, resourceGroupName, applicationName, serviceName, replicaName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ReplicaClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.ReplicaClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ReplicaClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client ReplicaClient) GetPreparer(ctx context.Context, resourceGroupName string, applicationName string, serviceName string, replicaName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"applicationName": applicationName,
"replicaName": replicaName,
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"serviceName": serviceName,
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/applications/{applicationName}/services/{serviceName}/replicas/{replicaName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client ReplicaClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client ReplicaClient) GetResponder(resp *http.Response) (result ServiceReplicaDescription, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListByServiceName gets the information about all replicas of a given service of an application. The information
// includes the runtime properties of the replica instance.
// Parameters:
// resourceGroupName - azure resource group name
// applicationName - the identity of the application.
// serviceName - the identity of the service.
func (client ReplicaClient) ListByServiceName(ctx context.Context, resourceGroupName string, applicationName string, serviceName string) (result ServiceReplicaListPage, err error) {
result.fn = client.listByServiceNameNextResults
req, err := client.ListByServiceNamePreparer(ctx, resourceGroupName, applicationName, serviceName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ReplicaClient", "ListByServiceName", nil, "Failure preparing request")
return
}
resp, err := client.ListByServiceNameSender(req)
if err != nil {
result.srl.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.ReplicaClient", "ListByServiceName", resp, "Failure sending request")
return
}
result.srl, err = client.ListByServiceNameResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ReplicaClient", "ListByServiceName", resp, "Failure responding to request")
}
return
}
// ListByServiceNamePreparer prepares the ListByServiceName request.
func (client ReplicaClient) ListByServiceNamePreparer(ctx context.Context, resourceGroupName string, applicationName string, serviceName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"applicationName": applicationName,
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"serviceName": serviceName,
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/applications/{applicationName}/services/{serviceName}/replicas", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByServiceNameSender sends the ListByServiceName request. The method will close the
// http.Response Body if it receives an error.
func (client ReplicaClient) ListByServiceNameSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListByServiceNameResponder handles the response to the ListByServiceName request. The method always
// closes the http.Response Body.
func (client ReplicaClient) ListByServiceNameResponder(resp *http.Response) (result ServiceReplicaList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByServiceNameNextResults retrieves the next set of results, if any.
func (client ReplicaClient) listByServiceNameNextResults(lastResults ServiceReplicaList) (result ServiceReplicaList, err error) {
req, err := lastResults.serviceReplicaListPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "servicefabricmesh.ReplicaClient", "listByServiceNameNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByServiceNameSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "servicefabricmesh.ReplicaClient", "listByServiceNameNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByServiceNameResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ReplicaClient", "listByServiceNameNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByServiceNameComplete enumerates all values, automatically crossing page boundaries as required.
func (client ReplicaClient) ListByServiceNameComplete(ctx context.Context, resourceGroupName string, applicationName string, serviceName string) (result ServiceReplicaListIterator, err error) {
result.page, err = client.ListByServiceName(ctx, resourceGroupName, applicationName, serviceName)
return
}

View File

@@ -0,0 +1,205 @@
package servicefabricmesh
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// ServiceClient is the service Fabric Mesh Management Client
type ServiceClient struct {
BaseClient
}
// NewServiceClient creates an instance of the ServiceClient client.
func NewServiceClient(subscriptionID string) ServiceClient {
return NewServiceClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewServiceClientWithBaseURI creates an instance of the ServiceClient client.
func NewServiceClientWithBaseURI(baseURI string, subscriptionID string) ServiceClient {
return ServiceClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Get the operation returns the properties of the service.
// Parameters:
// resourceGroupName - azure resource group name
// applicationName - the identity of the application.
// serviceName - the identity of the service.
func (client ServiceClient) Get(ctx context.Context, resourceGroupName string, applicationName string, serviceName string) (result ServiceResourceDescription, err error) {
req, err := client.GetPreparer(ctx, resourceGroupName, applicationName, serviceName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ServiceClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.ServiceClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ServiceClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client ServiceClient) GetPreparer(ctx context.Context, resourceGroupName string, applicationName string, serviceName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"applicationName": applicationName,
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"serviceName": serviceName,
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/applications/{applicationName}/services/{serviceName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client ServiceClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client ServiceClient) GetResponder(resp *http.Response) (result ServiceResourceDescription, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListByApplicationName gets the information about all services of a given service of an application. The information
// includes the runtime properties of the service instance.
// Parameters:
// resourceGroupName - azure resource group name
// applicationName - the identity of the application.
func (client ServiceClient) ListByApplicationName(ctx context.Context, resourceGroupName string, applicationName string) (result ServiceListPage, err error) {
result.fn = client.listByApplicationNameNextResults
req, err := client.ListByApplicationNamePreparer(ctx, resourceGroupName, applicationName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ServiceClient", "ListByApplicationName", nil, "Failure preparing request")
return
}
resp, err := client.ListByApplicationNameSender(req)
if err != nil {
result.sl.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.ServiceClient", "ListByApplicationName", resp, "Failure sending request")
return
}
result.sl, err = client.ListByApplicationNameResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ServiceClient", "ListByApplicationName", resp, "Failure responding to request")
}
return
}
// ListByApplicationNamePreparer prepares the ListByApplicationName request.
func (client ServiceClient) ListByApplicationNamePreparer(ctx context.Context, resourceGroupName string, applicationName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"applicationName": applicationName,
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/applications/{applicationName}/services", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByApplicationNameSender sends the ListByApplicationName request. The method will close the
// http.Response Body if it receives an error.
func (client ServiceClient) ListByApplicationNameSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListByApplicationNameResponder handles the response to the ListByApplicationName request. The method always
// closes the http.Response Body.
func (client ServiceClient) ListByApplicationNameResponder(resp *http.Response) (result ServiceList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByApplicationNameNextResults retrieves the next set of results, if any.
func (client ServiceClient) listByApplicationNameNextResults(lastResults ServiceList) (result ServiceList, err error) {
req, err := lastResults.serviceListPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "servicefabricmesh.ServiceClient", "listByApplicationNameNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByApplicationNameSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "servicefabricmesh.ServiceClient", "listByApplicationNameNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByApplicationNameResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.ServiceClient", "listByApplicationNameNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByApplicationNameComplete enumerates all values, automatically crossing page boundaries as required.
func (client ServiceClient) ListByApplicationNameComplete(ctx context.Context, resourceGroupName string, applicationName string) (result ServiceListIterator, err error) {
result.page, err = client.ListByApplicationName(ctx, resourceGroupName, applicationName)
return
}

View File

@@ -0,0 +1,30 @@
package servicefabricmesh
import "github.com/Azure/azure-sdk-for-go/version"
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
return "Azure-SDK-For-Go/" + version.Number + " servicefabricmesh/2018-07-01-preview"
}
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return version.Number
}

View File

@@ -0,0 +1,443 @@
package servicefabricmesh
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// VolumeClient is the service Fabric Mesh Management Client
type VolumeClient struct {
BaseClient
}
// NewVolumeClient creates an instance of the VolumeClient client.
func NewVolumeClient(subscriptionID string) VolumeClient {
return NewVolumeClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewVolumeClientWithBaseURI creates an instance of the VolumeClient client.
func NewVolumeClientWithBaseURI(baseURI string, subscriptionID string) VolumeClient {
return VolumeClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// Create creates a volume resource with the specified name and description. If a volume with the same name already
// exists, then its description is updated to the one indicated in this request.
// Parameters:
// resourceGroupName - azure resource group name
// volumeName - the identity of the volume.
// volumeResourceDescription - description for creating a volume resource.
func (client VolumeClient) Create(ctx context.Context, resourceGroupName string, volumeName string, volumeResourceDescription VolumeResourceDescription) (result VolumeResourceDescription, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: volumeResourceDescription,
Constraints: []validation.Constraint{{Target: "volumeResourceDescription.VolumeResourceProperties", Name: validation.Null, Rule: true,
Chain: []validation.Constraint{{Target: "volumeResourceDescription.VolumeResourceProperties.Provider", Name: validation.Null, Rule: true, Chain: nil},
{Target: "volumeResourceDescription.VolumeResourceProperties.AzureFileParameters", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "volumeResourceDescription.VolumeResourceProperties.AzureFileParameters.AccountName", Name: validation.Null, Rule: true, Chain: nil},
{Target: "volumeResourceDescription.VolumeResourceProperties.AzureFileParameters.ShareName", Name: validation.Null, Rule: true, Chain: nil},
}},
}}}}}); err != nil {
return result, validation.NewError("servicefabricmesh.VolumeClient", "Create", err.Error())
}
req, err := client.CreatePreparer(ctx, resourceGroupName, volumeName, volumeResourceDescription)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "Create", nil, "Failure preparing request")
return
}
resp, err := client.CreateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "Create", resp, "Failure sending request")
return
}
result, err = client.CreateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "Create", resp, "Failure responding to request")
}
return
}
// CreatePreparer prepares the Create request.
func (client VolumeClient) CreatePreparer(ctx context.Context, resourceGroupName string, volumeName string, volumeResourceDescription VolumeResourceDescription) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"volumeName": volumeName,
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/volumes/{volumeName}", pathParameters),
autorest.WithJSON(volumeResourceDescription),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateSender sends the Create request. The method will close the
// http.Response Body if it receives an error.
func (client VolumeClient) CreateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// CreateResponder handles the response to the Create request. The method always
// closes the http.Response Body.
func (client VolumeClient) CreateResponder(resp *http.Response) (result VolumeResourceDescription, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes the volume identified by the name.
// Parameters:
// resourceGroupName - azure resource group name
// volumeName - the identity of the volume.
func (client VolumeClient) Delete(ctx context.Context, resourceGroupName string, volumeName string) (result autorest.Response, err error) {
req, err := client.DeletePreparer(ctx, resourceGroupName, volumeName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "Delete", resp, "Failure responding to request")
}
return
}
// DeletePreparer prepares the Delete request.
func (client VolumeClient) DeletePreparer(ctx context.Context, resourceGroupName string, volumeName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"volumeName": volumeName,
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/volumes/{volumeName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client VolumeClient) DeleteSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client VolumeClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get gets the information about the volume resource with a given name. This information includes the volume
// description and other runtime information.
// Parameters:
// resourceGroupName - azure resource group name
// volumeName - the identity of the volume.
func (client VolumeClient) Get(ctx context.Context, resourceGroupName string, volumeName string) (result VolumeResourceDescription, err error) {
req, err := client.GetPreparer(ctx, resourceGroupName, volumeName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client VolumeClient) GetPreparer(ctx context.Context, resourceGroupName string, volumeName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"volumeName": volumeName,
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/volumes/{volumeName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client VolumeClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client VolumeClient) GetResponder(resp *http.Response) (result VolumeResourceDescription, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListByResourceGroup gets the information about all volume resources in a given resource group. The information
// includes the volume description and other runtime information.
// Parameters:
// resourceGroupName - azure resource group name
func (client VolumeClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result VolumeResourceDescriptionListPage, err error) {
result.fn = client.listByResourceGroupNextResults
req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "ListByResourceGroup", nil, "Failure preparing request")
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.vrdl.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "ListByResourceGroup", resp, "Failure sending request")
return
}
result.vrdl, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "ListByResourceGroup", resp, "Failure responding to request")
}
return
}
// ListByResourceGroupPreparer prepares the ListByResourceGroup request.
func (client VolumeClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabricMesh/volumes", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the
// http.Response Body if it receives an error.
func (client VolumeClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always
// closes the http.Response Body.
func (client VolumeClient) ListByResourceGroupResponder(resp *http.Response) (result VolumeResourceDescriptionList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByResourceGroupNextResults retrieves the next set of results, if any.
func (client VolumeClient) listByResourceGroupNextResults(lastResults VolumeResourceDescriptionList) (result VolumeResourceDescriptionList, err error) {
req, err := lastResults.volumeResourceDescriptionListPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "listByResourceGroupNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required.
func (client VolumeClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result VolumeResourceDescriptionListIterator, err error) {
result.page, err = client.ListByResourceGroup(ctx, resourceGroupName)
return
}
// ListBySubscription gets the information about all volume resources in a given subscription. The information includes
// the volume description and other runtime information.
func (client VolumeClient) ListBySubscription(ctx context.Context) (result VolumeResourceDescriptionListPage, err error) {
result.fn = client.listBySubscriptionNextResults
req, err := client.ListBySubscriptionPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "ListBySubscription", nil, "Failure preparing request")
return
}
resp, err := client.ListBySubscriptionSender(req)
if err != nil {
result.vrdl.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "ListBySubscription", resp, "Failure sending request")
return
}
result.vrdl, err = client.ListBySubscriptionResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "ListBySubscription", resp, "Failure responding to request")
}
return
}
// ListBySubscriptionPreparer prepares the ListBySubscription request.
func (client VolumeClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2018-07-01-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.ServiceFabricMesh/volumes", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListBySubscriptionSender sends the ListBySubscription request. The method will close the
// http.Response Body if it receives an error.
func (client VolumeClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always
// closes the http.Response Body.
func (client VolumeClient) ListBySubscriptionResponder(resp *http.Response) (result VolumeResourceDescriptionList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listBySubscriptionNextResults retrieves the next set of results, if any.
func (client VolumeClient) listBySubscriptionNextResults(lastResults VolumeResourceDescriptionList) (result VolumeResourceDescriptionList, err error) {
req, err := lastResults.volumeResourceDescriptionListPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListBySubscriptionSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "listBySubscriptionNextResults", resp, "Failure sending next results request")
}
result, err = client.ListBySubscriptionResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "servicefabricmesh.VolumeClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request")
}
return
}
// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required.
func (client VolumeClient) ListBySubscriptionComplete(ctx context.Context) (result VolumeResourceDescriptionListIterator, err error) {
result.page, err = client.ListBySubscription(ctx)
return
}

View File

@@ -18,4 +18,4 @@ package version
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// Number contains the semantic version of this SDK.
const Number = "v15.1.1"
const Number = "v19.1.0"

View File

@@ -26,10 +26,10 @@ const (
// OAuthConfig represents the endpoints needed
// in OAuth operations
type OAuthConfig struct {
AuthorityEndpoint url.URL
AuthorizeEndpoint url.URL
TokenEndpoint url.URL
DeviceCodeEndpoint url.URL
AuthorityEndpoint url.URL `json:"authorityEndpoint"`
AuthorizeEndpoint url.URL `json:"authorizeEndpoint"`
TokenEndpoint url.URL `json:"tokenEndpoint"`
DeviceCodeEndpoint url.URL `json:"deviceCodeEndpoint"`
}
// IsZero returns true if the OAuthConfig object is zero-initialized.

View File

@@ -22,8 +22,10 @@ import (
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math"
"net"
"net/http"
"net/url"
@@ -33,6 +35,7 @@ import (
"time"
"github.com/Azure/go-autorest/autorest/date"
"github.com/Azure/go-autorest/version"
"github.com/dgrijalva/jwt-go"
)
@@ -59,6 +62,9 @@ const (
// msiEndpoint is the well known endpoint for getting MSI authentications tokens
msiEndpoint = "http://169.254.169.254/metadata/identity/oauth2/token"
// the default number of attempts to refresh an MSI authentication token
defaultMaxMSIRefreshAttempts = 5
)
// OAuthTokenProvider is an interface which should be implemented by an access token retriever
@@ -136,6 +142,12 @@ func (t *Token) OAuthToken() string {
return t.AccessToken
}
// ServicePrincipalSecret is an interface that allows various secret mechanism to fill the form
// that is submitted when acquiring an oAuth token.
type ServicePrincipalSecret interface {
SetAuthenticationValues(spt *ServicePrincipalToken, values *url.Values) error
}
// ServicePrincipalNoSecret represents a secret type that contains no secret
// meaning it is not valid for fetching a fresh token. This is used by Manual
type ServicePrincipalNoSecret struct {
@@ -147,15 +159,19 @@ func (noSecret *ServicePrincipalNoSecret) SetAuthenticationValues(spt *ServicePr
return fmt.Errorf("Manually created ServicePrincipalToken does not contain secret material to retrieve a new access token")
}
// ServicePrincipalSecret is an interface that allows various secret mechanism to fill the form
// that is submitted when acquiring an oAuth token.
type ServicePrincipalSecret interface {
SetAuthenticationValues(spt *ServicePrincipalToken, values *url.Values) error
// MarshalJSON implements the json.Marshaler interface.
func (noSecret ServicePrincipalNoSecret) MarshalJSON() ([]byte, error) {
type tokenType struct {
Type string `json:"type"`
}
return json.Marshal(tokenType{
Type: "ServicePrincipalNoSecret",
})
}
// ServicePrincipalTokenSecret implements ServicePrincipalSecret for client_secret type authorization.
type ServicePrincipalTokenSecret struct {
ClientSecret string
ClientSecret string `json:"value"`
}
// SetAuthenticationValues is a method of the interface ServicePrincipalSecret.
@@ -165,49 +181,24 @@ func (tokenSecret *ServicePrincipalTokenSecret) SetAuthenticationValues(spt *Ser
return nil
}
// MarshalJSON implements the json.Marshaler interface.
func (tokenSecret ServicePrincipalTokenSecret) MarshalJSON() ([]byte, error) {
type tokenType struct {
Type string `json:"type"`
Value string `json:"value"`
}
return json.Marshal(tokenType{
Type: "ServicePrincipalTokenSecret",
Value: tokenSecret.ClientSecret,
})
}
// ServicePrincipalCertificateSecret implements ServicePrincipalSecret for generic RSA cert auth with signed JWTs.
type ServicePrincipalCertificateSecret struct {
Certificate *x509.Certificate
PrivateKey *rsa.PrivateKey
}
// ServicePrincipalMSISecret implements ServicePrincipalSecret for machines running the MSI Extension.
type ServicePrincipalMSISecret struct {
}
// ServicePrincipalUsernamePasswordSecret implements ServicePrincipalSecret for username and password auth.
type ServicePrincipalUsernamePasswordSecret struct {
Username string
Password string
}
// ServicePrincipalAuthorizationCodeSecret implements ServicePrincipalSecret for authorization code auth.
type ServicePrincipalAuthorizationCodeSecret struct {
ClientSecret string
AuthorizationCode string
RedirectURI string
}
// SetAuthenticationValues is a method of the interface ServicePrincipalSecret.
func (secret *ServicePrincipalAuthorizationCodeSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error {
v.Set("code", secret.AuthorizationCode)
v.Set("client_secret", secret.ClientSecret)
v.Set("redirect_uri", secret.RedirectURI)
return nil
}
// SetAuthenticationValues is a method of the interface ServicePrincipalSecret.
func (secret *ServicePrincipalUsernamePasswordSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error {
v.Set("username", secret.Username)
v.Set("password", secret.Password)
return nil
}
// SetAuthenticationValues is a method of the interface ServicePrincipalSecret.
func (msiSecret *ServicePrincipalMSISecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error {
return nil
}
// SignJwt returns the JWT signed with the certificate's private key.
func (secret *ServicePrincipalCertificateSecret) SignJwt(spt *ServicePrincipalToken) (string, error) {
hasher := sha1.New()
@@ -228,9 +219,9 @@ func (secret *ServicePrincipalCertificateSecret) SignJwt(spt *ServicePrincipalTo
token := jwt.New(jwt.SigningMethodRS256)
token.Header["x5t"] = thumbprint
token.Claims = jwt.MapClaims{
"aud": spt.oauthConfig.TokenEndpoint.String(),
"iss": spt.clientID,
"sub": spt.clientID,
"aud": spt.inner.OauthConfig.TokenEndpoint.String(),
"iss": spt.inner.ClientID,
"sub": spt.inner.ClientID,
"jti": base64.URLEncoding.EncodeToString(jti),
"nbf": time.Now().Unix(),
"exp": time.Now().Add(time.Hour * 24).Unix(),
@@ -253,19 +244,151 @@ func (secret *ServicePrincipalCertificateSecret) SetAuthenticationValues(spt *Se
return nil
}
// MarshalJSON implements the json.Marshaler interface.
func (secret ServicePrincipalCertificateSecret) MarshalJSON() ([]byte, error) {
return nil, errors.New("marshalling ServicePrincipalCertificateSecret is not supported")
}
// ServicePrincipalMSISecret implements ServicePrincipalSecret for machines running the MSI Extension.
type ServicePrincipalMSISecret struct {
}
// SetAuthenticationValues is a method of the interface ServicePrincipalSecret.
func (msiSecret *ServicePrincipalMSISecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error {
return nil
}
// MarshalJSON implements the json.Marshaler interface.
func (msiSecret ServicePrincipalMSISecret) MarshalJSON() ([]byte, error) {
return nil, errors.New("marshalling ServicePrincipalMSISecret is not supported")
}
// ServicePrincipalUsernamePasswordSecret implements ServicePrincipalSecret for username and password auth.
type ServicePrincipalUsernamePasswordSecret struct {
Username string `json:"username"`
Password string `json:"password"`
}
// SetAuthenticationValues is a method of the interface ServicePrincipalSecret.
func (secret *ServicePrincipalUsernamePasswordSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error {
v.Set("username", secret.Username)
v.Set("password", secret.Password)
return nil
}
// MarshalJSON implements the json.Marshaler interface.
func (secret ServicePrincipalUsernamePasswordSecret) MarshalJSON() ([]byte, error) {
type tokenType struct {
Type string `json:"type"`
Username string `json:"username"`
Password string `json:"password"`
}
return json.Marshal(tokenType{
Type: "ServicePrincipalUsernamePasswordSecret",
Username: secret.Username,
Password: secret.Password,
})
}
// ServicePrincipalAuthorizationCodeSecret implements ServicePrincipalSecret for authorization code auth.
type ServicePrincipalAuthorizationCodeSecret struct {
ClientSecret string `json:"value"`
AuthorizationCode string `json:"authCode"`
RedirectURI string `json:"redirect"`
}
// SetAuthenticationValues is a method of the interface ServicePrincipalSecret.
func (secret *ServicePrincipalAuthorizationCodeSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error {
v.Set("code", secret.AuthorizationCode)
v.Set("client_secret", secret.ClientSecret)
v.Set("redirect_uri", secret.RedirectURI)
return nil
}
// MarshalJSON implements the json.Marshaler interface.
func (secret ServicePrincipalAuthorizationCodeSecret) MarshalJSON() ([]byte, error) {
type tokenType struct {
Type string `json:"type"`
Value string `json:"value"`
AuthCode string `json:"authCode"`
Redirect string `json:"redirect"`
}
return json.Marshal(tokenType{
Type: "ServicePrincipalAuthorizationCodeSecret",
Value: secret.ClientSecret,
AuthCode: secret.AuthorizationCode,
Redirect: secret.RedirectURI,
})
}
// ServicePrincipalToken encapsulates a Token created for a Service Principal.
type ServicePrincipalToken struct {
token Token
secret ServicePrincipalSecret
oauthConfig OAuthConfig
clientID string
resource string
autoRefresh bool
refreshLock *sync.RWMutex
refreshWithin time.Duration
sender Sender
inner servicePrincipalToken
refreshLock *sync.RWMutex
sender Sender
refreshCallbacks []TokenRefreshCallback
// MaxMSIRefreshAttempts is the maximum number of attempts to refresh an MSI token.
MaxMSIRefreshAttempts int
}
// MarshalTokenJSON returns the marshalled inner token.
func (spt ServicePrincipalToken) MarshalTokenJSON() ([]byte, error) {
return json.Marshal(spt.inner.Token)
}
// SetRefreshCallbacks replaces any existing refresh callbacks with the specified callbacks.
func (spt *ServicePrincipalToken) SetRefreshCallbacks(callbacks []TokenRefreshCallback) {
spt.refreshCallbacks = callbacks
}
// MarshalJSON implements the json.Marshaler interface.
func (spt ServicePrincipalToken) MarshalJSON() ([]byte, error) {
return json.Marshal(spt.inner)
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (spt *ServicePrincipalToken) UnmarshalJSON(data []byte) error {
// need to determine the token type
raw := map[string]interface{}{}
err := json.Unmarshal(data, &raw)
if err != nil {
return err
}
secret := raw["secret"].(map[string]interface{})
switch secret["type"] {
case "ServicePrincipalNoSecret":
spt.inner.Secret = &ServicePrincipalNoSecret{}
case "ServicePrincipalTokenSecret":
spt.inner.Secret = &ServicePrincipalTokenSecret{}
case "ServicePrincipalCertificateSecret":
return errors.New("unmarshalling ServicePrincipalCertificateSecret is not supported")
case "ServicePrincipalMSISecret":
return errors.New("unmarshalling ServicePrincipalMSISecret is not supported")
case "ServicePrincipalUsernamePasswordSecret":
spt.inner.Secret = &ServicePrincipalUsernamePasswordSecret{}
case "ServicePrincipalAuthorizationCodeSecret":
spt.inner.Secret = &ServicePrincipalAuthorizationCodeSecret{}
default:
return fmt.Errorf("unrecognized token type '%s'", secret["type"])
}
err = json.Unmarshal(data, &spt.inner)
if err != nil {
return err
}
spt.refreshLock = &sync.RWMutex{}
spt.sender = &http.Client{}
return nil
}
// internal type used for marshalling/unmarshalling
type servicePrincipalToken struct {
Token Token `json:"token"`
Secret ServicePrincipalSecret `json:"secret"`
OauthConfig OAuthConfig `json:"oauth"`
ClientID string `json:"clientID"`
Resource string `json:"resource"`
AutoRefresh bool `json:"autoRefresh"`
RefreshWithin time.Duration `json:"refreshWithin"`
}
func validateOAuthConfig(oac OAuthConfig) error {
@@ -290,13 +413,15 @@ func NewServicePrincipalTokenWithSecret(oauthConfig OAuthConfig, id string, reso
return nil, fmt.Errorf("parameter 'secret' cannot be nil")
}
spt := &ServicePrincipalToken{
oauthConfig: oauthConfig,
secret: secret,
clientID: id,
resource: resource,
autoRefresh: true,
inner: servicePrincipalToken{
OauthConfig: oauthConfig,
Secret: secret,
ClientID: id,
Resource: resource,
AutoRefresh: true,
RefreshWithin: defaultRefresh,
},
refreshLock: &sync.RWMutex{},
refreshWithin: defaultRefresh,
sender: &http.Client{},
refreshCallbacks: callbacks,
}
@@ -327,7 +452,39 @@ func NewServicePrincipalTokenFromManualToken(oauthConfig OAuthConfig, clientID s
return nil, err
}
spt.token = token
spt.inner.Token = token
return spt, nil
}
// NewServicePrincipalTokenFromManualTokenSecret creates a ServicePrincipalToken using the supplied token and secret
func NewServicePrincipalTokenFromManualTokenSecret(oauthConfig OAuthConfig, clientID string, resource string, token Token, secret ServicePrincipalSecret, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) {
if err := validateOAuthConfig(oauthConfig); err != nil {
return nil, err
}
if err := validateStringParam(clientID, "clientID"); err != nil {
return nil, err
}
if err := validateStringParam(resource, "resource"); err != nil {
return nil, err
}
if secret == nil {
return nil, fmt.Errorf("parameter 'secret' cannot be nil")
}
if token.IsZero() {
return nil, fmt.Errorf("parameter 'token' cannot be zero-initialized")
}
spt, err := NewServicePrincipalTokenWithSecret(
oauthConfig,
clientID,
resource,
secret,
callbacks...)
if err != nil {
return nil, err
}
spt.inner.Token = token
return spt, nil
}
@@ -495,20 +652,23 @@ func newServicePrincipalTokenFromMSI(msiEndpoint, resource string, userAssignedI
msiEndpointURL.RawQuery = v.Encode()
spt := &ServicePrincipalToken{
oauthConfig: OAuthConfig{
TokenEndpoint: *msiEndpointURL,
inner: servicePrincipalToken{
OauthConfig: OAuthConfig{
TokenEndpoint: *msiEndpointURL,
},
Secret: &ServicePrincipalMSISecret{},
Resource: resource,
AutoRefresh: true,
RefreshWithin: defaultRefresh,
},
secret: &ServicePrincipalMSISecret{},
resource: resource,
autoRefresh: true,
refreshLock: &sync.RWMutex{},
refreshWithin: defaultRefresh,
sender: &http.Client{},
refreshCallbacks: callbacks,
refreshLock: &sync.RWMutex{},
sender: &http.Client{},
refreshCallbacks: callbacks,
MaxMSIRefreshAttempts: defaultMaxMSIRefreshAttempts,
}
if userAssignedID != nil {
spt.clientID = *userAssignedID
spt.inner.ClientID = *userAssignedID
}
return spt, nil
@@ -543,12 +703,12 @@ func (spt *ServicePrincipalToken) EnsureFresh() error {
// EnsureFreshWithContext will refresh the token if it will expire within the refresh window (as set by
// RefreshWithin) and autoRefresh flag is on. This method is safe for concurrent use.
func (spt *ServicePrincipalToken) EnsureFreshWithContext(ctx context.Context) error {
if spt.autoRefresh && spt.token.WillExpireIn(spt.refreshWithin) {
if spt.inner.AutoRefresh && spt.inner.Token.WillExpireIn(spt.inner.RefreshWithin) {
// take the write lock then check to see if the token was already refreshed
spt.refreshLock.Lock()
defer spt.refreshLock.Unlock()
if spt.token.WillExpireIn(spt.refreshWithin) {
return spt.refreshInternal(ctx, spt.resource)
if spt.inner.Token.WillExpireIn(spt.inner.RefreshWithin) {
return spt.refreshInternal(ctx, spt.inner.Resource)
}
}
return nil
@@ -558,7 +718,7 @@ func (spt *ServicePrincipalToken) EnsureFreshWithContext(ctx context.Context) er
func (spt *ServicePrincipalToken) InvokeRefreshCallbacks(token Token) error {
if spt.refreshCallbacks != nil {
for _, callback := range spt.refreshCallbacks {
err := callback(spt.token)
err := callback(spt.inner.Token)
if err != nil {
return fmt.Errorf("adal: TokenRefreshCallback handler failed. Error = '%v'", err)
}
@@ -578,7 +738,7 @@ func (spt *ServicePrincipalToken) Refresh() error {
func (spt *ServicePrincipalToken) RefreshWithContext(ctx context.Context) error {
spt.refreshLock.Lock()
defer spt.refreshLock.Unlock()
return spt.refreshInternal(ctx, spt.resource)
return spt.refreshInternal(ctx, spt.inner.Resource)
}
// RefreshExchange refreshes the token, but for a different resource.
@@ -596,7 +756,7 @@ func (spt *ServicePrincipalToken) RefreshExchangeWithContext(ctx context.Context
}
func (spt *ServicePrincipalToken) getGrantType() string {
switch spt.secret.(type) {
switch spt.inner.Secret.(type) {
case *ServicePrincipalUsernamePasswordSecret:
return OAuthGrantTypeUserPass
case *ServicePrincipalAuthorizationCodeSecret:
@@ -615,22 +775,31 @@ func isIMDS(u url.URL) bool {
}
func (spt *ServicePrincipalToken) refreshInternal(ctx context.Context, resource string) error {
req, err := http.NewRequest(http.MethodPost, spt.oauthConfig.TokenEndpoint.String(), nil)
req, err := http.NewRequest(http.MethodPost, spt.inner.OauthConfig.TokenEndpoint.String(), nil)
if err != nil {
return fmt.Errorf("adal: Failed to build the refresh request. Error = '%v'", err)
}
req.Header.Add("User-Agent", version.UserAgent())
req = req.WithContext(ctx)
if !isIMDS(spt.oauthConfig.TokenEndpoint) {
if !isIMDS(spt.inner.OauthConfig.TokenEndpoint) {
v := url.Values{}
v.Set("client_id", spt.clientID)
v.Set("client_id", spt.inner.ClientID)
v.Set("resource", resource)
if spt.token.RefreshToken != "" {
if spt.inner.Token.RefreshToken != "" {
v.Set("grant_type", OAuthGrantTypeRefreshToken)
v.Set("refresh_token", spt.token.RefreshToken)
v.Set("refresh_token", spt.inner.Token.RefreshToken)
// web apps must specify client_secret when refreshing tokens
// see https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code#refreshing-the-access-tokens
if spt.getGrantType() == OAuthGrantTypeAuthorizationCode {
err := spt.inner.Secret.SetAuthenticationValues(spt, &v)
if err != nil {
return err
}
}
} else {
v.Set("grant_type", spt.getGrantType())
err := spt.secret.SetAuthenticationValues(spt, &v)
err := spt.inner.Secret.SetAuthenticationValues(spt, &v)
if err != nil {
return err
}
@@ -643,14 +812,14 @@ func (spt *ServicePrincipalToken) refreshInternal(ctx context.Context, resource
req.Body = body
}
if _, ok := spt.secret.(*ServicePrincipalMSISecret); ok {
if _, ok := spt.inner.Secret.(*ServicePrincipalMSISecret); ok {
req.Method = http.MethodGet
req.Header.Set(metadataHeader, "true")
}
var resp *http.Response
if isIMDS(spt.oauthConfig.TokenEndpoint) {
resp, err = retry(spt.sender, req)
if isIMDS(spt.inner.OauthConfig.TokenEndpoint) {
resp, err = retryForIMDS(spt.sender, req, spt.MaxMSIRefreshAttempts)
} else {
resp, err = spt.sender.Do(req)
}
@@ -684,12 +853,14 @@ func (spt *ServicePrincipalToken) refreshInternal(ctx context.Context, resource
return fmt.Errorf("adal: Failed to unmarshal the service principal token during refresh. Error = '%v' JSON = '%s'", err, string(rb))
}
spt.token = token
spt.inner.Token = token
return spt.InvokeRefreshCallbacks(token)
}
func retry(sender Sender, req *http.Request) (resp *http.Response, err error) {
// retry logic specific to retrieving a token from the IMDS endpoint
func retryForIMDS(sender Sender, req *http.Request, maxAttempts int) (resp *http.Response, err error) {
// copied from client.go due to circular dependency
retries := []int{
http.StatusRequestTimeout, // 408
http.StatusTooManyRequests, // 429
@@ -698,8 +869,10 @@ func retry(sender Sender, req *http.Request) (resp *http.Response, err error) {
http.StatusServiceUnavailable, // 503
http.StatusGatewayTimeout, // 504
}
// Extra retry status codes requered
retries = append(retries, http.StatusNotFound,
// extra retry status codes specific to IMDS
retries = append(retries,
http.StatusNotFound,
http.StatusGone,
// all remaining 5xx
http.StatusNotImplemented,
http.StatusHTTPVersionNotSupported,
@@ -709,36 +882,52 @@ func retry(sender Sender, req *http.Request) (resp *http.Response, err error) {
http.StatusNotExtended,
http.StatusNetworkAuthenticationRequired)
// see https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/how-to-use-vm-token#retry-guidance
const maxDelay time.Duration = 60 * time.Second
attempt := 0
maxAttempts := 5
delay := time.Duration(0)
for attempt < maxAttempts {
resp, err = sender.Do(req)
// retry on temporary network errors, e.g. transient network failures.
if (err != nil && !isTemporaryNetworkError(err)) || resp.StatusCode == http.StatusOK || !containsInt(retries, resp.StatusCode) {
// if we don't receive a response then assume we can't connect to the
// endpoint so we're likely not running on an Azure VM so don't retry.
if (err != nil && !isTemporaryNetworkError(err)) || resp == nil || resp.StatusCode == http.StatusOK || !containsInt(retries, resp.StatusCode) {
return
}
if !delay(resp, req.Context().Done()) {
select {
case <-time.After(time.Second):
attempt++
case <-req.Context().Done():
err = req.Context().Err()
return
}
// perform exponential backoff with a cap.
// must increment attempt before calculating delay.
attempt++
// the base value of 2 is the "delta backoff" as specified in the guidance doc
delay += (time.Duration(math.Pow(2, float64(attempt))) * time.Second)
if delay > maxDelay {
delay = maxDelay
}
select {
case <-time.After(delay):
// intentionally left blank
case <-req.Context().Done():
err = req.Context().Err()
return
}
}
return
}
// returns true if the specified error is a temporary network error or false if it's not.
// if the error doesn't implement the net.Error interface the return value is true.
func isTemporaryNetworkError(err error) bool {
if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
if netErr, ok := err.(net.Error); !ok || (ok && netErr.Temporary()) {
return true
}
return false
}
// returns true if slice ints contains the value n
func containsInt(ints []int, n int) bool {
for _, i := range ints {
if i == n {
@@ -748,31 +937,15 @@ func containsInt(ints []int, n int) bool {
return false
}
func delay(resp *http.Response, cancel <-chan struct{}) bool {
if resp == nil {
return false
}
retryAfter, _ := strconv.Atoi(resp.Header.Get("Retry-After"))
if resp.StatusCode == http.StatusTooManyRequests && retryAfter > 0 {
select {
case <-time.After(time.Duration(retryAfter) * time.Second):
return true
case <-cancel:
return false
}
}
return false
}
// SetAutoRefresh enables or disables automatic refreshing of stale tokens.
func (spt *ServicePrincipalToken) SetAutoRefresh(autoRefresh bool) {
spt.autoRefresh = autoRefresh
spt.inner.AutoRefresh = autoRefresh
}
// SetRefreshWithin sets the interval within which if the token will expire, EnsureFresh will
// refresh the token.
func (spt *ServicePrincipalToken) SetRefreshWithin(d time.Duration) {
spt.refreshWithin = d
spt.inner.RefreshWithin = d
return
}
@@ -784,12 +957,12 @@ func (spt *ServicePrincipalToken) SetSender(s Sender) { spt.sender = s }
func (spt *ServicePrincipalToken) OAuthToken() string {
spt.refreshLock.RLock()
defer spt.refreshLock.RUnlock()
return spt.token.OAuthToken()
return spt.inner.Token.OAuthToken()
}
// Token returns a copy of the current token.
func (spt *ServicePrincipalToken) Token() Token {
spt.refreshLock.RLock()
defer spt.refreshLock.RUnlock()
return spt.token
return spt.inner.Token
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,444 @@
package auth
// Copyright 2017 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import (
"bytes"
"crypto/rsa"
"crypto/x509"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"unicode/utf16"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/dimchansky/utfbom"
"golang.org/x/crypto/pkcs12"
)
// NewAuthorizerFromEnvironment creates an Authorizer configured from environment variables in the order:
// 1. Client credentials
// 2. Client certificate
// 3. Username password
// 4. MSI
func NewAuthorizerFromEnvironment() (autorest.Authorizer, error) {
settings, err := getAuthenticationSettings()
if err != nil {
return nil, err
}
if settings.resource == "" {
settings.resource = settings.environment.ResourceManagerEndpoint
}
return settings.getAuthorizer()
}
// NewAuthorizerFromEnvironmentWithResource creates an Authorizer configured from environment variables in the order:
// 1. Client credentials
// 2. Client certificate
// 3. Username password
// 4. MSI
func NewAuthorizerFromEnvironmentWithResource(resource string) (autorest.Authorizer, error) {
settings, err := getAuthenticationSettings()
if err != nil {
return nil, err
}
settings.resource = resource
return settings.getAuthorizer()
}
type settings struct {
tenantID string
clientID string
clientSecret string
certificatePath string
certificatePassword string
username string
password string
envName string
resource string
environment azure.Environment
}
func getAuthenticationSettings() (s settings, err error) {
s = settings{
tenantID: os.Getenv("AZURE_TENANT_ID"),
clientID: os.Getenv("AZURE_CLIENT_ID"),
clientSecret: os.Getenv("AZURE_CLIENT_SECRET"),
certificatePath: os.Getenv("AZURE_CERTIFICATE_PATH"),
certificatePassword: os.Getenv("AZURE_CERTIFICATE_PASSWORD"),
username: os.Getenv("AZURE_USERNAME"),
password: os.Getenv("AZURE_PASSWORD"),
envName: os.Getenv("AZURE_ENVIRONMENT"),
resource: os.Getenv("AZURE_AD_RESOURCE"),
}
if s.envName == "" {
s.environment = azure.PublicCloud
} else {
s.environment, err = azure.EnvironmentFromName(s.envName)
}
return
}
func (settings settings) getAuthorizer() (autorest.Authorizer, error) {
//1.Client Credentials
if settings.clientSecret != "" {
config := NewClientCredentialsConfig(settings.clientID, settings.clientSecret, settings.tenantID)
config.AADEndpoint = settings.environment.ActiveDirectoryEndpoint
config.Resource = settings.resource
return config.Authorizer()
}
//2. Client Certificate
if settings.certificatePath != "" {
config := NewClientCertificateConfig(settings.certificatePath, settings.certificatePassword, settings.clientID, settings.tenantID)
config.AADEndpoint = settings.environment.ActiveDirectoryEndpoint
config.Resource = settings.resource
return config.Authorizer()
}
//3. Username Password
if settings.username != "" && settings.password != "" {
config := NewUsernamePasswordConfig(settings.username, settings.password, settings.clientID, settings.tenantID)
config.AADEndpoint = settings.environment.ActiveDirectoryEndpoint
config.Resource = settings.resource
return config.Authorizer()
}
// 4. MSI
config := NewMSIConfig()
config.Resource = settings.resource
config.ClientID = settings.clientID
return config.Authorizer()
}
// NewAuthorizerFromFile creates an Authorizer configured from a configuration file.
func NewAuthorizerFromFile(baseURI string) (autorest.Authorizer, error) {
fileLocation := os.Getenv("AZURE_AUTH_LOCATION")
if fileLocation == "" {
return nil, errors.New("auth file not found. Environment variable AZURE_AUTH_LOCATION is not set")
}
contents, err := ioutil.ReadFile(fileLocation)
if err != nil {
return nil, err
}
// Auth file might be encoded
decoded, err := decode(contents)
if err != nil {
return nil, err
}
file := file{}
err = json.Unmarshal(decoded, &file)
if err != nil {
return nil, err
}
resource, err := getResourceForToken(file, baseURI)
if err != nil {
return nil, err
}
config, err := adal.NewOAuthConfig(file.ActiveDirectoryEndpoint, file.TenantID)
if err != nil {
return nil, err
}
spToken, err := adal.NewServicePrincipalToken(*config, file.ClientID, file.ClientSecret, resource)
if err != nil {
return nil, err
}
return autorest.NewBearerAuthorizer(spToken), nil
}
// File represents the authentication file
type file struct {
ClientID string `json:"clientId,omitempty"`
ClientSecret string `json:"clientSecret,omitempty"`
SubscriptionID string `json:"subscriptionId,omitempty"`
TenantID string `json:"tenantId,omitempty"`
ActiveDirectoryEndpoint string `json:"activeDirectoryEndpointUrl,omitempty"`
ResourceManagerEndpoint string `json:"resourceManagerEndpointUrl,omitempty"`
GraphResourceID string `json:"activeDirectoryGraphResourceId,omitempty"`
SQLManagementEndpoint string `json:"sqlManagementEndpointUrl,omitempty"`
GalleryEndpoint string `json:"galleryEndpointUrl,omitempty"`
ManagementEndpoint string `json:"managementEndpointUrl,omitempty"`
}
func decode(b []byte) ([]byte, error) {
reader, enc := utfbom.Skip(bytes.NewReader(b))
switch enc {
case utfbom.UTF16LittleEndian:
u16 := make([]uint16, (len(b)/2)-1)
err := binary.Read(reader, binary.LittleEndian, &u16)
if err != nil {
return nil, err
}
return []byte(string(utf16.Decode(u16))), nil
case utfbom.UTF16BigEndian:
u16 := make([]uint16, (len(b)/2)-1)
err := binary.Read(reader, binary.BigEndian, &u16)
if err != nil {
return nil, err
}
return []byte(string(utf16.Decode(u16))), nil
}
return ioutil.ReadAll(reader)
}
func getResourceForToken(f file, baseURI string) (string, error) {
// Compare dafault base URI from the SDK to the endpoints from the public cloud
// Base URI and token resource are the same string. This func finds the authentication
// file field that matches the SDK base URI. The SDK defines the public cloud
// endpoint as its default base URI
if !strings.HasSuffix(baseURI, "/") {
baseURI += "/"
}
switch baseURI {
case azure.PublicCloud.ServiceManagementEndpoint:
return f.ManagementEndpoint, nil
case azure.PublicCloud.ResourceManagerEndpoint:
return f.ResourceManagerEndpoint, nil
case azure.PublicCloud.ActiveDirectoryEndpoint:
return f.ActiveDirectoryEndpoint, nil
case azure.PublicCloud.GalleryEndpoint:
return f.GalleryEndpoint, nil
case azure.PublicCloud.GraphEndpoint:
return f.GraphResourceID, nil
}
return "", fmt.Errorf("auth: base URI not found in endpoints")
}
// NewClientCredentialsConfig creates an AuthorizerConfig object configured to obtain an Authorizer through Client Credentials.
// Defaults to Public Cloud and Resource Manager Endpoint.
func NewClientCredentialsConfig(clientID string, clientSecret string, tenantID string) ClientCredentialsConfig {
return ClientCredentialsConfig{
ClientID: clientID,
ClientSecret: clientSecret,
TenantID: tenantID,
Resource: azure.PublicCloud.ResourceManagerEndpoint,
AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint,
}
}
// NewClientCertificateConfig creates a ClientCertificateConfig object configured to obtain an Authorizer through client certificate.
// Defaults to Public Cloud and Resource Manager Endpoint.
func NewClientCertificateConfig(certificatePath string, certificatePassword string, clientID string, tenantID string) ClientCertificateConfig {
return ClientCertificateConfig{
CertificatePath: certificatePath,
CertificatePassword: certificatePassword,
ClientID: clientID,
TenantID: tenantID,
Resource: azure.PublicCloud.ResourceManagerEndpoint,
AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint,
}
}
// NewUsernamePasswordConfig creates an UsernamePasswordConfig object configured to obtain an Authorizer through username and password.
// Defaults to Public Cloud and Resource Manager Endpoint.
func NewUsernamePasswordConfig(username string, password string, clientID string, tenantID string) UsernamePasswordConfig {
return UsernamePasswordConfig{
Username: username,
Password: password,
ClientID: clientID,
TenantID: tenantID,
Resource: azure.PublicCloud.ResourceManagerEndpoint,
AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint,
}
}
// NewMSIConfig creates an MSIConfig object configured to obtain an Authorizer through MSI.
func NewMSIConfig() MSIConfig {
return MSIConfig{
Resource: azure.PublicCloud.ResourceManagerEndpoint,
}
}
// NewDeviceFlowConfig creates a DeviceFlowConfig object configured to obtain an Authorizer through device flow.
// Defaults to Public Cloud and Resource Manager Endpoint.
func NewDeviceFlowConfig(clientID string, tenantID string) DeviceFlowConfig {
return DeviceFlowConfig{
ClientID: clientID,
TenantID: tenantID,
Resource: azure.PublicCloud.ResourceManagerEndpoint,
AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint,
}
}
//AuthorizerConfig provides an authorizer from the configuration provided.
type AuthorizerConfig interface {
Authorizer() (autorest.Authorizer, error)
}
// ClientCredentialsConfig provides the options to get a bearer authorizer from client credentials.
type ClientCredentialsConfig struct {
ClientID string
ClientSecret string
TenantID string
AADEndpoint string
Resource string
}
// Authorizer gets the authorizer from client credentials.
func (ccc ClientCredentialsConfig) Authorizer() (autorest.Authorizer, error) {
oauthConfig, err := adal.NewOAuthConfig(ccc.AADEndpoint, ccc.TenantID)
if err != nil {
return nil, err
}
spToken, err := adal.NewServicePrincipalToken(*oauthConfig, ccc.ClientID, ccc.ClientSecret, ccc.Resource)
if err != nil {
return nil, fmt.Errorf("failed to get oauth token from client credentials: %v", err)
}
return autorest.NewBearerAuthorizer(spToken), nil
}
// ClientCertificateConfig provides the options to get a bearer authorizer from a client certificate.
type ClientCertificateConfig struct {
ClientID string
CertificatePath string
CertificatePassword string
TenantID string
AADEndpoint string
Resource string
}
// Authorizer gets an authorizer object from client certificate.
func (ccc ClientCertificateConfig) Authorizer() (autorest.Authorizer, error) {
oauthConfig, err := adal.NewOAuthConfig(ccc.AADEndpoint, ccc.TenantID)
certData, err := ioutil.ReadFile(ccc.CertificatePath)
if err != nil {
return nil, fmt.Errorf("failed to read the certificate file (%s): %v", ccc.CertificatePath, err)
}
certificate, rsaPrivateKey, err := decodePkcs12(certData, ccc.CertificatePassword)
if err != nil {
return nil, fmt.Errorf("failed to decode pkcs12 certificate while creating spt: %v", err)
}
spToken, err := adal.NewServicePrincipalTokenFromCertificate(*oauthConfig, ccc.ClientID, certificate, rsaPrivateKey, ccc.Resource)
if err != nil {
return nil, fmt.Errorf("failed to get oauth token from certificate auth: %v", err)
}
return autorest.NewBearerAuthorizer(spToken), nil
}
// DeviceFlowConfig provides the options to get a bearer authorizer using device flow authentication.
type DeviceFlowConfig struct {
ClientID string
TenantID string
AADEndpoint string
Resource string
}
// Authorizer gets the authorizer from device flow.
func (dfc DeviceFlowConfig) Authorizer() (autorest.Authorizer, error) {
oauthClient := &autorest.Client{}
oauthConfig, err := adal.NewOAuthConfig(dfc.AADEndpoint, dfc.TenantID)
deviceCode, err := adal.InitiateDeviceAuth(oauthClient, *oauthConfig, dfc.ClientID, dfc.Resource)
if err != nil {
return nil, fmt.Errorf("failed to start device auth flow: %s", err)
}
log.Println(*deviceCode.Message)
token, err := adal.WaitForUserCompletion(oauthClient, deviceCode)
if err != nil {
return nil, fmt.Errorf("failed to finish device auth flow: %s", err)
}
spToken, err := adal.NewServicePrincipalTokenFromManualToken(*oauthConfig, dfc.ClientID, dfc.Resource, *token)
if err != nil {
return nil, fmt.Errorf("failed to get oauth token from device flow: %v", err)
}
return autorest.NewBearerAuthorizer(spToken), nil
}
func decodePkcs12(pkcs []byte, password string) (*x509.Certificate, *rsa.PrivateKey, error) {
privateKey, certificate, err := pkcs12.Decode(pkcs, password)
if err != nil {
return nil, nil, err
}
rsaPrivateKey, isRsaKey := privateKey.(*rsa.PrivateKey)
if !isRsaKey {
return nil, nil, fmt.Errorf("PKCS#12 certificate must contain an RSA private key")
}
return certificate, rsaPrivateKey, nil
}
// UsernamePasswordConfig provides the options to get a bearer authorizer from a username and a password.
type UsernamePasswordConfig struct {
ClientID string
Username string
Password string
TenantID string
AADEndpoint string
Resource string
}
// Authorizer gets the authorizer from a username and a password.
func (ups UsernamePasswordConfig) Authorizer() (autorest.Authorizer, error) {
oauthConfig, err := adal.NewOAuthConfig(ups.AADEndpoint, ups.TenantID)
spToken, err := adal.NewServicePrincipalTokenFromUsernamePassword(*oauthConfig, ups.ClientID, ups.Username, ups.Password, ups.Resource)
if err != nil {
return nil, fmt.Errorf("failed to get oauth token from username and password auth: %v", err)
}
return autorest.NewBearerAuthorizer(spToken), nil
}
// MSIConfig provides the options to get a bearer authorizer through MSI.
type MSIConfig struct {
Resource string
ClientID string
}
// Authorizer gets the authorizer from MSI.
func (mc MSIConfig) Authorizer() (autorest.Authorizer, error) {
msiEndpoint, err := adal.GetMSIVMEndpoint()
if err != nil {
return nil, err
}
spToken, err := adal.NewServicePrincipalTokenFromMSI(msiEndpoint, mc.Resource)
if err != nil {
return nil, fmt.Errorf("failed to get oauth token from MSI: %v", err)
}
return autorest.NewBearerAuthorizer(spToken), nil
}

View File

@@ -44,11 +44,12 @@ const (
// ServiceError encapsulates the error response from an Azure service.
// It adhears to the OData v4 specification for error responses.
type ServiceError struct {
Code string `json:"code"`
Message string `json:"message"`
Target *string `json:"target"`
Details []map[string]interface{} `json:"details"`
InnerError map[string]interface{} `json:"innererror"`
Code string `json:"code"`
Message string `json:"message"`
Target *string `json:"target"`
Details []map[string]interface{} `json:"details"`
InnerError map[string]interface{} `json:"innererror"`
AdditionalInfo []map[string]interface{} `json:"additionalInfo"`
}
func (se ServiceError) Error() string {
@@ -74,6 +75,14 @@ func (se ServiceError) Error() string {
result += fmt.Sprintf(" InnerError=%v", string(d))
}
if se.AdditionalInfo != nil {
d, err := json.Marshal(se.AdditionalInfo)
if err != nil {
result += fmt.Sprintf(" AdditionalInfo=%v", se.AdditionalInfo)
}
result += fmt.Sprintf(" AdditionalInfo=%v", string(d))
}
return result
}
@@ -86,44 +95,47 @@ func (se *ServiceError) UnmarshalJSON(b []byte) error {
// http://docs.oasis-open.org/odata/odata-json-format/v4.0/os/odata-json-format-v4.0-os.html#_Toc372793091
type serviceError1 struct {
Code string `json:"code"`
Message string `json:"message"`
Target *string `json:"target"`
Details []map[string]interface{} `json:"details"`
InnerError map[string]interface{} `json:"innererror"`
Code string `json:"code"`
Message string `json:"message"`
Target *string `json:"target"`
Details []map[string]interface{} `json:"details"`
InnerError map[string]interface{} `json:"innererror"`
AdditionalInfo []map[string]interface{} `json:"additionalInfo"`
}
type serviceError2 struct {
Code string `json:"code"`
Message string `json:"message"`
Target *string `json:"target"`
Details map[string]interface{} `json:"details"`
InnerError map[string]interface{} `json:"innererror"`
Code string `json:"code"`
Message string `json:"message"`
Target *string `json:"target"`
Details map[string]interface{} `json:"details"`
InnerError map[string]interface{} `json:"innererror"`
AdditionalInfo []map[string]interface{} `json:"additionalInfo"`
}
se1 := serviceError1{}
err := json.Unmarshal(b, &se1)
if err == nil {
se.populate(se1.Code, se1.Message, se1.Target, se1.Details, se1.InnerError)
se.populate(se1.Code, se1.Message, se1.Target, se1.Details, se1.InnerError, se1.AdditionalInfo)
return nil
}
se2 := serviceError2{}
err = json.Unmarshal(b, &se2)
if err == nil {
se.populate(se2.Code, se2.Message, se2.Target, nil, se2.InnerError)
se.populate(se2.Code, se2.Message, se2.Target, nil, se2.InnerError, se2.AdditionalInfo)
se.Details = append(se.Details, se2.Details)
return nil
}
return err
}
func (se *ServiceError) populate(code, message string, target *string, details []map[string]interface{}, inner map[string]interface{}) {
func (se *ServiceError) populate(code, message string, target *string, details []map[string]interface{}, inner map[string]interface{}, additional []map[string]interface{}) {
se.Code = code
se.Message = message
se.Target = target
se.Details = details
se.InnerError = inner
se.AdditionalInfo = additional
}
// RequestError describes an error response returned by Azure service.
@@ -279,16 +291,29 @@ func WithErrorUnlessStatusCode(codes ...int) autorest.RespondDecorator {
resp.Body = ioutil.NopCloser(&b)
if decodeErr != nil {
return fmt.Errorf("autorest/azure: error response cannot be parsed: %q error: %v", b.String(), decodeErr)
} else if e.ServiceError == nil {
}
if e.ServiceError == nil {
// Check if error is unwrapped ServiceError
if err := json.Unmarshal(b.Bytes(), &e.ServiceError); err != nil || e.ServiceError.Message == "" {
e.ServiceError = &ServiceError{
Code: "Unknown",
Message: "Unknown service error",
}
if err := json.Unmarshal(b.Bytes(), &e.ServiceError); err != nil {
return err
}
}
if e.ServiceError.Message == "" {
// if we're here it means the returned error wasn't OData v4 compliant.
// try to unmarshal the body as raw JSON in hopes of getting something.
rawBody := map[string]interface{}{}
if err := json.Unmarshal(b.Bytes(), &rawBody); err != nil {
return err
}
e.ServiceError = &ServiceError{
Code: "Unknown",
Message: "Unknown service error",
}
if len(rawBody) > 0 {
e.ServiceError.Details = []map[string]interface{}{rawBody}
}
}
e.Response = resp
e.RequestID = ExtractRequestID(resp)
if e.StatusCode == nil {
e.StatusCode = resp.StatusCode

View File

@@ -64,7 +64,7 @@ func DoRetryWithRegistration(client autorest.Client) autorest.SendDecorator {
}
}
}
return resp, fmt.Errorf("failed request: %s", err)
return resp, err
})
}
}

View File

@@ -22,8 +22,11 @@ import (
"log"
"net/http"
"net/http/cookiejar"
"runtime"
"strings"
"time"
"github.com/Azure/go-autorest/logger"
"github.com/Azure/go-autorest/version"
)
const (
@@ -41,15 +44,6 @@ const (
)
var (
// defaultUserAgent builds a string containing the Go version, system archityecture and OS,
// and the go-autorest version.
defaultUserAgent = fmt.Sprintf("Go/%s (%s-%s) go-autorest/%s",
runtime.Version(),
runtime.GOARCH,
runtime.GOOS,
Version(),
)
// StatusCodesForRetry are a defined group of status code for which the client will retry
StatusCodesForRetry = []int{
http.StatusRequestTimeout, // 408
@@ -179,7 +173,7 @@ func NewClientWithUserAgent(ua string) Client {
PollingDuration: DefaultPollingDuration,
RetryAttempts: DefaultRetryAttempts,
RetryDuration: DefaultRetryDuration,
UserAgent: defaultUserAgent,
UserAgent: version.UserAgent(),
}
c.Sender = c.sender()
c.AddToUserAgent(ua)
@@ -216,8 +210,17 @@ func (c Client) Do(r *http.Request) (*http.Response, error) {
}
return resp, NewErrorWithError(err, "autorest/Client", "Do", nil, "Preparing request failed")
}
logger.Instance.WriteRequest(r, logger.Filter{
Header: func(k string, v []string) (bool, []string) {
// remove the auth token from the log
if strings.EqualFold(k, "Authorization") || strings.EqualFold(k, "Ocp-Apim-Subscription-Key") {
v = []string{"**REDACTED**"}
}
return true, v
},
})
resp, err := SendWithSender(c.sender(), r)
logger.Instance.WriteResponse(resp, logger.Filter{})
Respond(resp, c.ByInspecting())
return resp, err
}

View File

@@ -218,9 +218,10 @@ func IsTokenRefreshError(err error) bool {
return false
}
// IsTemporaryNetworkError returns true if the specified error is a temporary network error.
// IsTemporaryNetworkError returns true if the specified error is a temporary network error or false
// if it's not. If the error doesn't implement the net.Error interface the return value is true.
func IsTemporaryNetworkError(err error) bool {
if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
if netErr, ok := err.(net.Error); !ok || (ok && netErr.Temporary()) {
return true
}
return false

View File

@@ -136,29 +136,29 @@ func validatePtr(x reflect.Value, v Constraint) error {
func validateInt(x reflect.Value, v Constraint) error {
i := x.Int()
r, ok := v.Rule.(int)
r, ok := toInt64(v.Rule)
if !ok {
return createError(x, v, fmt.Sprintf("rule must be integer value for %v constraint; got: %v", v.Name, v.Rule))
}
switch v.Name {
case MultipleOf:
if i%int64(r) != 0 {
if i%r != 0 {
return createError(x, v, fmt.Sprintf("value must be a multiple of %v", r))
}
case ExclusiveMinimum:
if i <= int64(r) {
if i <= r {
return createError(x, v, fmt.Sprintf("value must be greater than %v", r))
}
case ExclusiveMaximum:
if i >= int64(r) {
if i >= r {
return createError(x, v, fmt.Sprintf("value must be less than %v", r))
}
case InclusiveMinimum:
if i < int64(r) {
if i < r {
return createError(x, v, fmt.Sprintf("value must be greater than or equal to %v", r))
}
case InclusiveMaximum:
if i > int64(r) {
if i > r {
return createError(x, v, fmt.Sprintf("value must be less than or equal to %v", r))
}
default:
@@ -388,6 +388,17 @@ func createError(x reflect.Value, v Constraint, err string) error {
v.Target, v.Name, getInterfaceValue(x), err)
}
func toInt64(v interface{}) (int64, bool) {
if i64, ok := v.(int64); ok {
return i64, true
}
// older generators emit max constants as int, so if int64 fails fall back to int
if i32, ok := v.(int); ok {
return int64(i32), true
}
return 0, false
}
// NewErrorWithValidationError appends package type and method name in
// validation error.
//

View File

@@ -1,5 +1,7 @@
package autorest
import "github.com/Azure/go-autorest/version"
// Copyright 2017 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -16,5 +18,5 @@ package autorest
// Version returns the semantic version (see http://semver.org).
func Version() string {
return "v10.8.1"
return version.Number
}

328
vendor/github.com/Azure/go-autorest/logger/logger.go generated vendored Normal file
View File

@@ -0,0 +1,328 @@
package logger
// Copyright 2017 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
)
// LevelType tells a logger the minimum level to log. When code reports a log entry,
// the LogLevel indicates the level of the log entry. The logger only records entries
// whose level is at least the level it was told to log. See the Log* constants.
// For example, if a logger is configured with LogError, then LogError, LogPanic,
// and LogFatal entries will be logged; lower level entries are ignored.
type LevelType uint32
const (
// LogNone tells a logger not to log any entries passed to it.
LogNone LevelType = iota
// LogFatal tells a logger to log all LogFatal entries passed to it.
LogFatal
// LogPanic tells a logger to log all LogPanic and LogFatal entries passed to it.
LogPanic
// LogError tells a logger to log all LogError, LogPanic and LogFatal entries passed to it.
LogError
// LogWarning tells a logger to log all LogWarning, LogError, LogPanic and LogFatal entries passed to it.
LogWarning
// LogInfo tells a logger to log all LogInfo, LogWarning, LogError, LogPanic and LogFatal entries passed to it.
LogInfo
// LogDebug tells a logger to log all LogDebug, LogInfo, LogWarning, LogError, LogPanic and LogFatal entries passed to it.
LogDebug
)
const (
logNone = "NONE"
logFatal = "FATAL"
logPanic = "PANIC"
logError = "ERROR"
logWarning = "WARNING"
logInfo = "INFO"
logDebug = "DEBUG"
logUnknown = "UNKNOWN"
)
// ParseLevel converts the specified string into the corresponding LevelType.
func ParseLevel(s string) (lt LevelType, err error) {
switch strings.ToUpper(s) {
case logFatal:
lt = LogFatal
case logPanic:
lt = LogPanic
case logError:
lt = LogError
case logWarning:
lt = LogWarning
case logInfo:
lt = LogInfo
case logDebug:
lt = LogDebug
default:
err = fmt.Errorf("bad log level '%s'", s)
}
return
}
// String implements the stringer interface for LevelType.
func (lt LevelType) String() string {
switch lt {
case LogNone:
return logNone
case LogFatal:
return logFatal
case LogPanic:
return logPanic
case LogError:
return logError
case LogWarning:
return logWarning
case LogInfo:
return logInfo
case LogDebug:
return logDebug
default:
return logUnknown
}
}
// Filter defines functions for filtering HTTP request/response content.
type Filter struct {
// URL returns a potentially modified string representation of a request URL.
URL func(u *url.URL) string
// Header returns a potentially modified set of values for the specified key.
// To completely exclude the header key/values return false.
Header func(key string, val []string) (bool, []string)
// Body returns a potentially modified request/response body.
Body func(b []byte) []byte
}
func (f Filter) processURL(u *url.URL) string {
if f.URL == nil {
return u.String()
}
return f.URL(u)
}
func (f Filter) processHeader(k string, val []string) (bool, []string) {
if f.Header == nil {
return true, val
}
return f.Header(k, val)
}
func (f Filter) processBody(b []byte) []byte {
if f.Body == nil {
return b
}
return f.Body(b)
}
// Writer defines methods for writing to a logging facility.
type Writer interface {
// Writeln writes the specified message with the standard log entry header and new-line character.
Writeln(level LevelType, message string)
// Writef writes the specified format specifier with the standard log entry header and no new-line character.
Writef(level LevelType, format string, a ...interface{})
// WriteRequest writes the specified HTTP request to the logger if the log level is greater than
// or equal to LogInfo. The request body, if set, is logged at level LogDebug or higher.
// Custom filters can be specified to exclude URL, header, and/or body content from the log.
// By default no request content is excluded.
WriteRequest(req *http.Request, filter Filter)
// WriteResponse writes the specified HTTP response to the logger if the log level is greater than
// or equal to LogInfo. The response body, if set, is logged at level LogDebug or higher.
// Custom filters can be specified to exclude URL, header, and/or body content from the log.
// By default no respone content is excluded.
WriteResponse(resp *http.Response, filter Filter)
}
// Instance is the default log writer initialized during package init.
// This can be replaced with a custom implementation as required.
var Instance Writer
// default log level
var logLevel = LogNone
// Level returns the value specified in AZURE_GO_AUTOREST_LOG_LEVEL.
// If no value was specified the default value is LogNone.
// Custom loggers can call this to retrieve the configured log level.
func Level() LevelType {
return logLevel
}
func init() {
// separated for testing purposes
initDefaultLogger()
}
func initDefaultLogger() {
// init with nilLogger so callers don't have to do a nil check on Default
Instance = nilLogger{}
llStr := strings.ToLower(os.Getenv("AZURE_GO_SDK_LOG_LEVEL"))
if llStr == "" {
return
}
var err error
logLevel, err = ParseLevel(llStr)
if err != nil {
fmt.Fprintf(os.Stderr, "go-autorest: failed to parse log level: %s\n", err.Error())
return
}
if logLevel == LogNone {
return
}
// default to stderr
dest := os.Stderr
lfStr := os.Getenv("AZURE_GO_SDK_LOG_FILE")
if strings.EqualFold(lfStr, "stdout") {
dest = os.Stdout
} else if lfStr != "" {
lf, err := os.Create(lfStr)
if err == nil {
dest = lf
} else {
fmt.Fprintf(os.Stderr, "go-autorest: failed to create log file, using stderr: %s\n", err.Error())
}
}
Instance = fileLogger{
logLevel: logLevel,
mu: &sync.Mutex{},
logFile: dest,
}
}
// the nil logger does nothing
type nilLogger struct{}
func (nilLogger) Writeln(LevelType, string) {}
func (nilLogger) Writef(LevelType, string, ...interface{}) {}
func (nilLogger) WriteRequest(*http.Request, Filter) {}
func (nilLogger) WriteResponse(*http.Response, Filter) {}
// A File is used instead of a Logger so the stream can be flushed after every write.
type fileLogger struct {
logLevel LevelType
mu *sync.Mutex // for synchronizing writes to logFile
logFile *os.File
}
func (fl fileLogger) Writeln(level LevelType, message string) {
fl.Writef(level, "%s\n", message)
}
func (fl fileLogger) Writef(level LevelType, format string, a ...interface{}) {
if fl.logLevel >= level {
fl.mu.Lock()
defer fl.mu.Unlock()
fmt.Fprintf(fl.logFile, "%s %s", entryHeader(level), fmt.Sprintf(format, a...))
fl.logFile.Sync()
}
}
func (fl fileLogger) WriteRequest(req *http.Request, filter Filter) {
if req == nil || fl.logLevel < LogInfo {
return
}
b := &bytes.Buffer{}
fmt.Fprintf(b, "%s REQUEST: %s %s\n", entryHeader(LogInfo), req.Method, filter.processURL(req.URL))
// dump headers
for k, v := range req.Header {
if ok, mv := filter.processHeader(k, v); ok {
fmt.Fprintf(b, "%s: %s\n", k, strings.Join(mv, ","))
}
}
if fl.shouldLogBody(req.Header, req.Body) {
// dump body
body, err := ioutil.ReadAll(req.Body)
if err == nil {
fmt.Fprintln(b, string(filter.processBody(body)))
if nc, ok := req.Body.(io.Seeker); ok {
// rewind to the beginning
nc.Seek(0, io.SeekStart)
} else {
// recreate the body
req.Body = ioutil.NopCloser(bytes.NewReader(body))
}
} else {
fmt.Fprintf(b, "failed to read body: %v\n", err)
}
}
fl.mu.Lock()
defer fl.mu.Unlock()
fmt.Fprintf(fl.logFile, b.String())
fl.logFile.Sync()
}
func (fl fileLogger) WriteResponse(resp *http.Response, filter Filter) {
if resp == nil || fl.logLevel < LogInfo {
return
}
b := &bytes.Buffer{}
fmt.Fprintf(b, "%s RESPONSE: %d %s\n", entryHeader(LogInfo), resp.StatusCode, filter.processURL(resp.Request.URL))
// dump headers
for k, v := range resp.Header {
if ok, mv := filter.processHeader(k, v); ok {
fmt.Fprintf(b, "%s: %s\n", k, strings.Join(mv, ","))
}
}
if fl.shouldLogBody(resp.Header, resp.Body) {
// dump body
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err == nil {
fmt.Fprintln(b, string(filter.processBody(body)))
resp.Body = ioutil.NopCloser(bytes.NewReader(body))
} else {
fmt.Fprintf(b, "failed to read body: %v\n", err)
}
}
fl.mu.Lock()
defer fl.mu.Unlock()
fmt.Fprintf(fl.logFile, b.String())
fl.logFile.Sync()
}
// returns true if the provided body should be included in the log
func (fl fileLogger) shouldLogBody(header http.Header, body io.ReadCloser) bool {
ct := header.Get("Content-Type")
return fl.logLevel >= LogDebug && body != nil && strings.Index(ct, "application/octet-stream") == -1
}
// creates standard header for log entries, it contains a timestamp and the log level
func entryHeader(level LevelType) string {
// this format provides a fixed number of digits so the size of the timestamp is constant
return fmt.Sprintf("(%s) %s:", time.Now().Format("2006-01-02T15:04:05.0000000Z07:00"), level.String())
}

37
vendor/github.com/Azure/go-autorest/version/version.go generated vendored Normal file
View File

@@ -0,0 +1,37 @@
package version
// Copyright 2017 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import (
"fmt"
"runtime"
)
// Number contains the semantic version of this SDK.
const Number = "v10.15.0"
var (
userAgent = fmt.Sprintf("Go/%s (%s-%s) go-autorest/%s",
runtime.Version(),
runtime.GOARCH,
runtime.GOOS,
Number,
)
)
// UserAgent returns a string containing the Go version, system archityecture and OS, and the go-autorest version.
func UserAgent() string {
return userAgent
}

View File

@@ -1,9 +0,0 @@
language: go
go:
- 1.4.3
- 1.5.3
- tip
script:
- go test -v ./...

View File

@@ -1,10 +0,0 @@
# How to contribute
We definitely welcome patches and contribution to this project!
### Legal requirements
In order to protect both you and ourselves, you will need to sign the
[Contributor License Agreement](https://cla.developers.google.com/clas).
You may have already signed it for other Google projects.

View File

@@ -1,13 +0,0 @@
This project was automatically exported from code.google.com/p/go-uuid
# uuid ![build status](https://travis-ci.org/pborman/uuid.svg?branch=master)
The uuid package generates and inspects UUIDs based on [RFC 4122](http://tools.ietf.org/html/rfc4122) and DCE 1.1: Authentication and Security Services.
###### Install
`go get github.com/pborman/uuid`
###### Documentation
[![GoDoc](https://godoc.org/github.com/pborman/uuid?status.svg)](http://godoc.org/github.com/pborman/uuid)
Full `go doc` style documentation for the package can be viewed online without installing this package by using the GoDoc site here:
http://godoc.org/github.com/pborman/uuid

View File

@@ -1,124 +0,0 @@
// Copyright 2014 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package uuid
import (
"bytes"
"encoding/json"
"reflect"
"testing"
)
var testUUID = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
var testArray = testUUID.Array()
func TestJSON(t *testing.T) {
type S struct {
ID1 UUID
ID2 UUID
}
s1 := S{ID1: testUUID}
data, err := json.Marshal(&s1)
if err != nil {
t.Fatal(err)
}
var s2 S
if err := json.Unmarshal(data, &s2); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(&s1, &s2) {
t.Errorf("got %#v, want %#v", s2, s1)
}
}
func TestJSONArray(t *testing.T) {
type S struct {
ID1 Array
ID2 Array
}
s1 := S{ID1: testArray}
data, err := json.Marshal(&s1)
if err != nil {
t.Fatal(err)
}
var s2 S
if err := json.Unmarshal(data, &s2); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(&s1, &s2) {
t.Errorf("got %#v, want %#v", s2, s1)
}
}
func TestMarshal(t *testing.T) {
data, err := testUUID.MarshalBinary()
if err != nil {
t.Fatalf("MarhsalBinary returned unexpected error %v", err)
}
if !bytes.Equal(data, testUUID) {
t.Fatalf("MarhsalBinary returns %x, want %x", data, testUUID)
}
var u UUID
u.UnmarshalBinary(data)
if !Equal(data, u) {
t.Fatalf("UnmarhsalBinary returns %v, want %v", u, testUUID)
}
}
func TestMarshalArray(t *testing.T) {
data, err := testArray.MarshalBinary()
if err != nil {
t.Fatalf("MarhsalBinary returned unexpected error %v", err)
}
if !bytes.Equal(data, testUUID) {
t.Fatalf("MarhsalBinary returns %x, want %x", data, testUUID)
}
var a Array
a.UnmarshalBinary(data)
if a != testArray {
t.Fatalf("UnmarhsalBinary returns %v, want %v", a, testArray)
}
}
func TestMarshalTextArray(t *testing.T) {
data, err := testArray.MarshalText()
if err != nil {
t.Fatalf("MarhsalText returned unexpected error %v", err)
}
var a Array
a.UnmarshalText(data)
if a != testArray {
t.Fatalf("UnmarhsalText returns %v, want %v", a, testArray)
}
}
func BenchmarkUUID_MarshalJSON(b *testing.B) {
x := &struct {
UUID UUID `json:"uuid"`
}{}
x.UUID = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
if x.UUID == nil {
b.Fatal("invalid uuid")
}
for i := 0; i < b.N; i++ {
js, err := json.Marshal(x)
if err != nil {
b.Fatalf("marshal json: %#v (%v)", js, err)
}
}
}
func BenchmarkUUID_UnmarshalJSON(b *testing.B) {
js := []byte(`{"uuid":"f47ac10b-58cc-0372-8567-0e02b2c3d479"}`)
var x *struct {
UUID UUID `json:"uuid"`
}
for i := 0; i < b.N; i++ {
err := json.Unmarshal(js, &x)
if err != nil {
b.Fatalf("marshal json: %#v (%v)", js, err)
}
}
}

View File

@@ -5,13 +5,15 @@
package uuid
import (
"net"
"sync"
)
var (
nodeMu sync.Mutex
ifname string // name of interface being used
nodeID []byte // hardware for version 1 UUIDs
nodeMu sync.Mutex
interfaces []net.Interface // cached list of interfaces
ifname string // name of interface being used
nodeID []byte // hardware for version 1 UUIDs
)
// NodeInterface returns the name of the interface from which the NodeID was
@@ -32,18 +34,25 @@ func NodeInterface() string {
func SetNodeInterface(name string) bool {
defer nodeMu.Unlock()
nodeMu.Lock()
if nodeID != nil {
return true
}
return setNodeInterface(name)
}
func setNodeInterface(name string) bool {
if interfaces == nil {
var err error
interfaces, err = net.Interfaces()
if err != nil && name != "" {
return false
}
}
iname, addr := getHardwareInterface(name) // null implementation for js
if iname != "" && setNodeID(addr) {
ifname = iname
return true
for _, ifs := range interfaces {
if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) {
if setNodeID(ifs.HardwareAddr) {
ifname = ifs.Name
return true
}
}
}
// We found no interfaces with a valid hardware address. If name

View File

@@ -1,12 +0,0 @@
// Copyright 2017 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build js
package uuid
// getHardwareInterface returns nil values for the JS version of the code.
// This remvoves the "net" dependency, because it is not used in the browser.
// Using the "net" library inflates the size of the transpiled JS code by 673k bytes.
func getHardwareInterface(name string) (string, []byte) { return "", nil }

View File

@@ -1,36 +0,0 @@
// Copyright 2017 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !js
package uuid
import "net"
var interfaces []net.Interface // cached list of interfaces
// getHardwareInterface returns the name and hardware address of interface name.
// If name is "" then the name and hardware address of one of the system's
// interfaces is returned. If no interfaces are found (name does not exist or
// there are no interfaces) then "", nil is returned.
//
// Only addresses of at least 6 bytes are returned.
func getHardwareInterface(name string) (string, []byte) {
if interfaces == nil {
var err error
interfaces, err = net.Interfaces()
if err != nil {
return "", nil
}
}
for _, ifs := range interfaces {
if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) {
if setNodeID(ifs.HardwareAddr) {
ifname = ifs.Name
return ifname, nodeID
}
}
}
return "", nil
}

View File

@@ -1,66 +0,0 @@
// Copyright 2014 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package uuid
import (
"flag"
"runtime"
"testing"
"time"
)
// This test is only run when --regressions is passed on the go test line.
var regressions = flag.Bool("regressions", false, "run uuid regression tests")
// TestClockSeqRace tests for a particular race condition of returning two
// identical Version1 UUIDs. The duration of 1 minute was chosen as the race
// condition, before being fixed, nearly always occured in under 30 seconds.
func TestClockSeqRace(t *testing.T) {
if !*regressions {
t.Skip("skipping regression tests")
}
duration := time.Minute
done := make(chan struct{})
defer close(done)
ch := make(chan UUID, 10000)
ncpu := runtime.NumCPU()
switch ncpu {
case 0, 1:
// We can't run the test effectively.
t.Skip("skipping race test, only one CPU detected")
return
default:
runtime.GOMAXPROCS(ncpu)
}
for i := 0; i < ncpu; i++ {
go func() {
for {
select {
case <-done:
return
case ch <- NewUUID():
}
}
}()
}
uuids := make(map[string]bool)
cnt := 0
start := time.Now()
for u := range ch {
s := u.String()
if uuids[s] {
t.Errorf("duplicate uuid after %d in %v: %s", cnt, time.Since(start), s)
return
}
uuids[s] = true
if time.Since(start) > duration {
return
}
cnt++
}
}

View File

@@ -1,96 +0,0 @@
// Copyright 2015 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package uuid
import (
"strings"
"testing"
)
func TestScan(t *testing.T) {
var stringTest string = "f47ac10b-58cc-0372-8567-0e02b2c3d479"
var byteTest []byte = Parse(stringTest)
var badTypeTest int = 6
var invalidTest string = "f47ac10b-58cc-0372-8567-0e02b2c3d4"
// sunny day tests
var uuid UUID
err := (&uuid).Scan(stringTest)
if err != nil {
t.Fatal(err)
}
err = (&uuid).Scan([]byte(stringTest))
if err != nil {
t.Fatal(err)
}
err = (&uuid).Scan(byteTest)
if err != nil {
t.Fatal(err)
}
// bad type tests
err = (&uuid).Scan(badTypeTest)
if err == nil {
t.Error("int correctly parsed and shouldn't have")
}
if !strings.Contains(err.Error(), "unable to scan type") {
t.Error("attempting to parse an int returned an incorrect error message")
}
// invalid/incomplete uuids
err = (&uuid).Scan(invalidTest)
if err == nil {
t.Error("invalid uuid was parsed without error")
}
if !strings.Contains(err.Error(), "invalid UUID") {
t.Error("attempting to parse an invalid UUID returned an incorrect error message")
}
err = (&uuid).Scan(byteTest[:len(byteTest)-2])
if err == nil {
t.Error("invalid byte uuid was parsed without error")
}
if !strings.Contains(err.Error(), "invalid UUID") {
t.Error("attempting to parse an invalid byte UUID returned an incorrect error message")
}
// empty tests
uuid = nil
var emptySlice []byte
err = (&uuid).Scan(emptySlice)
if err != nil {
t.Fatal(err)
}
if uuid != nil {
t.Error("UUID was not nil after scanning empty byte slice")
}
uuid = nil
var emptyString string
err = (&uuid).Scan(emptyString)
if err != nil {
t.Fatal(err)
}
if uuid != nil {
t.Error("UUID was not nil after scanning empty string")
}
}
func TestValue(t *testing.T) {
stringTest := "f47ac10b-58cc-0372-8567-0e02b2c3d479"
uuid := Parse(stringTest)
val, _ := uuid.Value()
if val != stringTest {
t.Error("Value() did not return expected string")
}
}

View File

@@ -1,552 +0,0 @@
// Copyright 2011 Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package uuid
import (
"bytes"
"fmt"
"os"
"runtime"
"strings"
"testing"
"time"
)
type test struct {
in string
version Version
variant Variant
isuuid bool
}
var tests = []test{
{"f47ac10b-58cc-0372-8567-0e02b2c3d479", 0, RFC4122, true},
{"f47ac10b-58cc-1372-8567-0e02b2c3d479", 1, RFC4122, true},
{"f47ac10b-58cc-2372-8567-0e02b2c3d479", 2, RFC4122, true},
{"f47ac10b-58cc-3372-8567-0e02b2c3d479", 3, RFC4122, true},
{"f47ac10b-58cc-4372-8567-0e02b2c3d479", 4, RFC4122, true},
{"f47ac10b-58cc-5372-8567-0e02b2c3d479", 5, RFC4122, true},
{"f47ac10b-58cc-6372-8567-0e02b2c3d479", 6, RFC4122, true},
{"f47ac10b-58cc-7372-8567-0e02b2c3d479", 7, RFC4122, true},
{"f47ac10b-58cc-8372-8567-0e02b2c3d479", 8, RFC4122, true},
{"f47ac10b-58cc-9372-8567-0e02b2c3d479", 9, RFC4122, true},
{"f47ac10b-58cc-a372-8567-0e02b2c3d479", 10, RFC4122, true},
{"f47ac10b-58cc-b372-8567-0e02b2c3d479", 11, RFC4122, true},
{"f47ac10b-58cc-c372-8567-0e02b2c3d479", 12, RFC4122, true},
{"f47ac10b-58cc-d372-8567-0e02b2c3d479", 13, RFC4122, true},
{"f47ac10b-58cc-e372-8567-0e02b2c3d479", 14, RFC4122, true},
{"f47ac10b-58cc-f372-8567-0e02b2c3d479", 15, RFC4122, true},
{"urn:uuid:f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true},
{"URN:UUID:f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true},
{"f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true},
{"f47ac10b-58cc-4372-1567-0e02b2c3d479", 4, Reserved, true},
{"f47ac10b-58cc-4372-2567-0e02b2c3d479", 4, Reserved, true},
{"f47ac10b-58cc-4372-3567-0e02b2c3d479", 4, Reserved, true},
{"f47ac10b-58cc-4372-4567-0e02b2c3d479", 4, Reserved, true},
{"f47ac10b-58cc-4372-5567-0e02b2c3d479", 4, Reserved, true},
{"f47ac10b-58cc-4372-6567-0e02b2c3d479", 4, Reserved, true},
{"f47ac10b-58cc-4372-7567-0e02b2c3d479", 4, Reserved, true},
{"f47ac10b-58cc-4372-8567-0e02b2c3d479", 4, RFC4122, true},
{"f47ac10b-58cc-4372-9567-0e02b2c3d479", 4, RFC4122, true},
{"f47ac10b-58cc-4372-a567-0e02b2c3d479", 4, RFC4122, true},
{"f47ac10b-58cc-4372-b567-0e02b2c3d479", 4, RFC4122, true},
{"f47ac10b-58cc-4372-c567-0e02b2c3d479", 4, Microsoft, true},
{"f47ac10b-58cc-4372-d567-0e02b2c3d479", 4, Microsoft, true},
{"f47ac10b-58cc-4372-e567-0e02b2c3d479", 4, Future, true},
{"f47ac10b-58cc-4372-f567-0e02b2c3d479", 4, Future, true},
{"f47ac10b158cc-5372-a567-0e02b2c3d479", 0, Invalid, false},
{"f47ac10b-58cc25372-a567-0e02b2c3d479", 0, Invalid, false},
{"f47ac10b-58cc-53723a567-0e02b2c3d479", 0, Invalid, false},
{"f47ac10b-58cc-5372-a56740e02b2c3d479", 0, Invalid, false},
{"f47ac10b-58cc-5372-a567-0e02-2c3d479", 0, Invalid, false},
{"g47ac10b-58cc-4372-a567-0e02b2c3d479", 0, Invalid, false},
}
var constants = []struct {
c interface{}
name string
}{
{Person, "Person"},
{Group, "Group"},
{Org, "Org"},
{Invalid, "Invalid"},
{RFC4122, "RFC4122"},
{Reserved, "Reserved"},
{Microsoft, "Microsoft"},
{Future, "Future"},
{Domain(17), "Domain17"},
{Variant(42), "BadVariant42"},
}
func testTest(t *testing.T, in string, tt test) {
uuid := Parse(in)
if ok := (uuid != nil); ok != tt.isuuid {
t.Errorf("Parse(%s) got %v expected %v\b", in, ok, tt.isuuid)
}
if uuid == nil {
return
}
if v := uuid.Variant(); v != tt.variant {
t.Errorf("Variant(%s) got %d expected %d\b", in, v, tt.variant)
}
if v, _ := uuid.Version(); v != tt.version {
t.Errorf("Version(%s) got %d expected %d\b", in, v, tt.version)
}
}
func TestUUID(t *testing.T) {
for _, tt := range tests {
testTest(t, tt.in, tt)
testTest(t, strings.ToUpper(tt.in), tt)
}
}
func TestConstants(t *testing.T) {
for x, tt := range constants {
v, ok := tt.c.(fmt.Stringer)
if !ok {
t.Errorf("%x: %v: not a stringer", x, v)
} else if s := v.String(); s != tt.name {
v, _ := tt.c.(int)
t.Errorf("%x: Constant %T:%d gives %q, expected %q", x, tt.c, v, s, tt.name)
}
}
}
func TestRandomUUID(t *testing.T) {
m := make(map[string]bool)
for x := 1; x < 32; x++ {
uuid := NewRandom()
s := uuid.String()
if m[s] {
t.Errorf("NewRandom returned duplicated UUID %s", s)
}
m[s] = true
if v, _ := uuid.Version(); v != 4 {
t.Errorf("Random UUID of version %s", v)
}
if uuid.Variant() != RFC4122 {
t.Errorf("Random UUID is variant %d", uuid.Variant())
}
}
}
func TestNew(t *testing.T) {
m := make(map[string]bool)
for x := 1; x < 32; x++ {
s := New()
if m[s] {
t.Errorf("New returned duplicated UUID %s", s)
}
m[s] = true
uuid := Parse(s)
if uuid == nil {
t.Errorf("New returned %q which does not decode", s)
continue
}
if v, _ := uuid.Version(); v != 4 {
t.Errorf("Random UUID of version %s", v)
}
if uuid.Variant() != RFC4122 {
t.Errorf("Random UUID is variant %d", uuid.Variant())
}
}
}
func clockSeq(t *testing.T, uuid UUID) int {
seq, ok := uuid.ClockSequence()
if !ok {
t.Fatalf("%s: invalid clock sequence", uuid)
}
return seq
}
func TestClockSeq(t *testing.T) {
// Fake time.Now for this test to return a monotonically advancing time; restore it at end.
defer func(orig func() time.Time) { timeNow = orig }(timeNow)
monTime := time.Now()
timeNow = func() time.Time {
monTime = monTime.Add(1 * time.Second)
return monTime
}
SetClockSequence(-1)
uuid1 := NewUUID()
uuid2 := NewUUID()
if clockSeq(t, uuid1) != clockSeq(t, uuid2) {
t.Errorf("clock sequence %d != %d", clockSeq(t, uuid1), clockSeq(t, uuid2))
}
SetClockSequence(-1)
uuid2 = NewUUID()
// Just on the very off chance we generated the same sequence
// two times we try again.
if clockSeq(t, uuid1) == clockSeq(t, uuid2) {
SetClockSequence(-1)
uuid2 = NewUUID()
}
if clockSeq(t, uuid1) == clockSeq(t, uuid2) {
t.Errorf("Duplicate clock sequence %d", clockSeq(t, uuid1))
}
SetClockSequence(0x1234)
uuid1 = NewUUID()
if seq := clockSeq(t, uuid1); seq != 0x1234 {
t.Errorf("%s: expected seq 0x1234 got 0x%04x", uuid1, seq)
}
}
func TestCoding(t *testing.T) {
text := "7d444840-9dc0-11d1-b245-5ffdce74fad2"
urn := "urn:uuid:7d444840-9dc0-11d1-b245-5ffdce74fad2"
data := UUID{
0x7d, 0x44, 0x48, 0x40,
0x9d, 0xc0,
0x11, 0xd1,
0xb2, 0x45,
0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2,
}
if v := data.String(); v != text {
t.Errorf("%x: encoded to %s, expected %s", data, v, text)
}
if v := data.URN(); v != urn {
t.Errorf("%x: urn is %s, expected %s", data, v, urn)
}
uuid := Parse(text)
if !Equal(uuid, data) {
t.Errorf("%s: decoded to %s, expected %s", text, uuid, data)
}
}
func TestVersion1(t *testing.T) {
uuid1 := NewUUID()
uuid2 := NewUUID()
if Equal(uuid1, uuid2) {
t.Errorf("%s:duplicate uuid", uuid1)
}
if v, _ := uuid1.Version(); v != 1 {
t.Errorf("%s: version %s expected 1", uuid1, v)
}
if v, _ := uuid2.Version(); v != 1 {
t.Errorf("%s: version %s expected 1", uuid2, v)
}
n1 := uuid1.NodeID()
n2 := uuid2.NodeID()
if !bytes.Equal(n1, n2) {
t.Errorf("Different nodes %x != %x", n1, n2)
}
t1, ok := uuid1.Time()
if !ok {
t.Errorf("%s: invalid time", uuid1)
}
t2, ok := uuid2.Time()
if !ok {
t.Errorf("%s: invalid time", uuid2)
}
q1, ok := uuid1.ClockSequence()
if !ok {
t.Errorf("%s: invalid clock sequence", uuid1)
}
q2, ok := uuid2.ClockSequence()
if !ok {
t.Errorf("%s: invalid clock sequence", uuid2)
}
switch {
case t1 == t2 && q1 == q2:
t.Error("time stopped")
case t1 > t2 && q1 == q2:
t.Error("time reversed")
case t1 < t2 && q1 != q2:
t.Error("clock sequence chaned unexpectedly")
}
}
func TestNode(t *testing.T) {
// This test is mostly to make sure we don't leave nodeMu locked.
ifname = ""
if ni := NodeInterface(); ni != "" {
t.Errorf("NodeInterface got %q, want %q", ni, "")
}
nodeID = nil // Reset global state for next test
if SetNodeInterface("xyzzy") {
t.Error("SetNodeInterface succeeded on a bad interface name")
}
nodeID = nil // Reset global state for next test
if !SetNodeInterface("") {
t.Error("SetNodeInterface failed")
}
if runtime.GOARCH != "js" {
if ni := NodeInterface(); ni == "" {
t.Error("NodeInterface returned an empty string")
}
}
ni := NodeID()
if len(ni) != 6 {
t.Errorf("ni got %d bytes, want 6", len(ni))
}
hasData := false
for _, b := range ni {
if b != 0 {
hasData = true
}
}
if !hasData {
t.Error("nodeid is all zeros")
}
id := []byte{1, 2, 3, 4, 5, 6, 7, 8}
SetNodeID(id)
ni = NodeID()
if !bytes.Equal(ni, id[:6]) {
t.Errorf("got nodeid %v, want %v", ni, id[:6])
}
if ni := NodeInterface(); ni != "user" {
t.Errorf("got inteface %q, want %q", ni, "user")
}
}
func TestNodeAndTime(t *testing.T) {
// Time is February 5, 1998 12:30:23.136364800 AM GMT
uuid := Parse("7d444840-9dc0-11d1-b245-5ffdce74fad2")
node := []byte{0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2}
ts, ok := uuid.Time()
if ok {
c := time.Unix(ts.UnixTime())
want := time.Date(1998, 2, 5, 0, 30, 23, 136364800, time.UTC)
if !c.Equal(want) {
t.Errorf("Got time %v, want %v", c, want)
}
} else {
t.Errorf("%s: bad time", uuid)
}
if !bytes.Equal(node, uuid.NodeID()) {
t.Errorf("Expected node %v got %v", node, uuid.NodeID())
}
}
func TestMD5(t *testing.T) {
uuid := NewMD5(NameSpace_DNS, []byte("python.org")).String()
want := "6fa459ea-ee8a-3ca4-894e-db77e160355e"
if uuid != want {
t.Errorf("MD5: got %q expected %q", uuid, want)
}
}
func TestSHA1(t *testing.T) {
uuid := NewSHA1(NameSpace_DNS, []byte("python.org")).String()
want := "886313e1-3b8a-5372-9b90-0c9aee199e5d"
if uuid != want {
t.Errorf("SHA1: got %q expected %q", uuid, want)
}
}
func TestNodeID(t *testing.T) {
nid := []byte{1, 2, 3, 4, 5, 6}
nodeID = nil // Reset global state for next test
SetNodeInterface("")
s := NodeInterface()
if runtime.GOARCH != "js" {
if s == "" || s == "user" {
t.Errorf("NodeInterface %q after SetInterface", s)
}
}
node1 := NodeID()
if node1 == nil {
t.Error("NodeID nil after SetNodeInterface", s)
}
SetNodeID(nid)
s = NodeInterface()
if s != "user" {
t.Errorf("Expected NodeInterface %q got %q", "user", s)
}
node2 := NodeID()
if node2 == nil {
t.Error("NodeID nil after SetNodeID", s)
}
if bytes.Equal(node1, node2) {
t.Error("NodeID not changed after SetNodeID", s)
} else if !bytes.Equal(nid, node2) {
t.Errorf("NodeID is %x, expected %x", node2, nid)
}
}
func testDCE(t *testing.T, name string, uuid UUID, domain Domain, id uint32) {
if uuid == nil {
t.Errorf("%s failed", name)
return
}
if v, _ := uuid.Version(); v != 2 {
t.Errorf("%s: %s: expected version 2, got %s", name, uuid, v)
return
}
if v, ok := uuid.Domain(); !ok || v != domain {
if !ok {
t.Errorf("%s: %d: Domain failed", name, uuid)
} else {
t.Errorf("%s: %s: expected domain %d, got %d", name, uuid, domain, v)
}
}
if v, ok := uuid.Id(); !ok || v != id {
if !ok {
t.Errorf("%s: %d: Id failed", name, uuid)
} else {
t.Errorf("%s: %s: expected id %d, got %d", name, uuid, id, v)
}
}
}
func TestDCE(t *testing.T) {
testDCE(t, "NewDCESecurity", NewDCESecurity(42, 12345678), 42, 12345678)
testDCE(t, "NewDCEPerson", NewDCEPerson(), Person, uint32(os.Getuid()))
testDCE(t, "NewDCEGroup", NewDCEGroup(), Group, uint32(os.Getgid()))
}
type badRand struct{}
func (r badRand) Read(buf []byte) (int, error) {
for i, _ := range buf {
buf[i] = byte(i)
}
return len(buf), nil
}
func TestBadRand(t *testing.T) {
SetRand(badRand{})
uuid1 := New()
uuid2 := New()
if uuid1 != uuid2 {
t.Errorf("expected duplicates, got %q and %q", uuid1, uuid2)
}
SetRand(nil)
uuid1 = New()
uuid2 = New()
if uuid1 == uuid2 {
t.Errorf("unexpected duplicates, got %q", uuid1)
}
}
func TestUUID_Array(t *testing.T) {
expect := Array{
0xf4, 0x7a, 0xc1, 0x0b,
0x58, 0xcc,
0x03, 0x72,
0x85, 0x67,
0x0e, 0x02, 0xb2, 0xc3, 0xd4, 0x79,
}
uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
if uuid == nil {
t.Fatal("invalid uuid")
}
if uuid.Array() != expect {
t.Fatal("invalid array")
}
}
func TestArray_UUID(t *testing.T) {
array := Array{
0xf4, 0x7a, 0xc1, 0x0b,
0x58, 0xcc,
0x03, 0x72,
0x85, 0x67,
0x0e, 0x02, 0xb2, 0xc3, 0xd4, 0x79,
}
expect := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
if expect == nil {
t.Fatal("invalid uuid")
}
if !bytes.Equal(array.UUID(), expect) {
t.Fatal("invalid uuid")
}
}
func BenchmarkParse(b *testing.B) {
for i := 0; i < b.N; i++ {
uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
if uuid == nil {
b.Fatal("invalid uuid")
}
}
}
func BenchmarkNew(b *testing.B) {
for i := 0; i < b.N; i++ {
New()
}
}
func BenchmarkUUID_String(b *testing.B) {
uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
if uuid == nil {
b.Fatal("invalid uuid")
}
for i := 0; i < b.N; i++ {
if uuid.String() == "" {
b.Fatal("invalid uuid")
}
}
}
func BenchmarkUUID_URN(b *testing.B) {
uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
if uuid == nil {
b.Fatal("invalid uuid")
}
for i := 0; i < b.N; i++ {
if uuid.URN() == "" {
b.Fatal("invalid uuid")
}
}
}
func BenchmarkUUID_Array(b *testing.B) {
expect := Array{
0xf4, 0x7a, 0xc1, 0x0b,
0x58, 0xcc,
0x03, 0x72,
0x85, 0x67,
0x0e, 0x02, 0xb2, 0xc3, 0xd4, 0x79,
}
uuid := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
if uuid == nil {
b.Fatal("invalid uuid")
}
for i := 0; i < b.N; i++ {
if uuid.Array() != expect {
b.Fatal("invalid array")
}
}
}
func BenchmarkArray_UUID(b *testing.B) {
array := Array{
0xf4, 0x7a, 0xc1, 0x0b,
0x58, 0xcc,
0x03, 0x72,
0x85, 0x67,
0x0e, 0x02, 0xb2, 0xc3, 0xd4, 0x79,
}
expect := Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479")
if expect == nil {
b.Fatal("invalid uuid")
}
for i := 0; i < b.N; i++ {
if !bytes.Equal(array.UUID(), expect) {
b.Fatal("invalid uuid")
}
}
}

View File

@@ -15,7 +15,9 @@ import (
// SetClockSequence then it will be set automatically. If GetTime fails to
// return the current NewUUID returns nil.
func NewUUID() UUID {
SetNodeInterface("")
if nodeID == nil {
SetNodeInterface("")
}
now, seq, err := GetTime()
if err != nil {

8320
vendor/github.com/vmware/vic/LICENSE generated vendored

File diff suppressed because it is too large Load Diff

View File

@@ -2,13 +2,13 @@ NOTICE
vSphere Integrated Containers Engine
Copyright (c) 2016-2017 VMware, Inc. All Rights Reserved.
Copyright (c) 2016-2018 VMware, Inc. All Rights Reserved.
This product is licensed to you under the Apache License, Version 2.0 (the
"License"). You may not use this product except in compliance with the
License.
This product may include a number of components with separate copyright
notices and license terms. Your use of the source code for these components is
subject to the terms and conditions of the component's license, as noted in
the LICENSE file.
This product may include a number of components with separate copyright notices
and license terms. Your use of the source code for these components is subject
to the terms and conditions of the component's license, as noted in the LICENSE
file.

View File

@@ -34,6 +34,14 @@ func (e InvalidVolumeError) Error() string {
return fmt.Sprintf("mounting directories as a data volume is not supported.")
}
type VolumeExistError struct {
Volume string
}
func (e VolumeExistError) Error() string {
return fmt.Sprintf("A volume named %s already exists. Choose a different volume name.", e.Volume)
}
// InvalidBindError is returned when create/run -v has more params than allowed.
type InvalidBindError struct {
Volume string
@@ -187,6 +195,12 @@ func IsServerNotReady(err error) bool {
return ok
}
func IsVolumeExistError(err error) bool {
_, ok := err.(VolumeExistError)
return ok
}
type DetachError struct{}
func (DetachError) Error() string {

View File

@@ -33,7 +33,7 @@ import (
"github.com/docker/docker/api/types"
)
type VicArchiveProxy interface {
type ArchiveProxy interface {
ArchiveExportReader(op trace.Operation, store, ancestorStore, deviceID, ancestor string, data bool, filterSpec archive.FilterSpec) (io.ReadCloser, error)
ArchiveImportWriter(op trace.Operation, store, deviceID string, filterSpec archive.FilterSpec, wg *sync.WaitGroup, errchan chan error) (io.WriteCloser, error)
StatPath(op trace.Operation, store, deviceID string, filterSpec archive.FilterSpec) (*types.ContainerPathStat, error)
@@ -43,23 +43,23 @@ type VicArchiveProxy interface {
// ArchiveProxy
//------------------------------------
type ArchiveProxy struct {
type VicArchiveProxy struct {
client *client.PortLayer
}
var archiveProxy *ArchiveProxy
var archiveProxy *VicArchiveProxy
func NewArchiveProxy(client *client.PortLayer) VicArchiveProxy {
return &ArchiveProxy{client: client}
func NewArchiveProxy(client *client.PortLayer) *VicArchiveProxy {
return &VicArchiveProxy{client: client}
}
func GetArchiveProxy() VicArchiveProxy {
func GetArchiveProxy() ArchiveProxy {
return archiveProxy
}
// ArchiveExportReader streams a tar archive from the portlayer. Once the stream is complete,
// an io.Reader is returned and the caller can use that reader to parse the data.
func (a *ArchiveProxy) ArchiveExportReader(op trace.Operation, store, ancestorStore, deviceID, ancestor string, data bool, filterSpec archive.FilterSpec) (io.ReadCloser, error) {
func (a *VicArchiveProxy) ArchiveExportReader(op trace.Operation, store, ancestorStore, deviceID, ancestor string, data bool, filterSpec archive.FilterSpec) (io.ReadCloser, error) {
defer trace.End(trace.Begin(deviceID))
if a.client == nil {
@@ -141,7 +141,7 @@ func (a *ArchiveProxy) ArchiveExportReader(op trace.Operation, store, ancestorSt
// ArchiveImportWriter initializes a write stream for a path. This is usually called
// for getting a writer during docker cp TO container.
func (a *ArchiveProxy) ArchiveImportWriter(op trace.Operation, store, deviceID string, filterSpec archive.FilterSpec, wg *sync.WaitGroup, errchan chan error) (io.WriteCloser, error) {
func (a *VicArchiveProxy) ArchiveImportWriter(op trace.Operation, store, deviceID string, filterSpec archive.FilterSpec, wg *sync.WaitGroup, errchan chan error) (io.WriteCloser, error) {
defer trace.End(trace.Begin(deviceID))
if a.client == nil {
@@ -232,7 +232,7 @@ func (a *ArchiveProxy) ArchiveImportWriter(op trace.Operation, store, deviceID s
// StatPath requests the portlayer to stat the filesystem resource at the
// specified path in the container vc.
func (a *ArchiveProxy) StatPath(op trace.Operation, store, deviceID string, filterSpec archive.FilterSpec) (*types.ContainerPathStat, error) {
func (a *VicArchiveProxy) StatPath(op trace.Operation, store, deviceID string, filterSpec archive.FilterSpec) (*types.ContainerPathStat, error) {
defer trace.End(trace.Begin(deviceID))
if a.client == nil {

View File

@@ -74,7 +74,7 @@ import (
)
// VicContainerProxy interface
type VicContainerProxy interface {
type ContainerProxy interface {
CreateContainerHandle(ctx context.Context, vc *viccontainer.VicContainer, config types.ContainerCreateConfig) (string, string, error)
AddImageToContainer(ctx context.Context, handle string, deltaID string, layerID string, imageID string, config types.ContainerCreateConfig) (string, error)
CreateContainerTask(ctx context.Context, handle string, id string, layerID string, config types.ContainerCreateConfig) (string, error)
@@ -91,7 +91,7 @@ type VicContainerProxy interface {
// TODO: we should not be returning a swagger model here, however we do not have a solid architected return for this yet.
InspectTask(op trace.Operation, handle string, eid string, cid string) (*models.TaskInspectResponse, error)
BindTask(op trace.Operation, handle string, eid string) (string, error)
WaitTask(op trace.Operation, cid string, cname string, eid string) error
WaitTask(op trace.Operation, handle string, cid string, eid string) error
Handle(ctx context.Context, id, name string) (string, error)
@@ -108,7 +108,7 @@ type VicContainerProxy interface {
}
// ContainerProxy struct
type ContainerProxy struct {
type VicContainerProxy struct {
client *client.PortLayer
portlayerAddr string
portlayerName string
@@ -126,20 +126,24 @@ const (
)
// NewContainerProxy will create a new proxy
func NewContainerProxy(plClient *client.PortLayer, portlayerAddr string, portlayerName string) *ContainerProxy {
return &ContainerProxy{client: plClient, portlayerAddr: portlayerAddr, portlayerName: portlayerName}
func NewContainerProxy(plClient *client.PortLayer, portlayerAddr string, portlayerName string) *VicContainerProxy {
return &VicContainerProxy{client: plClient, portlayerAddr: portlayerAddr, portlayerName: portlayerName}
}
// Handle retrieves a handle to a VIC container. Handles should be treated as opaque strings.
//
// returns:
// (handle string, error)
func (c *ContainerProxy) Handle(ctx context.Context, id, name string) (string, error) {
func (c *VicContainerProxy) Handle(ctx context.Context, id, name string) (string, error) {
op := trace.FromContext(ctx, "Handle: %s", id)
defer trace.End(trace.Begin(name, op))
opID := op.ID()
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
}
resp, err := c.client.Containers.Get(containers.NewGetParamsWithContext(ctx).WithID(id))
resp, err := c.client.Containers.Get(containers.NewGetParamsWithContext(ctx).WithOpID(&opID).WithID(id))
if err != nil {
switch err := err.(type) {
case *containers.GetNotFound:
@@ -158,8 +162,10 @@ func (c *ContainerProxy) Handle(ctx context.Context, id, name string) (string, e
//
// returns:
// (containerID, containerHandle, error)
func (c *ContainerProxy) CreateContainerHandle(ctx context.Context, vc *viccontainer.VicContainer, config types.ContainerCreateConfig) (string, string, error) {
defer trace.End(trace.Begin(vc.ImageID))
func (c *VicContainerProxy) CreateContainerHandle(ctx context.Context, vc *viccontainer.VicContainer, config types.ContainerCreateConfig) (string, string, error) {
op := trace.FromContext(ctx, "CreateContainerHandle: %s", vc.Name)
defer trace.End(trace.Begin(vc.Name, op))
opID := op.ID()
if c.client == nil {
return "", "", errors.NillPortlayerClientError("ContainerProxy")
@@ -179,12 +185,12 @@ func (c *ContainerProxy) CreateContainerHandle(ctx context.Context, vc *vicconta
return "", "", errors.InternalServerError("ContainerProxy.CreateContainerHandle got unexpected error getting VCH UUID")
}
plCreateParams := dockerContainerCreateParamsToPortlayer(ctx, config, vc, host)
plCreateParams := dockerContainerCreateParamsToPortlayer(ctx, config, vc, host).WithOpID(&opID)
createResults, err := c.client.Containers.Create(plCreateParams)
if err != nil {
if _, ok := err.(*containers.CreateNotFound); ok {
cerr := fmt.Errorf("No such image: %s", vc.ImageID)
log.Errorf("%s (%s)", cerr, err)
op.Errorf("%s (%s)", cerr, err)
return "", "", errors.NotFoundError(cerr.Error())
}
@@ -203,7 +209,7 @@ func (c *ContainerProxy) CreateContainerHandle(ctx context.Context, vc *vicconta
//
// returns:
// modified handle
func (c *ContainerProxy) AddImageToContainer(ctx context.Context, handle, deltaID, layerID, imageID string, config types.ContainerCreateConfig) (string, error) {
func (c *VicContainerProxy) AddImageToContainer(ctx context.Context, handle, deltaID, layerID, imageID string, config types.ContainerCreateConfig) (string, error) {
defer trace.End(trace.Begin(handle))
if c.client == nil {
@@ -237,20 +243,23 @@ func (c *ContainerProxy) AddImageToContainer(ctx context.Context, handle, deltaI
//
// returns:
// (containerHandle, error)
func (c *ContainerProxy) CreateContainerTask(ctx context.Context, handle, id, layerID string, config types.ContainerCreateConfig) (string, error) {
defer trace.End(trace.Begin(""))
func (c *VicContainerProxy) CreateContainerTask(ctx context.Context, handle, id, layerID string, config types.ContainerCreateConfig) (string, error) {
op := trace.FromContext(ctx, "CreateContainerTask: %s", id)
defer trace.End(trace.Begin(id, op))
opID := op.ID()
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
}
plTaskParams := dockerContainerCreateParamsToTask(ctx, id, layerID, config)
plTaskParams := dockerContainerCreateParamsToTask(op, id, layerID, config)
plTaskParams.Config.Handle = handle
plTaskParams.WithOpID(&opID)
log.Infof("*** CreateContainerTask - params = %#v", *plTaskParams.Config)
op.Infof("*** CreateContainerTask - params = %#v", *plTaskParams.Config)
responseJoin, err := c.client.Tasks.Join(plTaskParams)
if err != nil {
log.Errorf("Unable to join primary task to container: %+v", err)
op.Errorf("Unable to join primary task to container: %+v", err)
return "", errors.InternalServerError(err.Error())
}
@@ -259,10 +268,13 @@ func (c *ContainerProxy) CreateContainerTask(ctx context.Context, handle, id, la
return "", errors.InternalServerError(fmt.Sprintf("Type assertion failed on handle from task join: %#+v", handle))
}
plBindParams := tasks.NewBindParamsWithContext(ctx).WithConfig(&models.TaskBindConfig{Handle: handle, ID: id})
plBindParams := tasks.NewBindParamsWithContext(ctx).
WithOpID(&opID).
WithConfig(&models.TaskBindConfig{Handle: handle, ID: id})
responseBind, err := c.client.Tasks.Bind(plBindParams)
if err != nil {
log.Errorf("Unable to bind primary task to container: %+v", err)
op.Errorf("Unable to bind primary task to container: %+v", err)
return "", errors.InternalServerError(err.Error())
}
@@ -274,8 +286,10 @@ func (c *ContainerProxy) CreateContainerTask(ctx context.Context, handle, id, la
return handle, nil
}
func (c *ContainerProxy) CreateExecTask(ctx context.Context, handle string, config *types.ExecConfig) (string, string, error) {
defer trace.End(trace.Begin(""))
func (c *VicContainerProxy) CreateExecTask(ctx context.Context, handle string, config *types.ExecConfig) (string, string, error) {
op := trace.FromContext(ctx, "CreateExecTask: %s", handle)
defer trace.End(trace.Begin(handle, op))
opID := op.ID()
if c.client == nil {
return "", "", errors.NillPortlayerClientError("ContainerProxy")
@@ -293,7 +307,7 @@ func (c *ContainerProxy) CreateExecTask(ctx context.Context, handle string, conf
}
// call Join with JoinParams
joinparams := tasks.NewJoinParamsWithContext(ctx).WithConfig(joinconfig)
joinparams := tasks.NewJoinParamsWithContext(ctx).WithOpID(&opID).WithConfig(joinconfig)
resp, err := c.client.Tasks.Join(joinparams)
if err != nil {
return "", "", errors.InternalServerError(err.Error())
@@ -313,18 +327,21 @@ func (c *ContainerProxy) CreateExecTask(ctx context.Context, handle string, conf
//
// returns:
// modified handle
func (c *ContainerProxy) AddContainerToScope(ctx context.Context, handle string, config types.ContainerCreateConfig) (string, error) {
defer trace.End(trace.Begin(handle))
func (c *VicContainerProxy) AddContainerToScope(ctx context.Context, handle string, config types.ContainerCreateConfig) (string, error) {
op := trace.FromContext(ctx, "AddContainerToScope: %s", handle)
defer trace.End(trace.Begin(handle, op))
opID := op.ID()
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
}
log.Debugf("Network Configuration Section - Container Create")
op.Debugf("Network Configuration Section - Container Create")
// configure network
netConf := toModelsNetworkConfig(config)
if netConf != nil {
addContRes, err := c.client.Scopes.AddContainer(scopes.NewAddContainerParamsWithContext(ctx).
WithOpID(&opID).
WithScope(netConf.NetworkName).
WithConfig(&models.ScopesAddContainerConfig{
Handle: handle,
@@ -332,7 +349,7 @@ func (c *ContainerProxy) AddContainerToScope(ctx context.Context, handle string,
}))
if err != nil {
log.Errorf("ContainerProxy.AddContainerToScope: Scopes error: %s", err.Error())
op.Errorf("ContainerProxy.AddContainerToScope: Scopes error: %s", err.Error())
return handle, errors.InternalServerError(err.Error())
}
@@ -341,8 +358,11 @@ func (c *ContainerProxy) AddContainerToScope(ctx context.Context, handle string,
return
}
// roll back the AddContainer call
if _, err2 := c.client.Scopes.RemoveContainer(scopes.NewRemoveContainerParamsWithContext(ctx).WithHandle(handle).WithScope(netConf.NetworkName)); err2 != nil {
log.Warnf("could not roll back container add: %s", err2)
if _, err2 := c.client.Scopes.RemoveContainer(scopes.NewRemoveContainerParamsWithContext(ctx).
WithHandle(handle).
WithScope(netConf.NetworkName).
WithOpID(&opID)); err2 != nil {
op.Warnf("could not roll back container add: %s", err2)
}
}()
@@ -357,14 +377,17 @@ func (c *ContainerProxy) AddContainerToScope(ctx context.Context, handle string,
//
// returns:
// modified handle
func (c *ContainerProxy) AddLoggingToContainer(ctx context.Context, handle string, config types.ContainerCreateConfig) (string, error) {
defer trace.End(trace.Begin(handle))
func (c *VicContainerProxy) AddLoggingToContainer(ctx context.Context, handle string, config types.ContainerCreateConfig) (string, error) {
op := trace.FromContext(ctx, "AddLoggingToContainer: %s", handle)
defer trace.End(trace.Begin(handle, op))
opID := op.ID()
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
}
response, err := c.client.Logging.LoggingJoin(logging.NewLoggingJoinParamsWithContext(ctx).
WithOpID(&opID).
WithConfig(&models.LoggingJoinConfig{
Handle: handle,
}))
@@ -384,14 +407,17 @@ func (c *ContainerProxy) AddLoggingToContainer(ctx context.Context, handle strin
//
// returns:
// modified handle
func (c *ContainerProxy) AddInteractionToContainer(ctx context.Context, handle string, config types.ContainerCreateConfig) (string, error) {
defer trace.End(trace.Begin(handle))
func (c *VicContainerProxy) AddInteractionToContainer(ctx context.Context, handle string, config types.ContainerCreateConfig) (string, error) {
op := trace.FromContext(ctx, "AddLoggingToContainer: %s", handle)
defer trace.End(trace.Begin(handle, op))
opID := op.ID()
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
}
response, err := c.client.Interaction.InteractionJoin(interaction.NewInteractionJoinParamsWithContext(ctx).
WithOpID(&opID).
WithConfig(&models.InteractionJoinConfig{
Handle: handle,
}))
@@ -407,8 +433,10 @@ func (c *ContainerProxy) AddInteractionToContainer(ctx context.Context, handle s
}
// BindInteraction enables interaction capabilities
func (c *ContainerProxy) BindInteraction(ctx context.Context, handle string, name string, id string) (string, error) {
defer trace.End(trace.Begin(handle))
func (c *VicContainerProxy) BindInteraction(ctx context.Context, handle string, name string, id string) (string, error) {
op := trace.FromContext(ctx, "BindInteraction: %s", handle)
defer trace.End(trace.Begin(handle, op))
opID := op.ID()
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
@@ -416,6 +444,7 @@ func (c *ContainerProxy) BindInteraction(ctx context.Context, handle string, nam
bind, err := c.client.Interaction.InteractionBind(
interaction.NewInteractionBindParamsWithContext(ctx).
WithOpID(&opID).
WithConfig(&models.InteractionBindConfig{
Handle: handle,
ID: id,
@@ -436,8 +465,10 @@ func (c *ContainerProxy) BindInteraction(ctx context.Context, handle string, nam
}
// UnbindInteraction disables interaction capabilities
func (c *ContainerProxy) UnbindInteraction(ctx context.Context, handle string, name string, id string) (string, error) {
defer trace.End(trace.Begin(handle))
func (c *VicContainerProxy) UnbindInteraction(ctx context.Context, handle string, name string, id string) (string, error) {
op := trace.FromContext(ctx, "UnbindInteraction: %s", handle)
defer trace.End(trace.Begin(handle, op))
opID := op.ID()
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
@@ -445,6 +476,7 @@ func (c *ContainerProxy) UnbindInteraction(ctx context.Context, handle string, n
unbind, err := c.client.Interaction.InteractionUnbind(
interaction.NewInteractionUnbindParamsWithContext(ctx).
WithOpID(&opID).
WithConfig(&models.InteractionUnbindConfig{
Handle: handle,
ID: id,
@@ -464,18 +496,21 @@ func (c *ContainerProxy) UnbindInteraction(ctx context.Context, handle string, n
//
// Args:
// waitTime <= 0 means no wait time
func (c *ContainerProxy) CommitContainerHandle(ctx context.Context, handle, containerID string, waitTime int32) error {
defer trace.End(trace.Begin(handle))
func (c *VicContainerProxy) CommitContainerHandle(ctx context.Context, handle, containerID string, waitTime int32) error {
op := trace.FromContext(ctx, "CommitContainerHandle: %s", handle)
defer trace.End(trace.Begin(handle, op))
opID := op.ID()
if c.client == nil {
return errors.NillPortlayerClientError("ContainerProxy")
}
var commitParams *containers.CommitParams
commitParams := containers.NewCommitParamsWithContext(ctx).
WithOpID(&opID).
WithHandle(handle)
if waitTime > 0 {
commitParams = containers.NewCommitParamsWithContext(ctx).WithHandle(handle).WithWaitTime(&waitTime)
} else {
commitParams = containers.NewCommitParamsWithContext(ctx).WithHandle(handle)
commitParams.WithWaitTime(&waitTime)
}
_, err := c.client.Containers.Commit(commitParams)
@@ -495,8 +530,9 @@ func (c *ContainerProxy) CommitContainerHandle(ctx context.Context, handle, cont
return nil
}
func (c *ContainerProxy) InspectTask(op trace.Operation, handle string, eid string, cid string) (*models.TaskInspectResponse, error) {
defer trace.End(trace.Begin(fmt.Sprintf("handle(%s), eid(%s), cid(%s)", handle, eid, cid)))
func (c *VicContainerProxy) InspectTask(op trace.Operation, handle string, eid string, cid string) (*models.TaskInspectResponse, error) {
defer trace.End(trace.Begin(fmt.Sprintf("handle(%s), eid(%s), cid(%s)", handle, eid, cid), op))
opID := op.ID()
if c.client == nil {
return nil, errors.NillPortlayerClientError("ContainerProxy")
@@ -510,7 +546,7 @@ func (c *ContainerProxy) InspectTask(op trace.Operation, handle string, eid stri
// FIXME: right now we are only using this path for exec targets. But later the error messages may need to be changed
// to be more accurate.
params := tasks.NewInspectParamsWithContext(op).WithConfig(config)
params := tasks.NewInspectParamsWithContext(op).WithOpID(&opID).WithConfig(config)
resp, err := c.client.Tasks.Inspect(params)
if err != nil {
switch err := err.(type) {
@@ -529,8 +565,9 @@ func (c *ContainerProxy) InspectTask(op trace.Operation, handle string, eid stri
return resp.Payload, nil
}
func (c *ContainerProxy) BindTask(op trace.Operation, handle string, eid string) (string, error) {
defer trace.End(trace.Begin(fmt.Sprintf("handle(%s), eid(%s)", handle, eid)))
func (c *VicContainerProxy) BindTask(op trace.Operation, handle string, eid string) (string, error) {
defer trace.End(trace.Begin(fmt.Sprintf("handle(%s), eid(%s)", handle, eid), op))
opID := op.ID()
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
@@ -540,7 +577,7 @@ func (c *ContainerProxy) BindTask(op trace.Operation, handle string, eid string)
Handle: handle,
ID: eid,
}
bindparams := tasks.NewBindParamsWithContext(op).WithConfig(bindconfig)
bindparams := tasks.NewBindParamsWithContext(op).WithOpID(&opID).WithConfig(bindconfig)
// call Bind with bindparams
resp, err := c.client.Tasks.Bind(bindparams)
@@ -569,28 +606,26 @@ func (c *ContainerProxy) BindTask(op trace.Operation, handle string, eid string)
return respHandle, nil
}
func (c *ContainerProxy) WaitTask(op trace.Operation, cid string, cname string, eid string) error {
func (c *VicContainerProxy) WaitTask(op trace.Operation, handle string, cid string, eid string) error {
defer trace.End(trace.Begin(fmt.Sprintf("handle(%s), cid(%s)", handle, cid), op))
opID := op.ID()
if c.client == nil {
return errors.NillPortlayerClientError("ContainerProxy")
}
handle, err := c.Handle(op, cid, cname)
if err != nil {
return err
}
// wait the Task to start
// wait for the Task to change in state
config := &models.TaskWaitConfig{
Handle: handle,
ID: eid,
}
params := tasks.NewWaitParamsWithContext(op).WithConfig(config)
_, err = c.client.Tasks.Wait(params)
params := tasks.NewWaitParamsWithContext(op).WithOpID(&opID).WithConfig(config)
_, err := c.client.Tasks.Wait(params)
if err != nil {
switch err := err.(type) {
case *tasks.WaitNotFound:
return errors.InternalServerError(fmt.Sprintf("the Container(%s) has been shutdown during execution of the exec operation", cid))
return errors.InternalServerError(fmt.Sprintf("the container(%s) has been shutdown during execution of the exec operation", cid))
case *tasks.WaitPreconditionRequired:
return errors.InternalServerError(fmt.Sprintf("container(%s) must be powered on in order to perform the desired exec operation", cid))
case *tasks.WaitInternalServerError:
@@ -608,8 +643,10 @@ func (c *ContainerProxy) WaitTask(op trace.Operation, cid string, cname string,
//
// returns
// error
func (c *ContainerProxy) Stop(ctx context.Context, vc *viccontainer.VicContainer, name string, seconds *int, unbound bool) error {
defer trace.End(trace.Begin(vc.ContainerID))
func (c *VicContainerProxy) Stop(ctx context.Context, vc *viccontainer.VicContainer, name string, seconds *int, unbound bool) error {
op := trace.FromContext(ctx, "Stop: %s", name)
defer trace.End(trace.Begin(fmt.Sprintf("Name: %s, container id: %s", name, vc.ContainerID), op))
opID := op.ID()
if c.client == nil {
return errors.NillPortlayerClientError("ContainerProxy")
@@ -648,7 +685,11 @@ func (c *ContainerProxy) Stop(ctx context.Context, vc *viccontainer.VicContainer
}
// change the state of the container
changeParams := containers.NewStateChangeParamsWithContext(ctx).WithHandle(handle).WithState("STOPPED")
changeParams := containers.NewStateChangeParamsWithContext(ctx).
WithOpID(&opID).
WithHandle(handle).
WithState("STOPPED")
stateChangeResponse, err := c.client.Containers.StateChange(changeParams)
if err != nil {
switch err := err.(type) {
@@ -682,20 +723,22 @@ func (c *ContainerProxy) Stop(ctx context.Context, vc *viccontainer.VicContainer
}
// UnbindContainerFromNetwork unbinds a container from the networks that it connects to
func (c *ContainerProxy) UnbindContainerFromNetwork(ctx context.Context, vc *viccontainer.VicContainer, handle string) (string, error) {
defer trace.End(trace.Begin(vc.ContainerID))
func (c *VicContainerProxy) UnbindContainerFromNetwork(ctx context.Context, vc *viccontainer.VicContainer, handle string) (string, error) {
op := trace.FromContext(ctx, "UnbindContainerFromNetwork: %s", vc.ContainerID)
defer trace.End(trace.Begin(vc.ContainerID, op))
opID := op.ID()
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
}
unbindParams := scopes.NewUnbindContainerParamsWithContext(ctx).WithHandle(handle)
unbindParams := scopes.NewUnbindContainerParamsWithContext(ctx).WithOpID(&opID).WithHandle(handle)
ub, err := c.client.Scopes.UnbindContainer(unbindParams)
if err != nil {
switch err := err.(type) {
case *scopes.UnbindContainerNotFound:
// ignore error
log.Warnf("Container %s not found by network unbind", vc.ContainerID)
op.Warnf("Container %s not found by network unbind", vc.ContainerID)
case *scopes.UnbindContainerInternalServerError:
return "", errors.InternalServerError(err.Payload.Message)
default:
@@ -707,14 +750,18 @@ func (c *ContainerProxy) UnbindContainerFromNetwork(ctx context.Context, vc *vic
}
// State returns container state
func (c *ContainerProxy) State(ctx context.Context, vc *viccontainer.VicContainer) (*types.ContainerState, error) {
defer trace.End(trace.Begin(""))
func (c *VicContainerProxy) State(ctx context.Context, vc *viccontainer.VicContainer) (*types.ContainerState, error) {
op := trace.FromContext(ctx, "State: %s", vc.ContainerID)
defer trace.End(trace.Begin(vc.ContainerID, op))
opID := op.ID()
if c.client == nil {
return nil, errors.NillPortlayerClientError("ContainerProxy")
}
results, err := c.client.Containers.GetContainerInfo(containers.NewGetContainerInfoParamsWithContext(ctx).WithID(vc.ContainerID))
results, err := c.client.Containers.GetContainerInfo(containers.NewGetContainerInfoParamsWithContext(ctx).
WithOpID(&opID).
WithID(vc.ContainerID))
if err != nil {
switch err := err.(type) {
case *containers.GetContainerInfoNotFound:
@@ -734,14 +781,15 @@ func (c *ContainerProxy) State(ctx context.Context, vc *viccontainer.VicContaine
}
// GetStateFromHandle takes a handle and returns the state of the container based on that handle. Also returns handle that comes back with the response.
func (c *ContainerProxy) GetStateFromHandle(op trace.Operation, handle string) (string, string, error) {
func (c *VicContainerProxy) GetStateFromHandle(op trace.Operation, handle string) (string, string, error) {
defer trace.End(trace.Begin(fmt.Sprintf("handle(%s)", handle), op))
opID := op.ID()
if c.client == nil {
return "", "", errors.NillPortlayerClientError("ContainerProxy")
}
params := containers.NewGetStateParams().WithHandle(handle)
params := containers.NewGetStateParams().WithOpID(&opID).WithHandle(handle)
resp, err := c.client.Containers.GetState(params)
if err != nil {
switch err := err.(type) {
@@ -756,14 +804,19 @@ func (c *ContainerProxy) GetStateFromHandle(op trace.Operation, handle string) (
}
// ExitCode returns container exitCode
func (c *ContainerProxy) ExitCode(ctx context.Context, vc *viccontainer.VicContainer) (string, error) {
defer trace.End(trace.Begin(""))
func (c *VicContainerProxy) ExitCode(ctx context.Context, vc *viccontainer.VicContainer) (string, error) {
op := trace.FromContext(ctx, "ExitCode: %s", vc.ContainerID)
defer trace.End(trace.Begin(vc.ContainerID, op))
opID := op.ID()
if c.client == nil {
return "", errors.NillPortlayerClientError("ContainerProxy")
}
results, err := c.client.Containers.GetContainerInfo(containers.NewGetContainerInfoParamsWithContext(ctx).WithID(vc.ContainerID))
results, err := c.client.Containers.GetContainerInfo(containers.NewGetContainerInfoParamsWithContext(ctx).
WithOpID(&opID).
WithID(vc.ContainerID))
if err != nil {
switch err := err.(type) {
case *containers.GetContainerInfoNotFound:
@@ -783,8 +836,11 @@ func (c *ContainerProxy) ExitCode(ctx context.Context, vc *viccontainer.VicConta
return strconv.Itoa(dockerState.ExitCode), nil
}
func (c *ContainerProxy) Wait(ctx context.Context, vc *viccontainer.VicContainer, timeout time.Duration) (
func (c *VicContainerProxy) Wait(ctx context.Context, vc *viccontainer.VicContainer, timeout time.Duration) (
*types.ContainerState, error) {
op := trace.FromContext(ctx, "Wait: %s", vc.ContainerID)
defer trace.End(trace.Begin(vc.ContainerID, op))
opID := op.ID()
defer trace.End(trace.Begin(vc.ContainerID))
@@ -798,8 +854,10 @@ func (c *ContainerProxy) Wait(ctx context.Context, vc *viccontainer.VicContainer
}
params := containers.NewContainerWaitParamsWithContext(ctx).
WithOpID(&opID).
WithTimeout(int64(timeout.Seconds())).
WithID(vc.ContainerID)
results, err := c.client.Containers.ContainerWait(params)
if err != nil {
switch err := err.(type) {
@@ -826,8 +884,10 @@ func (c *ContainerProxy) Wait(ctx context.Context, vc *viccontainer.VicContainer
return dockerState, nil
}
func (c *ContainerProxy) Signal(ctx context.Context, vc *viccontainer.VicContainer, sig uint64) error {
defer trace.End(trace.Begin(vc.ContainerID))
func (c *VicContainerProxy) Signal(ctx context.Context, vc *viccontainer.VicContainer, sig uint64) error {
op := trace.FromContext(ctx, "Signal: %s", vc.ContainerID)
defer trace.End(trace.Begin(vc.ContainerID, op))
opID := op.ID()
if vc == nil {
return errors.InternalServerError("Signal bad arguments")
@@ -845,7 +905,11 @@ func (c *ContainerProxy) Signal(ctx context.Context, vc *viccontainer.VicContain
if sig == 0 {
sig = uint64(syscall.SIGKILL)
}
params := containers.NewContainerSignalParamsWithContext(ctx).WithID(vc.ContainerID).WithSignal(int64(sig))
params := containers.NewContainerSignalParamsWithContext(ctx).
WithOpID(&opID).
WithID(vc.ContainerID).
WithSignal(int64(sig))
if _, err := c.client.Containers.ContainerSignal(params); err != nil {
switch err := err.(type) {
case *containers.ContainerSignalNotFound:
@@ -867,7 +931,11 @@ func (c *ContainerProxy) Signal(ctx context.Context, vc *viccontainer.VicContain
return nil
}
func (c *ContainerProxy) Resize(ctx context.Context, id string, height, width int32) error {
func (c *VicContainerProxy) Resize(ctx context.Context, id string, height, width int32) error {
op := trace.FromContext(ctx, "Resize: %s", id)
defer trace.End(trace.Begin(id, op))
opID := op.ID()
defer trace.End(trace.Begin(id))
if c.client == nil {
@@ -875,6 +943,7 @@ func (c *ContainerProxy) Resize(ctx context.Context, id string, height, width in
}
plResizeParam := interaction.NewContainerResizeParamsWithContext(ctx).
WithOpID(&opID).
WithID(id).
WithHeight(height).
WithWidth(width)
@@ -894,8 +963,10 @@ func (c *ContainerProxy) Resize(ctx context.Context, id string, height, width in
// Rename calls the portlayer's RenameContainerHandler to update the container name in the handle,
// and then commit the new name to vSphere
func (c *ContainerProxy) Rename(ctx context.Context, vc *viccontainer.VicContainer, newName string) error {
defer trace.End(trace.Begin(vc.ContainerID))
func (c *VicContainerProxy) Rename(ctx context.Context, vc *viccontainer.VicContainer, newName string) error {
op := trace.FromContext(ctx, "Rename: %s", vc.ContainerID)
defer trace.End(trace.Begin(vc.ContainerID, op))
opID := op.ID()
//retrieve client to portlayer
handle, err := c.Handle(context.TODO(), vc.ContainerID, vc.Name)
@@ -908,7 +979,11 @@ func (c *ContainerProxy) Rename(ctx context.Context, vc *viccontainer.VicContain
}
// Call the rename functionality in the portlayer.
renameParams := containers.NewContainerRenameParamsWithContext(ctx).WithName(newName).WithHandle(handle)
renameParams := containers.NewContainerRenameParamsWithContext(ctx).
WithOpID(&opID).
WithName(newName).
WithHandle(handle)
result, err := c.client.Containers.ContainerRename(renameParams)
if err != nil {
switch err := err.(type) {
@@ -942,15 +1017,19 @@ func (c *ContainerProxy) Rename(ctx context.Context, vc *viccontainer.VicContain
// Remove calls the portlayer's ContainerRemove handler to remove the container and its
// anonymous volumes if the remove flag is set.
func (c *ContainerProxy) Remove(ctx context.Context, vc *viccontainer.VicContainer, config *types.ContainerRmConfig) error {
defer trace.End(trace.Begin(vc.ContainerID))
func (c *VicContainerProxy) Remove(ctx context.Context, vc *viccontainer.VicContainer, config *types.ContainerRmConfig) error {
op := trace.FromContext(ctx, "Remove: %s", vc.ContainerID)
defer trace.End(trace.Begin(vc.ContainerID, op))
opID := op.ID()
if c.client == nil {
return errors.NillPortlayerClientError("ContainerProxy")
}
id := vc.ContainerID
_, err := c.client.Containers.ContainerRemove(containers.NewContainerRemoveParamsWithContext(ctx).WithID(id))
_, err := c.client.Containers.ContainerRemove(containers.NewContainerRemoveParamsWithContext(ctx).
WithOpID(&opID).
WithID(id))
if err != nil {
switch err := err.(type) {
case *containers.ContainerRemoveNotFound:

View File

@@ -39,20 +39,22 @@ import (
"github.com/vmware/vic/pkg/trace"
)
type VicStorageProxy interface {
type StorageProxy interface {
Create(ctx context.Context, name, driverName string, volumeData, labels map[string]string) (*types.Volume, error)
VolumeExist(ctx context.Context, name string) (bool, error)
VolumeList(ctx context.Context, filter string) ([]*models.VolumeResponse, error)
VolumeInfo(ctx context.Context, name string) (*models.VolumeResponse, error)
Remove(ctx context.Context, name string) error
VolumeJoin(ctx context.Context, handle, volName, mountPath string, flags map[string]string) (string, error)
AddVolumesToContainer(ctx context.Context, handle string, config types.ContainerCreateConfig) (string, error)
}
type StorageProxy struct {
type VicStorageProxy struct {
client *client.PortLayer
}
type volumeFields struct {
type VolumeFields struct {
ID string
Dest string
Flags string
@@ -96,26 +98,27 @@ var SupportedVolDrivers = map[string]struct{}{
//Validation pattern for Volume Names
var volumeNameRegex = regexp.MustCompile("^[a-zA-Z0-9][a-zA-Z0-9_.-]*$")
func NewStorageProxy(client *client.PortLayer) VicStorageProxy {
func NewStorageProxy(client *client.PortLayer) *VicStorageProxy {
if client == nil {
return nil
}
return &StorageProxy{client: client}
return &VicStorageProxy{client: client}
}
func (s *StorageProxy) Create(ctx context.Context, name, driverName string, volumeData, labels map[string]string) (*types.Volume, error) {
defer trace.End(trace.Begin(""))
func (s *VicStorageProxy) Create(ctx context.Context, name, driverName string, volumeData, labels map[string]string) (*types.Volume, error) {
op := trace.FromContext(ctx, "VolumeCreate: %s", name)
defer trace.End(trace.Begin(name, op))
if s.client == nil {
return nil, errors.NillPortlayerClientError("StorageProxy")
}
result, err := s.volumeCreate(ctx, name, driverName, volumeData, labels)
result, err := s.volumeCreate(op, name, driverName, volumeData, labels)
if err != nil {
switch err := err.(type) {
case *storage.CreateVolumeConflict:
return result, errors.VolumeInternalServerError(fmt.Errorf("A volume named %s already exists. Choose a different volume name.", name))
return result, errors.VolumeExistError{Volume: name}
case *storage.CreateVolumeNotFound:
return result, errors.VolumeInternalServerError(fmt.Errorf("No volume store named (%s) exists", volumeStore(volumeData)))
case *storage.CreateVolumeInternalServerError:
@@ -132,8 +135,9 @@ func (s *StorageProxy) Create(ctx context.Context, name, driverName string, volu
}
// volumeCreate issues a CreateVolume request to the portlayer
func (s *StorageProxy) volumeCreate(ctx context.Context, name, driverName string, volumeData, labels map[string]string) (*types.Volume, error) {
defer trace.End(trace.Begin(""))
func (s *VicStorageProxy) volumeCreate(op trace.Operation, name, driverName string, volumeData, labels map[string]string) (*types.Volume, error) {
defer trace.End(trace.Begin(name, op))
opID := op.ID()
result := &types.Volume{}
if s.client == nil {
@@ -150,9 +154,9 @@ func (s *StorageProxy) volumeCreate(ctx context.Context, name, driverName string
if varErr != nil {
return result, varErr
}
log.Infof("Finalized model for volume create request to portlayer: %#v", req)
op.Infof("Finalized model for volume create request to portlayer: %#v", req)
res, err := s.client.Storage.CreateVolume(storage.NewCreateVolumeParamsWithContext(ctx).WithVolumeRequest(req))
res, err := s.client.Storage.CreateVolume(storage.NewCreateVolumeParamsWithContext(op).WithOpID(&opID).WithVolumeRequest(req))
if err != nil {
return result, err
}
@@ -160,14 +164,31 @@ func (s *StorageProxy) volumeCreate(ctx context.Context, name, driverName string
return NewVolumeModel(res.Payload, labels), nil
}
func (s *StorageProxy) VolumeList(ctx context.Context, filter string) ([]*models.VolumeResponse, error) {
defer trace.End(trace.Begin(""))
func (s *VicStorageProxy) VolumeExist(ctx context.Context, name string) (bool, error) {
defer trace.End(trace.Begin(name))
vols, err := s.VolumeList(ctx, "")
if err == nil {
for _, v := range vols {
if name == v.Name {
return true, nil
}
}
}
return false, err
}
func (s *VicStorageProxy) VolumeList(ctx context.Context, filter string) ([]*models.VolumeResponse, error) {
op := trace.FromContext(ctx, "VolumeList")
defer trace.End(trace.Begin("", op))
opID := op.ID()
if s.client == nil {
return nil, errors.NillPortlayerClientError("StorageProxy")
}
res, err := s.client.Storage.ListVolumes(storage.NewListVolumesParamsWithContext(ctx).WithFilterString(&filter))
res, err := s.client.Storage.ListVolumes(storage.NewListVolumesParamsWithContext(op).WithOpID(&opID).WithFilterString(&filter))
if err != nil {
switch err := err.(type) {
case *storage.ListVolumesInternalServerError:
@@ -182,8 +203,10 @@ func (s *StorageProxy) VolumeList(ctx context.Context, filter string) ([]*models
return res.Payload, nil
}
func (s *StorageProxy) VolumeInfo(ctx context.Context, name string) (*models.VolumeResponse, error) {
defer trace.End(trace.Begin(name))
func (s *VicStorageProxy) VolumeInfo(ctx context.Context, name string) (*models.VolumeResponse, error) {
op := trace.FromContext(ctx, "VolumeInfo: %s", name)
defer trace.End(trace.Begin(name, op))
opID := op.ID()
if name == "" {
return nil, nil
@@ -193,7 +216,7 @@ func (s *StorageProxy) VolumeInfo(ctx context.Context, name string) (*models.Vol
return nil, errors.NillPortlayerClientError("StorageProxy")
}
param := storage.NewGetVolumeParamsWithContext(ctx).WithName(name)
param := storage.NewGetVolumeParamsWithContext(op).WithOpID(&opID).WithName(name)
res, err := s.client.Storage.GetVolume(param)
if err != nil {
switch err := err.(type) {
@@ -207,14 +230,16 @@ func (s *StorageProxy) VolumeInfo(ctx context.Context, name string) (*models.Vol
return res.Payload, nil
}
func (s *StorageProxy) Remove(ctx context.Context, name string) error {
defer trace.End(trace.Begin(name))
func (s *VicStorageProxy) Remove(ctx context.Context, name string) error {
op := trace.FromContext(ctx, "VolumeRemove: %s", name)
defer trace.End(trace.Begin(name, op))
opID := op.ID()
if s.client == nil {
return errors.NillPortlayerClientError("StorageProxy")
}
_, err := s.client.Storage.RemoveVolume(storage.NewRemoveVolumeParamsWithContext(ctx).WithName(name))
_, err := s.client.Storage.RemoveVolume(storage.NewRemoveVolumeParamsWithContext(op).WithOpID(&opID).WithName(name))
if err != nil {
switch err := err.(type) {
case *storage.RemoveVolumeNotFound:
@@ -236,16 +261,17 @@ func (s *StorageProxy) Remove(ctx context.Context, name string) error {
//
// returns:
// modified handle
func (s *StorageProxy) AddVolumesToContainer(ctx context.Context, handle string, config types.ContainerCreateConfig) (string, error) {
defer trace.End(trace.Begin(handle))
func (s *VicStorageProxy) AddVolumesToContainer(ctx context.Context, handle string, config types.ContainerCreateConfig) (string, error) {
op := trace.FromContext(ctx, "AddVolumesToContainer: %s", handle)
defer trace.End(trace.Begin(handle, op))
if s.client == nil {
return "", errors.NillPortlayerClientError("StorageProxy")
}
// Volume Attachment Section
log.Debugf("ContainerProxy.AddVolumesToContainer - VolumeSection")
log.Debugf("Raw volume arguments: binds: %#v, volumes: %#v", config.HostConfig.Binds, config.Config.Volumes)
op.Debugf("ContainerProxy.AddVolumesToContainer - VolumeSection")
op.Debugf("Raw volume arguments: binds: %#v, volumes: %#v", config.HostConfig.Binds, config.Config.Volumes)
// Collect all volume mappings. In a docker create/run, they
// can be anonymous (-v /dir) or specific (-v vol-name:/dir).
@@ -260,7 +286,7 @@ func (s *StorageProxy) AddVolumesToContainer(ctx context.Context, handle string,
if err != nil {
return handle, errors.BadRequestError(err.Error())
}
log.Infof("Finalized volume list: %#v", volList)
op.Infof("Finalized volume list: %#v", volList)
if len(config.Config.Volumes) > 0 {
// override anonymous volume list with generated volume id
@@ -269,7 +295,7 @@ func (s *StorageProxy) AddVolumesToContainer(ctx context.Context, handle string,
delete(config.Config.Volumes, vol.Dest)
mount := getMountString(vol.ID, vol.Dest, vol.Flags)
config.Config.Volumes[mount] = struct{}{}
log.Debugf("Replace anonymous volume config %s with %s", vol.Dest, mount)
op.Debugf("Replace anonymous volume config %s with %s", vol.Dest, mount)
}
}
}
@@ -285,59 +311,75 @@ func (s *StorageProxy) AddVolumesToContainer(ctx context.Context, handle string,
// NOTE: calling volumeCreate regardless of whether the volume is already
// present can be avoided by adding an extra optional param to VolumeJoin,
// which would then call volumeCreate if the volume does not exist.
_, err := s.volumeCreate(ctx, fields.ID, "vsphere", volumeData, nil)
if err != nil {
switch err := err.(type) {
case *storage.CreateVolumeConflict:
// Implicitly ignore the error where a volume with the same name
// already exists. We can just join the said volume to the container.
log.Infof("a volume with the name %s already exists", fields.ID)
case *storage.CreateVolumeNotFound:
return handle, errors.VolumeCreateNotFoundError(volumeStore(volumeData))
default:
return handle, errors.InternalServerError(err.Error())
}
} else {
log.Infof("volumeCreate succeeded. Volume mount section ID: %s", fields.ID)
_, err := s.Create(op, fields.ID, "vsphere", volumeData, nil)
if err != nil && !errors.IsVolumeExistError(err) {
return handle, err
}
flags := make(map[string]string)
//NOTE: for now we are passing the flags directly through. This is NOT SAFE and only a stop gap.
flags[constants.Mode] = fields.Flags
joinParams := storage.NewVolumeJoinParamsWithContext(ctx).WithJoinArgs(&models.VolumeJoinConfig{
Flags: flags,
Handle: handle,
MountPath: fields.Dest,
}).WithName(fields.ID)
res, err := s.client.Storage.VolumeJoin(joinParams)
h, err := s.VolumeJoin(op, handle, fields.ID, fields.Dest, flags)
if err != nil {
switch err := err.(type) {
case *storage.VolumeJoinInternalServerError:
return handle, errors.InternalServerError(err.Payload.Message)
case *storage.VolumeJoinDefault:
return handle, errors.InternalServerError(err.Payload.Message)
case *storage.VolumeJoinNotFound:
return handle, errors.VolumeJoinNotFoundError(err.Payload.Message)
default:
return handle, errors.InternalServerError(err.Error())
}
return handle, err
}
handle = res.Payload
handle = h
}
return handle, nil
}
// VolumeJoin declares a volume mount for a container. This should be called on container create.
func (s *VicStorageProxy) VolumeJoin(ctx context.Context, handle, volName, mountPath string, flags map[string]string) (string, error) {
op := trace.FromContext(ctx, "VolumeJoin: %s", handle)
defer trace.End(trace.Begin(handle, op))
opID := op.ID()
if s.client == nil {
return "", errors.NillPortlayerClientError("StorageProxy")
}
joinParams := storage.NewVolumeJoinParamsWithContext(op).
WithOpID(&opID).
WithJoinArgs(&models.VolumeJoinConfig{
Flags: flags,
Handle: handle,
MountPath: mountPath,
}).WithName(volName)
res, err := s.client.Storage.VolumeJoin(joinParams)
if err != nil {
switch err := err.(type) {
case *storage.VolumeJoinInternalServerError:
return handle, errors.InternalServerError(err.Payload.Message)
case *storage.VolumeJoinDefault:
return handle, errors.InternalServerError(err.Payload.Message)
case *storage.VolumeJoinNotFound:
return handle, errors.VolumeJoinNotFoundError(err.Payload.Message)
default:
return handle, errors.InternalServerError(err.Error())
}
}
handle = res.Payload
return handle, nil
}
// allContainers obtains all containers from the portlayer, akin to `docker ps -a`.
func (s *StorageProxy) allContainers(ctx context.Context) ([]*models.ContainerInfo, error) {
func (s *VicStorageProxy) allContainers(op trace.Operation) ([]*models.ContainerInfo, error) {
defer trace.End(trace.Begin("", op))
opID := op.ID()
if s.client == nil {
return nil, errors.NillPortlayerClientError("StorageProxy")
}
all := true
cons, err := s.client.Containers.GetContainerList(containers.NewGetContainerListParamsWithContext(ctx).WithAll(&all))
cons, err := s.client.Containers.GetContainerList(containers.NewGetContainerListParamsWithContext(op).
WithOpID(&opID).
WithAll(&all))
if err != nil {
return nil, err
}
@@ -347,8 +389,9 @@ func (s *StorageProxy) allContainers(ctx context.Context) ([]*models.ContainerIn
// fetchJoinedVolumes obtains all containers from the portlayer and returns a map with all
// volumes that are joined to at least one container.
func (s *StorageProxy) fetchJoinedVolumes(ctx context.Context) (map[string]struct{}, error) {
conts, err := s.allContainers(ctx)
func (s *VicStorageProxy) fetchJoinedVolumes(op trace.Operation) (map[string]struct{}, error) {
defer trace.End(trace.Begin("", op))
conts, err := s.allContainers(op)
if err != nil {
return nil, errors.VolumeInternalServerError(err)
}
@@ -410,6 +453,10 @@ func createVolumeMetadata(req *models.VolumeRequest, driverargs, labels map[stri
// to at least one other container, and calls the portlayer to remove this container's
// anonymous volumes if they are dangling. Errors, if any, are only logged.
func RemoveAnonContainerVols(ctx context.Context, pl *client.PortLayer, cID string, vc *viccontainer.VicContainer) {
op := trace.FromContext(ctx, "RemoveAnonContainerVols: %s", cID)
defer trace.End(trace.Begin(cID, op))
opID := op.ID()
// NOTE: these strings come in the form of <volume id>:<destination>:<volume options>
volumes := vc.Config.Volumes
// NOTE: these strings come in the form of <volume id>:<destination path>
@@ -420,17 +467,17 @@ func RemoveAnonContainerVols(ctx context.Context, pl *client.PortLayer, cID stri
for _, entry := range namedVolumes {
fields := strings.SplitN(entry, ":", 2)
if len(fields) != 2 {
log.Errorf("Invalid entry in the HostConfig.Binds metadata section for container %s: %s", cID, entry)
op.Errorf("Invalid entry in the HostConfig.Binds metadata section for container %s: %s", cID, entry)
continue
}
destPath := fields[1]
namedMaskList[destPath] = struct{}{}
}
proxy := StorageProxy{client: pl}
joinedVols, err := proxy.fetchJoinedVolumes(ctx)
proxy := VicStorageProxy{client: pl}
joinedVols, err := proxy.fetchJoinedVolumes(op)
if err != nil {
log.Errorf("Unable to obtain joined volumes from portlayer, skipping removal of anonymous volumes for %s: %s", cID, err.Error())
op.Errorf("Unable to obtain joined volumes from portlayer, skipping removal of anonymous volumes for %s: %s", cID, err.Error())
return
}
@@ -440,7 +487,7 @@ func RemoveAnonContainerVols(ctx context.Context, pl *client.PortLayer, cID stri
// NOTE(mavery): this check will start to fail when we fix our metadata correctness issues
if len(volFields) != 3 {
log.Debugf("Invalid entry in the volumes metadata section for container %s: %s", cID, vol)
op.Debugf("Invalid entry in the volumes metadata section for container %s: %s", cID, vol)
continue
}
volName := volFields[0]
@@ -449,27 +496,27 @@ func RemoveAnonContainerVols(ctx context.Context, pl *client.PortLayer, cID stri
_, isNamed := namedMaskList[volPath]
_, joined := joinedVols[volName]
if !joined && !isNamed {
_, err := pl.Storage.RemoveVolume(storage.NewRemoveVolumeParamsWithContext(ctx).WithName(volName))
_, err := pl.Storage.RemoveVolume(storage.NewRemoveVolumeParamsWithContext(op).WithOpID(&opID).WithName(volName))
if err != nil {
log.Debugf("Unable to remove anonymous volume %s in container %s: %s", volName, cID, err.Error())
op.Debugf("Unable to remove anonymous volume %s in container %s: %s", volName, cID, err.Error())
continue
}
log.Debugf("Successfully removed anonymous volume %s during remove operation against container(%s)", volName, cID)
op.Debugf("Successfully removed anonymous volume %s during remove operation against container(%s)", volName, cID)
}
}
}
// processVolumeParam is used to turn any call from docker create -v <stuff> into a volumeFields object.
// processVolumeParam is used to turn any call from docker create -v <stuff> into a VolumeFields object.
// The -v has 3 forms. -v <anonymous mount path>, -v <Volume Name>:<Destination Mount Path> and
// -v <Volume Name>:<Destination Mount Path>:<mount flags>
func processVolumeParam(volString string) (volumeFields, error) {
func processVolumeParam(volString string) (VolumeFields, error) {
volumeStrings := strings.Split(volString, ":")
fields := volumeFields{}
fields := VolumeFields{}
// Error out if the intended volume is a directory on the client filesystem.
numVolParams := len(volumeStrings)
if numVolParams > 1 && strings.HasPrefix(volumeStrings[0], "/") {
return volumeFields{}, errors.InvalidVolumeError{}
return VolumeFields{}, errors.InvalidVolumeError{}
}
// This switch determines which type of -v was invoked.
@@ -492,7 +539,7 @@ func processVolumeParam(volString string) (volumeFields, error) {
fields.Flags = volumeStrings[2]
default:
// NOTE: the docker cli should cover this case. This is here for posterity.
return volumeFields{}, errors.InvalidBindError{Volume: volString}
return VolumeFields{}, errors.InvalidBindError{Volume: volString}
}
return fields, nil
}
@@ -500,8 +547,8 @@ func processVolumeParam(volString string) (volumeFields, error) {
// processVolumeFields parses fields for volume mappings specified in a create/run -v.
// It returns a map of unique mountable volumes. This means that it removes dupes favoring
// specified volumes over anonymous volumes.
func processVolumeFields(volumes []string) (map[string]volumeFields, error) {
volumeFields := make(map[string]volumeFields)
func processVolumeFields(volumes []string) (map[string]VolumeFields, error) {
vf := make(map[string]VolumeFields)
for _, v := range volumes {
fields, err := processVolumeParam(v)
@@ -509,12 +556,12 @@ func processVolumeFields(volumes []string) (map[string]volumeFields, error) {
if err != nil {
return nil, err
}
volumeFields[fields.Dest] = fields
vf[fields.Dest] = fields
}
return volumeFields, nil
return vf, nil
}
func finalizeVolumeList(specifiedVolumes, anonymousVolumes []string) ([]volumeFields, error) {
func finalizeVolumeList(specifiedVolumes, anonymousVolumes []string) ([]VolumeFields, error) {
log.Infof("Specified Volumes : %#v", specifiedVolumes)
processedVolumes, err := processVolumeFields(specifiedVolumes)
if err != nil {
@@ -532,7 +579,7 @@ func finalizeVolumeList(specifiedVolumes, anonymousVolumes []string) ([]volumeFi
processedAnonVolumes[k] = v
}
finalizedVolumes := make([]volumeFields, 0, len(processedAnonVolumes))
finalizedVolumes := make([]VolumeFields, 0, len(processedAnonVolumes))
for _, v := range processedAnonVolumes {
finalizedVolumes = append(finalizedVolumes, v)
}

View File

@@ -22,7 +22,6 @@ import (
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/go-openapi/strfmt"
"github.com/docker/docker/api/types/backend"
@@ -33,16 +32,18 @@ import (
"github.com/vmware/vic/lib/apiservers/portlayer/client"
"github.com/vmware/vic/lib/apiservers/portlayer/client/containers"
"github.com/vmware/vic/lib/apiservers/portlayer/client/interaction"
"github.com/vmware/vic/lib/apiservers/portlayer/client/events"
"github.com/vmware/vic/pkg/trace"
)
type VicStreamProxy interface {
AttachStreams(ctx context.Context, ac *AttachConfig, stdin io.ReadCloser, stdout, stderr io.Writer) error
type StreamProxy interface {
AttachStreams(ctx context.Context, ac *AttachConfig, stdin io.ReadCloser, stdout, stderr io.Writer, autoclose bool) error
StreamContainerLogs(ctx context.Context, name string, out io.Writer, started chan struct{}, showTimestamps bool, followLogs bool, since int64, tailLines int64) error
StreamContainerStats(ctx context.Context, config *convert.ContainerStatsConfig) error
StreamEvents(ctx context.Context, out io.Writer) error
}
type StreamProxy struct {
type VicStreamProxy struct {
client *client.PortLayer
}
@@ -70,14 +71,18 @@ type AttachConfig struct {
CloseStdin bool
}
func NewStreamProxy(client *client.PortLayer) VicStreamProxy {
return &StreamProxy{client: client}
func NewStreamProxy(client *client.PortLayer) *VicStreamProxy {
return &VicStreamProxy{client: client}
}
// AttachStreams takes the the hijacked connections from the calling client and attaches
// them to the 3 streams from the portlayer's rest server.
// stdin, stdout, stderr are the hijacked connection
func (s *StreamProxy) AttachStreams(ctx context.Context, ac *AttachConfig, stdin io.ReadCloser, stdout, stderr io.Writer) error {
// autoclose controls whether the underlying client transport will be closed when stdout/stderr
func (s *VicStreamProxy) AttachStreams(ctx context.Context, ac *AttachConfig, stdin io.ReadCloser, stdout, stderr io.Writer, autoclose bool) error {
op := trace.FromContext(ctx, "")
defer trace.End(trace.Begin("", op))
// Cancel will close the child connections.
var wg, outWg sync.WaitGroup
@@ -96,10 +101,11 @@ func (s *StreamProxy) AttachStreams(ctx context.Context, ac *AttachConfig, stdin
}
}
ctx, cancel := context.WithCancel(ctx)
ctx, cancel := context.WithCancel(op)
defer cancel()
if ac.UseStdin {
if ac.UseStdin && autoclose {
// if we're not autoclosing then we don't want to block waiting for copyStdin to exit
wg.Add(1)
}
@@ -125,22 +131,26 @@ func (s *StreamProxy) AttachStreams(ctx context.Context, ac *AttachConfig, stdin
if ac.UseStdin {
go func() {
defer wg.Done()
err := copyStdIn(ctx, s.client, ac, stdin, keys)
if autoclose {
defer wg.Done()
}
err := copyStdIn(ctx, s.client, ac, stdin, keys, autoclose)
if err != nil {
log.Errorf("container attach: stdin (%s): %s", ac.ID, err)
op.Errorf("container attach: stdin (%s): %s", ac.ID, err)
} else {
log.Infof("container attach: stdin (%s) done", ac.ID)
op.Infof("container attach: stdin (%s) done", ac.ID)
}
// Check for EOF or canceled context. We can only detect EOF by checking the error string returned by swagger :/
// We check this before calling cancel so that we will be sure to return detach errors before stdout/err exits,
// even in the !autoclose case.
if EOForCanceled(err) {
errChan <- err
}
if !ac.CloseStdin || ac.UseTty {
cancel()
}
// Check for EOF or canceled context. We can only detect EOF by checking the error string returned by swagger :/
if EOForCanceled(err) {
errChan <- err
}
}()
}
@@ -151,9 +161,9 @@ func (s *StreamProxy) AttachStreams(ctx context.Context, ac *AttachConfig, stdin
err := copyStdOut(ctx, s.client, ac, stdout, attachAttemptTimeout)
if err != nil {
log.Errorf("container attach: stdout (%s): %s", ac.ID, err)
op.Errorf("container attach: stdout (%s): %s", ac.ID, err)
} else {
log.Infof("container attach: stdout (%s) done", ac.ID)
op.Infof("container attach: stdout (%s) done", ac.ID)
}
// Check for EOF or canceled context. We can only detect EOF by checking the error string returned by swagger :/
@@ -170,9 +180,9 @@ func (s *StreamProxy) AttachStreams(ctx context.Context, ac *AttachConfig, stdin
err := copyStdErr(ctx, s.client, ac, stderr)
if err != nil {
log.Errorf("container attach: stderr (%s): %s", ac.ID, err)
op.Errorf("container attach: stderr (%s): %s", ac.ID, err)
} else {
log.Infof("container attach: stderr (%s) done", ac.ID)
op.Infof("container attach: stderr (%s) done", ac.ID)
}
// Check for EOF or canceled context. We can only detect EOF by checking the error string returned by swagger :/
@@ -188,12 +198,12 @@ func (s *StreamProxy) AttachStreams(ctx context.Context, ac *AttachConfig, stdin
// close the channel so that we don't leak (if there is an error)/or get blocked (if there are no errors)
close(errChan)
log.Infof("cleaned up connections to %s. Checking errors", ac.ID)
op.Infof("cleaned up connections to %s", ac.ID)
for err := range errChan {
if err != nil {
// check if we got DetachError
if _, ok := err.(errors.DetachError); ok {
log.Infof("Detached from container detected")
op.Infof("Detached from container detected")
return err
}
@@ -202,20 +212,21 @@ func (s *StreamProxy) AttachStreams(ctx context.Context, ac *AttachConfig, stdin
// Go-swagger returns untyped errors to us if the error is not one that we define
// in the swagger spec. Even EOF. Therefore, we must scan the error string (if there
// is an error string in the untyped error) for the term EOF.
log.Errorf("container attach error: %s", err)
op.Errorf("container attach error: %s", err)
return err
}
}
log.Infof("No error found. Returning nil...")
return nil
}
// StreamContainerLogs reads the log stream from the portlayer rest server and writes
// it directly to the io.Writer that is passed in.
func (s *StreamProxy) StreamContainerLogs(ctx context.Context, name string, out io.Writer, started chan struct{}, showTimestamps bool, followLogs bool, since int64, tailLines int64) error {
defer trace.End(trace.Begin(""))
func (s *VicStreamProxy) StreamContainerLogs(ctx context.Context, name string, out io.Writer, started chan struct{}, showTimestamps bool, followLogs bool, since int64, tailLines int64) error {
op := trace.FromContext(ctx, "")
defer trace.End(trace.Begin("", op))
opID := op.ID()
if s.client == nil {
return errors.NillPortlayerClientError("StreamProxy")
@@ -223,12 +234,13 @@ func (s *StreamProxy) StreamContainerLogs(ctx context.Context, name string, out
close(started)
params := containers.NewGetContainerLogsParamsWithContext(ctx).
params := containers.NewGetContainerLogsParamsWithContext(op).
WithID(name).
WithFollow(&followLogs).
WithTimestamp(&showTimestamps).
WithSince(&since).
WithTaillines(&tailLines)
WithTaillines(&tailLines).
WithOpID(&opID)
_, err := s.client.Containers.GetContainerLogs(params, out)
if err != nil {
switch err := err.(type) {
@@ -253,8 +265,10 @@ func (s *StreamProxy) StreamContainerLogs(ctx context.Context, name string, out
// StreamContainerStats will provide a stream of container stats written to the provided
// io.Writer. Prior to writing to the provided io.Writer there will be a transformation
// from the portLayer representation of stats to the docker format
func (s *StreamProxy) StreamContainerStats(ctx context.Context, config *convert.ContainerStatsConfig) error {
defer trace.End(trace.Begin(config.ContainerID))
func (s *VicStreamProxy) StreamContainerStats(ctx context.Context, config *convert.ContainerStatsConfig) error {
op := trace.FromContext(ctx, "")
defer trace.End(trace.Begin(config.ContainerID, op))
opID := op.ID()
if s.client == nil {
return errors.NillPortlayerClientError("StreamProxy")
@@ -264,7 +278,7 @@ func (s *StreamProxy) StreamContainerStats(ctx context.Context, config *convert.
ctx, cancel := context.WithCancel(ctx)
defer cancel()
params := containers.NewGetContainerStatsParamsWithContext(ctx)
params := containers.NewGetContainerStatsParamsWithContext(op).WithOpID(&opID)
params.ID = config.ContainerID
params.Stream = config.Stream
@@ -303,11 +317,48 @@ func (s *StreamProxy) StreamContainerStats(ctx context.Context, config *convert.
return nil
}
// StreamEvents() handles all swagger interaction to the Portlayer's event manager
//
// Input:
// context and a io.Writer
func (s *VicStreamProxy) StreamEvents(ctx context.Context, out io.Writer) error {
op := trace.FromContext(ctx, "")
defer trace.End(trace.Begin("", op))
opID := op.ID()
if s.client == nil {
return errors.NillPortlayerClientError("StreamProxy")
}
params := events.NewGetEventsParamsWithContext(ctx).WithOpID(&opID)
if _, err := s.client.Events.GetEvents(params, out); err != nil {
switch err := err.(type) {
case *events.GetEventsInternalServerError:
return errors.InternalServerError("Server error from the events port layer")
default:
//Check for EOF. Since the connection, transport, and data handling are
//encapsulated inside of Swagger, we can only detect EOF by checking the
//error string
if strings.Contains(err.Error(), SwaggerSubstringEOF) {
return nil
}
return errors.InternalServerError(fmt.Sprintf("Unknown error from the interaction port layer: %s", err))
}
}
return nil
}
//------------------------------------
// ContainerAttach() Utility Functions
//------------------------------------
func copyStdIn(ctx context.Context, pl *client.PortLayer, ac *AttachConfig, stdin io.ReadCloser, keys []byte) error {
func copyStdIn(ctx context.Context, pl *client.PortLayer, ac *AttachConfig, stdin io.ReadCloser, keys []byte, autoclose bool) error {
op := trace.FromContext(ctx, "")
defer trace.End(trace.Begin("", op))
opID := op.ID()
// Pipe for stdin so we can interject and watch the input streams for detach keys.
stdinReader, stdinWriter := io.Pipe()
defer stdinReader.Close()
@@ -315,26 +366,28 @@ func copyStdIn(ctx context.Context, pl *client.PortLayer, ac *AttachConfig, stdi
var detach bool
done := make(chan struct{})
go func() {
// make sure we get out of io.Copy if context is canceled
select {
case <-ctx.Done():
// This will cause the transport to the API client to be shut down, so all output
// streams will get closed as well.
// See the closer in container_routes.go:postContainersAttach
if autoclose {
go func() {
// make sure we get out of io.Copy if context is canceled
select {
case <-ctx.Done():
// This will cause the transport to the API client to be shut down, so all output
// streams will get closed as well.
// See the closer in container_routes.go:postContainersAttach
// We're closing this here to disrupt the io.Copy below
// TODO: seems like we should be providing an io.Copy impl with ctx argument that honors
// cancelation with the amount of code dedicated to working around it
// We're closing this here to disrupt the io.Copy below
// TODO: seems like we should be providing an io.Copy impl with ctx argument that honors
// cancelation with the amount of code dedicated to working around it
// TODO: I think this still leaves a race between closing of the API client transport and
// copying of the output streams, it's just likely the error will be dropped as the transport is
// closed when it occurs.
// We should move away from needing to close transports to interrupt reads.
stdin.Close()
case <-done:
}
}()
// TODO: I think this still leaves a race between closing of the API client transport and
// copying of the output streams, it's just likely the error will be dropped as the transport is
// closed when it occurs.
// We should move away from needing to close transports to interrupt reads.
stdin.Close()
case <-done:
}
}()
}
go func() {
defer close(done)
@@ -347,7 +400,7 @@ func copyStdIn(ctx context.Context, pl *client.PortLayer, ac *AttachConfig, stdi
// Write some init bytes into the pipe to force Swagger to make the initial
// call to the portlayer, prior to any user input in whatever attach client
// he/she is using.
log.Debugf("copyStdIn writing primer bytes")
op.Debugf("copyStdIn writing primer bytes")
stdinWriter.Write([]byte(attachStdinInitString))
if ac.UseTty {
_, err = copyEscapable(stdinWriter, stdin, keys)
@@ -357,10 +410,10 @@ func copyStdIn(ctx context.Context, pl *client.PortLayer, ac *AttachConfig, stdi
if err != nil {
if _, ok := err.(errors.DetachError); ok {
log.Infof("stdin detach detected")
op.Infof("stdin detach detected")
detach = true
} else {
log.Errorf("stdin err: %s", err)
op.Errorf("stdin err: %s", err)
}
}
}()
@@ -369,19 +422,21 @@ func copyStdIn(ctx context.Context, pl *client.PortLayer, ac *AttachConfig, stdi
// Swagger wants an io.reader so give it the reader pipe. Also, the swagger call
// to set the stdin is synchronous so we need to run in a goroutine
setStdinParams := interaction.NewContainerSetStdinParamsWithContext(ctx).WithID(id)
setStdinParams = setStdinParams.WithRawStream(stdinReader)
setStdinParams := interaction.NewContainerSetStdinParamsWithContext(op).
WithID(id).
WithRawStream(stdinReader).
WithOpID(&opID)
_, err := pl.Interaction.ContainerSetStdin(setStdinParams)
<-done
if ac.CloseStdin && !ac.UseTty {
// Close the stdin connection. Mimicing Docker's behavior.
log.Errorf("Attach stream has stdinOnce set. Closing the stdin.")
op.Errorf("Attach stream has stdinOnce set. Closing the stdin.")
params := interaction.NewContainerCloseStdinParamsWithContext(ctx).WithID(id)
_, err := pl.Interaction.ContainerCloseStdin(params)
if err != nil {
log.Errorf("CloseStdin failed with %s", err)
op.Errorf("CloseStdin failed with %s", err)
}
}
@@ -394,19 +449,21 @@ func copyStdIn(ctx context.Context, pl *client.PortLayer, ac *AttachConfig, stdi
}
func copyStdOut(ctx context.Context, pl *client.PortLayer, ac *AttachConfig, stdout io.Writer, attemptTimeout time.Duration) error {
op := trace.FromContext(ctx, "")
defer trace.End(trace.Begin("", op))
id := ac.ID
//Calculate how much time to let portlayer attempt
plAttemptTimeout := attemptTimeout - attachPLAttemptDiff //assumes personality deadline longer than portlayer's deadline
plAttemptDeadline := time.Now().Add(plAttemptTimeout)
swaggerDeadline := strfmt.DateTime(plAttemptDeadline)
log.Debugf("* stdout portlayer deadline: %s", plAttemptDeadline.Format(time.UnixDate))
log.Debugf("* stdout personality deadline: %s", time.Now().Add(attemptTimeout).Format(time.UnixDate))
op.Debugf("* stdout portlayer deadline: %s", plAttemptDeadline.Format(time.UnixDate))
op.Debugf("* stdout personality deadline: %s", time.Now().Add(attemptTimeout).Format(time.UnixDate))
log.Debugf("* stdout attach start %s", time.Now().Format(time.UnixDate))
op.Debugf("* stdout attach start %s", time.Now().Format(time.UnixDate))
getStdoutParams := interaction.NewContainerGetStdoutParamsWithContext(ctx).WithID(id).WithDeadline(&swaggerDeadline)
_, err := pl.Interaction.ContainerGetStdout(getStdoutParams, stdout)
log.Debugf("* stdout attach end %s", time.Now().Format(time.UnixDate))
op.Debugf("* stdout attach end %s", time.Now().Format(time.UnixDate))
if err != nil {
if _, ok := err.(*interaction.ContainerGetStdoutNotFound); ok {
return errors.ContainerResourceNotFoundError(id, "interaction connection")

View File

@@ -37,7 +37,6 @@ import (
"golang.org/x/net/context"
log "github.com/Sirupsen/logrus"
derr "github.com/docker/docker/api/errors"
"github.com/vmware/vic/lib/apiservers/engine/errors"
@@ -48,36 +47,37 @@ import (
"github.com/vmware/vic/pkg/trace"
)
type VicSystemProxy interface {
type SystemProxy interface {
PingPortlayer(ctx context.Context) bool
ContainerCount(ctx context.Context) (int, int, int, error)
VCHInfo(ctx context.Context) (*models.VCHInfo, error)
}
type SystemProxy struct {
type VicSystemProxy struct {
client *client.PortLayer
}
func NewSystemProxy(client *client.PortLayer) VicSystemProxy {
func NewSystemProxy(client *client.PortLayer) *VicSystemProxy {
if client == nil {
return nil
}
return &SystemProxy{client: client}
return &VicSystemProxy{client: client}
}
func (s *SystemProxy) PingPortlayer(ctx context.Context) bool {
defer trace.End(trace.Begin(""))
func (s *VicSystemProxy) PingPortlayer(ctx context.Context) bool {
op := trace.FromContext(ctx, "")
defer trace.End(trace.Begin("", op))
if s.client == nil {
log.Errorf("Portlayer client is invalid")
op.Errorf("Portlayer client is invalid")
return false
}
pingParams := misc.NewPingParamsWithContext(ctx)
_, err := s.client.Misc.Ping(pingParams)
if err != nil {
log.Info("Ping to portlayer failed")
op.Info("Ping to portlayer failed")
return false
}
return true
@@ -85,8 +85,10 @@ func (s *SystemProxy) PingPortlayer(ctx context.Context) bool {
// Use the Portlayer's support for docker ps to get the container count
// return order: running, paused, stopped counts
func (s *SystemProxy) ContainerCount(ctx context.Context) (int, int, int, error) {
defer trace.End(trace.Begin(""))
func (s *VicSystemProxy) ContainerCount(ctx context.Context) (int, int, int, error) {
op := trace.FromContext(ctx, "")
defer trace.End(trace.Begin("", op))
opID := op.ID()
var running, paused, stopped int
@@ -95,7 +97,8 @@ func (s *SystemProxy) ContainerCount(ctx context.Context) (int, int, int, error)
}
all := true
containList, err := s.client.Containers.GetContainerList(containers.NewGetContainerListParamsWithContext(ctx).WithAll(&all))
params := containers.NewGetContainerListParamsWithContext(ctx).WithAll(&all).WithOpID(&opID)
containList, err := s.client.Containers.GetContainerList(params)
if err != nil {
return 0, 0, 0, derr.NewErrorWithStatusCode(fmt.Errorf("Failed to get container list: %s", err), http.StatusInternalServerError)
}
@@ -112,14 +115,16 @@ func (s *SystemProxy) ContainerCount(ctx context.Context) (int, int, int, error)
return running, paused, stopped, nil
}
func (s *SystemProxy) VCHInfo(ctx context.Context) (*models.VCHInfo, error) {
defer trace.End(trace.Begin(""))
func (s *VicSystemProxy) VCHInfo(ctx context.Context) (*models.VCHInfo, error) {
op := trace.FromContext(ctx, "")
defer trace.End(trace.Begin("", op))
opID := op.ID()
if s.client == nil {
return nil, errors.NillPortlayerClientError("SystemProxy")
}
params := misc.NewGetVCHInfoParamsWithContext(ctx)
params := misc.NewGetVCHInfoParamsWithContext(ctx).WithOpID(&opID)
resp, err := s.client.Misc.GetVCHInfo(params)
if err != nil {
//There are no custom error for this operation. If we get back an error, it's

View File

@@ -61,6 +61,8 @@ for the commit operation typically these are written to a http.Request
*/
type CommitParams struct {
/*OpID*/
OpID *string
/*Handle*/
Handle string
/*WaitTime*/
@@ -104,6 +106,17 @@ func (o *CommitParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the commit params
func (o *CommitParams) WithOpID(opID *string) *CommitParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the commit params
func (o *CommitParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithHandle adds the handle to the commit params
func (o *CommitParams) WithHandle(handle string) *CommitParams {
o.SetHandle(handle)
@@ -132,6 +145,15 @@ func (o *CommitParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Regist
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param handle
if err := r.SetPathParam("handle", o.Handle); err != nil {
return err

View File

@@ -81,6 +81,8 @@ for the container remove operation typically these are written to a http.Request
*/
type ContainerRemoveParams struct {
/*OpID*/
OpID *string
/*Force*/
Force *bool
/*ID*/
@@ -126,6 +128,17 @@ func (o *ContainerRemoveParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the container remove params
func (o *ContainerRemoveParams) WithOpID(opID *string) *ContainerRemoveParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the container remove params
func (o *ContainerRemoveParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithForce adds the force to the container remove params
func (o *ContainerRemoveParams) WithForce(force *bool) *ContainerRemoveParams {
o.SetForce(force)
@@ -165,6 +178,15 @@ func (o *ContainerRemoveParams) WriteToRequest(r runtime.ClientRequest, reg strf
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.Force != nil {
// query param force

View File

@@ -60,6 +60,8 @@ for the container rename operation typically these are written to a http.Request
*/
type ContainerRenameParams struct {
/*OpID*/
OpID *string
/*Handle*/
Handle string
/*Name
@@ -106,6 +108,17 @@ func (o *ContainerRenameParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the container rename params
func (o *ContainerRenameParams) WithOpID(opID *string) *ContainerRenameParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the container rename params
func (o *ContainerRenameParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithHandle adds the handle to the container rename params
func (o *ContainerRenameParams) WithHandle(handle string) *ContainerRenameParams {
o.SetHandle(handle)
@@ -134,6 +147,15 @@ func (o *ContainerRenameParams) WriteToRequest(r runtime.ClientRequest, reg strf
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param handle
if err := r.SetPathParam("handle", o.Handle); err != nil {
return err

View File

@@ -61,6 +61,8 @@ for the container signal operation typically these are written to a http.Request
*/
type ContainerSignalParams struct {
/*OpID*/
OpID *string
/*ID*/
ID string
/*Signal*/
@@ -104,6 +106,17 @@ func (o *ContainerSignalParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the container signal params
func (o *ContainerSignalParams) WithOpID(opID *string) *ContainerSignalParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the container signal params
func (o *ContainerSignalParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithID adds the id to the container signal params
func (o *ContainerSignalParams) WithID(id string) *ContainerSignalParams {
o.SetID(id)
@@ -132,6 +145,15 @@ func (o *ContainerSignalParams) WriteToRequest(r runtime.ClientRequest, reg strf
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param id
if err := r.SetPathParam("id", o.ID); err != nil {
return err

View File

@@ -61,6 +61,8 @@ for the container wait operation typically these are written to a http.Request
*/
type ContainerWaitParams struct {
/*OpID*/
OpID *string
/*ID*/
ID string
/*Timeout*/
@@ -104,6 +106,17 @@ func (o *ContainerWaitParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the container wait params
func (o *ContainerWaitParams) WithOpID(opID *string) *ContainerWaitParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the container wait params
func (o *ContainerWaitParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithID adds the id to the container wait params
func (o *ContainerWaitParams) WithID(id string) *ContainerWaitParams {
o.SetID(id)
@@ -132,6 +145,15 @@ func (o *ContainerWaitParams) WriteToRequest(r runtime.ClientRequest, reg strfmt
r.SetTimeout(o.requestTimeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param id
if err := r.SetPathParam("id", o.ID); err != nil {
return err

View File

@@ -62,6 +62,8 @@ for the create operation typically these are written to a http.Request
*/
type CreateParams struct {
/*OpID*/
OpID *string
/*CreateConfig*/
CreateConfig *models.ContainerCreateConfig
/*Name*/
@@ -105,6 +107,17 @@ func (o *CreateParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the create params
func (o *CreateParams) WithOpID(opID *string) *CreateParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the create params
func (o *CreateParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithCreateConfig adds the createConfig to the create params
func (o *CreateParams) WithCreateConfig(createConfig *models.ContainerCreateConfig) *CreateParams {
o.SetCreateConfig(createConfig)
@@ -133,6 +146,15 @@ func (o *CreateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Regist
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.CreateConfig == nil {
o.CreateConfig = new(models.ContainerCreateConfig)
}

View File

@@ -60,6 +60,8 @@ for the get container info operation typically these are written to a http.Reque
*/
type GetContainerInfoParams struct {
/*OpID*/
OpID *string
/*ID*/
ID string
@@ -101,6 +103,17 @@ func (o *GetContainerInfoParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the get container info params
func (o *GetContainerInfoParams) WithOpID(opID *string) *GetContainerInfoParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the get container info params
func (o *GetContainerInfoParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithID adds the id to the get container info params
func (o *GetContainerInfoParams) WithID(id string) *GetContainerInfoParams {
o.SetID(id)
@@ -118,6 +131,15 @@ func (o *GetContainerInfoParams) WriteToRequest(r runtime.ClientRequest, reg str
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param id
if err := r.SetPathParam("id", o.ID); err != nil {
return err

View File

@@ -61,6 +61,8 @@ for the get container list operation typically these are written to a http.Reque
*/
type GetContainerListParams struct {
/*OpID*/
OpID *string
/*All*/
All *bool
@@ -102,6 +104,17 @@ func (o *GetContainerListParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the get container list params
func (o *GetContainerListParams) WithOpID(opID *string) *GetContainerListParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the get container list params
func (o *GetContainerListParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithAll adds the all to the get container list params
func (o *GetContainerListParams) WithAll(all *bool) *GetContainerListParams {
o.SetAll(all)
@@ -119,6 +132,15 @@ func (o *GetContainerListParams) WriteToRequest(r runtime.ClientRequest, reg str
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.All != nil {
// query param all

View File

@@ -81,6 +81,8 @@ for the get container logs operation typically these are written to a http.Reque
*/
type GetContainerLogsParams struct {
/*OpID*/
OpID *string
/*Deadline*/
Deadline *int64
/*Follow*/
@@ -132,6 +134,17 @@ func (o *GetContainerLogsParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the get container logs params
func (o *GetContainerLogsParams) WithOpID(opID *string) *GetContainerLogsParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the get container logs params
func (o *GetContainerLogsParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithDeadline adds the deadline to the get container logs params
func (o *GetContainerLogsParams) WithDeadline(deadline *int64) *GetContainerLogsParams {
o.SetDeadline(deadline)
@@ -204,6 +217,15 @@ func (o *GetContainerLogsParams) WriteToRequest(r runtime.ClientRequest, reg str
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.Deadline != nil {
// query param deadline

View File

@@ -61,6 +61,8 @@ for the get container stats operation typically these are written to a http.Requ
*/
type GetContainerStatsParams struct {
/*OpID*/
OpID *string
/*ID*/
ID string
/*Stream*/
@@ -104,6 +106,17 @@ func (o *GetContainerStatsParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the get container stats params
func (o *GetContainerStatsParams) WithOpID(opID *string) *GetContainerStatsParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the get container stats params
func (o *GetContainerStatsParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithID adds the id to the get container stats params
func (o *GetContainerStatsParams) WithID(id string) *GetContainerStatsParams {
o.SetID(id)
@@ -132,6 +145,15 @@ func (o *GetContainerStatsParams) WriteToRequest(r runtime.ClientRequest, reg st
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param id
if err := r.SetPathParam("id", o.ID); err != nil {
return err

View File

@@ -60,6 +60,8 @@ for the get operation typically these are written to a http.Request
*/
type GetParams struct {
/*OpID*/
OpID *string
/*ID*/
ID string
@@ -101,6 +103,17 @@ func (o *GetParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the get params
func (o *GetParams) WithOpID(opID *string) *GetParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the get params
func (o *GetParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithID adds the id to the get params
func (o *GetParams) WithID(id string) *GetParams {
o.SetID(id)
@@ -118,6 +131,15 @@ func (o *GetParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry)
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param id
if err := r.SetPathParam("id", o.ID); err != nil {
return err

View File

@@ -60,6 +60,8 @@ for the get state operation typically these are written to a http.Request
*/
type GetStateParams struct {
/*OpID*/
OpID *string
/*Handle*/
Handle string
@@ -101,6 +103,17 @@ func (o *GetStateParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the get state params
func (o *GetStateParams) WithOpID(opID *string) *GetStateParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the get state params
func (o *GetStateParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithHandle adds the handle to the get state params
func (o *GetStateParams) WithHandle(handle string) *GetStateParams {
o.SetHandle(handle)
@@ -118,6 +131,15 @@ func (o *GetStateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Regi
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param handle
if err := r.SetPathParam("handle", o.Handle); err != nil {
return err

View File

@@ -60,6 +60,8 @@ for the state change operation typically these are written to a http.Request
*/
type StateChangeParams struct {
/*OpID*/
OpID *string
/*Handle*/
Handle string
/*State*/
@@ -103,6 +105,17 @@ func (o *StateChangeParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the state change params
func (o *StateChangeParams) WithOpID(opID *string) *StateChangeParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the state change params
func (o *StateChangeParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithHandle adds the handle to the state change params
func (o *StateChangeParams) WithHandle(handle string) *StateChangeParams {
o.SetHandle(handle)
@@ -131,6 +144,15 @@ func (o *StateChangeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.R
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param handle
if err := r.SetPathParam("handle", o.Handle); err != nil {
return err

View File

@@ -19,7 +19,7 @@ import (
// NewGetEventsParams creates a new GetEventsParams object
// with the default values initialized.
func NewGetEventsParams() *GetEventsParams {
var ()
return &GetEventsParams{
timeout: cr.DefaultTimeout,
@@ -29,7 +29,7 @@ func NewGetEventsParams() *GetEventsParams {
// NewGetEventsParamsWithTimeout creates a new GetEventsParams object
// with the default values initialized, and the ability to set a timeout on a request
func NewGetEventsParamsWithTimeout(timeout time.Duration) *GetEventsParams {
var ()
return &GetEventsParams{
timeout: timeout,
@@ -39,7 +39,7 @@ func NewGetEventsParamsWithTimeout(timeout time.Duration) *GetEventsParams {
// NewGetEventsParamsWithContext creates a new GetEventsParams object
// with the default values initialized, and the ability to set a context for a request
func NewGetEventsParamsWithContext(ctx context.Context) *GetEventsParams {
var ()
return &GetEventsParams{
Context: ctx,
@@ -49,7 +49,7 @@ func NewGetEventsParamsWithContext(ctx context.Context) *GetEventsParams {
// NewGetEventsParamsWithHTTPClient creates a new GetEventsParams object
// with the default values initialized, and the ability to set a custom HTTPClient for a request
func NewGetEventsParamsWithHTTPClient(client *http.Client) *GetEventsParams {
var ()
return &GetEventsParams{
HTTPClient: client,
}
@@ -59,6 +59,10 @@ func NewGetEventsParamsWithHTTPClient(client *http.Client) *GetEventsParams {
for the get events operation typically these are written to a http.Request
*/
type GetEventsParams struct {
/*OpID*/
OpID *string
timeout time.Duration
Context context.Context
HTTPClient *http.Client
@@ -97,12 +101,32 @@ func (o *GetEventsParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the get events params
func (o *GetEventsParams) WithOpID(opID *string) *GetEventsParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the get events params
func (o *GetEventsParams) SetOpID(opID *string) {
o.OpID = opID
}
// WriteToRequest writes these params to a swagger request
func (o *GetEventsParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}

View File

@@ -60,6 +60,8 @@ for the container close stdin operation typically these are written to a http.Re
*/
type ContainerCloseStdinParams struct {
/*OpID*/
OpID *string
/*ID*/
ID string
@@ -101,6 +103,17 @@ func (o *ContainerCloseStdinParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the container close stdin params
func (o *ContainerCloseStdinParams) WithOpID(opID *string) *ContainerCloseStdinParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the container close stdin params
func (o *ContainerCloseStdinParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithID adds the id to the container close stdin params
func (o *ContainerCloseStdinParams) WithID(id string) *ContainerCloseStdinParams {
o.SetID(id)
@@ -118,6 +131,15 @@ func (o *ContainerCloseStdinParams) WriteToRequest(r runtime.ClientRequest, reg
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param id
if err := r.SetPathParam("id", o.ID); err != nil {
return err

View File

@@ -60,6 +60,8 @@ for the container get stderr operation typically these are written to a http.Req
*/
type ContainerGetStderrParams struct {
/*OpID*/
OpID *string
/*Deadline*/
Deadline *strfmt.DateTime
/*ID*/
@@ -103,6 +105,17 @@ func (o *ContainerGetStderrParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the container get stderr params
func (o *ContainerGetStderrParams) WithOpID(opID *string) *ContainerGetStderrParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the container get stderr params
func (o *ContainerGetStderrParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithDeadline adds the deadline to the container get stderr params
func (o *ContainerGetStderrParams) WithDeadline(deadline *strfmt.DateTime) *ContainerGetStderrParams {
o.SetDeadline(deadline)
@@ -131,6 +144,15 @@ func (o *ContainerGetStderrParams) WriteToRequest(r runtime.ClientRequest, reg s
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.Deadline != nil {
// query param deadline

View File

@@ -60,6 +60,8 @@ for the container get stdout operation typically these are written to a http.Req
*/
type ContainerGetStdoutParams struct {
/*OpID*/
OpID *string
/*Deadline*/
Deadline *strfmt.DateTime
/*ID*/
@@ -103,6 +105,17 @@ func (o *ContainerGetStdoutParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the container get stdout params
func (o *ContainerGetStdoutParams) WithOpID(opID *string) *ContainerGetStdoutParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the container get stdout params
func (o *ContainerGetStdoutParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithDeadline adds the deadline to the container get stdout params
func (o *ContainerGetStdoutParams) WithDeadline(deadline *strfmt.DateTime) *ContainerGetStdoutParams {
o.SetDeadline(deadline)
@@ -131,6 +144,15 @@ func (o *ContainerGetStdoutParams) WriteToRequest(r runtime.ClientRequest, reg s
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.Deadline != nil {
// query param deadline

View File

@@ -61,6 +61,8 @@ for the container resize operation typically these are written to a http.Request
*/
type ContainerResizeParams struct {
/*OpID*/
OpID *string
/*Height*/
Height int32
/*ID*/
@@ -106,6 +108,17 @@ func (o *ContainerResizeParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the container resize params
func (o *ContainerResizeParams) WithOpID(opID *string) *ContainerResizeParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the container resize params
func (o *ContainerResizeParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithHeight adds the height to the container resize params
func (o *ContainerResizeParams) WithHeight(height int32) *ContainerResizeParams {
o.SetHeight(height)
@@ -145,6 +158,15 @@ func (o *ContainerResizeParams) WriteToRequest(r runtime.ClientRequest, reg strf
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// query param height
qrHeight := o.Height
qHeight := swag.FormatInt32(qrHeight)

View File

@@ -61,6 +61,8 @@ for the container set stdin operation typically these are written to a http.Requ
*/
type ContainerSetStdinParams struct {
/*OpID*/
OpID *string
/*Deadline*/
Deadline *strfmt.DateTime
/*ID*/
@@ -106,6 +108,17 @@ func (o *ContainerSetStdinParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the container set stdin params
func (o *ContainerSetStdinParams) WithOpID(opID *string) *ContainerSetStdinParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the container set stdin params
func (o *ContainerSetStdinParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithDeadline adds the deadline to the container set stdin params
func (o *ContainerSetStdinParams) WithDeadline(deadline *strfmt.DateTime) *ContainerSetStdinParams {
o.SetDeadline(deadline)
@@ -145,6 +158,15 @@ func (o *ContainerSetStdinParams) WriteToRequest(r runtime.ClientRequest, reg st
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.Deadline != nil {
// query param deadline

View File

@@ -62,6 +62,8 @@ for the interaction bind operation typically these are written to a http.Request
*/
type InteractionBindParams struct {
/*OpID*/
OpID *string
/*Config*/
Config *models.InteractionBindConfig
@@ -103,6 +105,17 @@ func (o *InteractionBindParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the interaction bind params
func (o *InteractionBindParams) WithOpID(opID *string) *InteractionBindParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the interaction bind params
func (o *InteractionBindParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithConfig adds the config to the interaction bind params
func (o *InteractionBindParams) WithConfig(config *models.InteractionBindConfig) *InteractionBindParams {
o.SetConfig(config)
@@ -120,6 +133,15 @@ func (o *InteractionBindParams) WriteToRequest(r runtime.ClientRequest, reg strf
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.Config == nil {
o.Config = new(models.InteractionBindConfig)
}

View File

@@ -62,6 +62,8 @@ for the interaction join operation typically these are written to a http.Request
*/
type InteractionJoinParams struct {
/*OpID*/
OpID *string
/*Config*/
Config *models.InteractionJoinConfig
@@ -103,6 +105,17 @@ func (o *InteractionJoinParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the interaction join params
func (o *InteractionJoinParams) WithOpID(opID *string) *InteractionJoinParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the interaction join params
func (o *InteractionJoinParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithConfig adds the config to the interaction join params
func (o *InteractionJoinParams) WithConfig(config *models.InteractionJoinConfig) *InteractionJoinParams {
o.SetConfig(config)
@@ -120,6 +133,15 @@ func (o *InteractionJoinParams) WriteToRequest(r runtime.ClientRequest, reg strf
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.Config == nil {
o.Config = new(models.InteractionJoinConfig)
}

View File

@@ -62,6 +62,8 @@ for the interaction unbind operation typically these are written to a http.Reque
*/
type InteractionUnbindParams struct {
/*OpID*/
OpID *string
/*Config*/
Config *models.InteractionUnbindConfig
@@ -103,6 +105,17 @@ func (o *InteractionUnbindParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the interaction unbind params
func (o *InteractionUnbindParams) WithOpID(opID *string) *InteractionUnbindParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the interaction unbind params
func (o *InteractionUnbindParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithConfig adds the config to the interaction unbind params
func (o *InteractionUnbindParams) WithConfig(config *models.InteractionUnbindConfig) *InteractionUnbindParams {
o.SetConfig(config)
@@ -120,6 +133,15 @@ func (o *InteractionUnbindParams) WriteToRequest(r runtime.ClientRequest, reg st
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.Config == nil {
o.Config = new(models.InteractionUnbindConfig)
}

View File

@@ -60,6 +60,8 @@ for the delete value operation typically these are written to a http.Request
*/
type DeleteValueParams struct {
/*OpID*/
OpID *string
/*Key*/
Key string
@@ -101,6 +103,17 @@ func (o *DeleteValueParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the delete value params
func (o *DeleteValueParams) WithOpID(opID *string) *DeleteValueParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the delete value params
func (o *DeleteValueParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithKey adds the key to the delete value params
func (o *DeleteValueParams) WithKey(key string) *DeleteValueParams {
o.SetKey(key)
@@ -118,6 +131,15 @@ func (o *DeleteValueParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.R
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param key
if err := r.SetPathParam("key", o.Key); err != nil {
return err

View File

@@ -60,6 +60,8 @@ for the get value operation typically these are written to a http.Request
*/
type GetValueParams struct {
/*OpID*/
OpID *string
/*Key*/
Key string
@@ -101,6 +103,17 @@ func (o *GetValueParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the get value params
func (o *GetValueParams) WithOpID(opID *string) *GetValueParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the get value params
func (o *GetValueParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithKey adds the key to the get value params
func (o *GetValueParams) WithKey(key string) *GetValueParams {
o.SetKey(key)
@@ -118,6 +131,15 @@ func (o *GetValueParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Regi
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param key
if err := r.SetPathParam("key", o.Key); err != nil {
return err

View File

@@ -62,6 +62,8 @@ for the put value operation typically these are written to a http.Request
*/
type PutValueParams struct {
/*OpID*/
OpID *string
/*Key*/
Key string
/*KeyValue*/
@@ -105,6 +107,17 @@ func (o *PutValueParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the put value params
func (o *PutValueParams) WithOpID(opID *string) *PutValueParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the put value params
func (o *PutValueParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithKey adds the key to the put value params
func (o *PutValueParams) WithKey(key string) *PutValueParams {
o.SetKey(key)
@@ -133,6 +146,15 @@ func (o *PutValueParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Regi
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param key
if err := r.SetPathParam("key", o.Key); err != nil {
return err

View File

@@ -62,6 +62,8 @@ for the logging bind operation typically these are written to a http.Request
*/
type LoggingBindParams struct {
/*OpID*/
OpID *string
/*Config*/
Config *models.LoggingBindConfig
@@ -103,6 +105,17 @@ func (o *LoggingBindParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the logging bind params
func (o *LoggingBindParams) WithOpID(opID *string) *LoggingBindParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the logging bind params
func (o *LoggingBindParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithConfig adds the config to the logging bind params
func (o *LoggingBindParams) WithConfig(config *models.LoggingBindConfig) *LoggingBindParams {
o.SetConfig(config)
@@ -120,6 +133,15 @@ func (o *LoggingBindParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.R
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.Config == nil {
o.Config = new(models.LoggingBindConfig)
}

View File

@@ -62,6 +62,8 @@ for the logging join operation typically these are written to a http.Request
*/
type LoggingJoinParams struct {
/*OpID*/
OpID *string
/*Config*/
Config *models.LoggingJoinConfig
@@ -103,6 +105,17 @@ func (o *LoggingJoinParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the logging join params
func (o *LoggingJoinParams) WithOpID(opID *string) *LoggingJoinParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the logging join params
func (o *LoggingJoinParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithConfig adds the config to the logging join params
func (o *LoggingJoinParams) WithConfig(config *models.LoggingJoinConfig) *LoggingJoinParams {
o.SetConfig(config)
@@ -120,6 +133,15 @@ func (o *LoggingJoinParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.R
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.Config == nil {
o.Config = new(models.LoggingJoinConfig)
}

View File

@@ -62,6 +62,8 @@ for the logging unbind operation typically these are written to a http.Request
*/
type LoggingUnbindParams struct {
/*OpID*/
OpID *string
/*Config*/
Config *models.LoggingUnbindConfig
@@ -103,6 +105,17 @@ func (o *LoggingUnbindParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the logging unbind params
func (o *LoggingUnbindParams) WithOpID(opID *string) *LoggingUnbindParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the logging unbind params
func (o *LoggingUnbindParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithConfig adds the config to the logging unbind params
func (o *LoggingUnbindParams) WithConfig(config *models.LoggingUnbindConfig) *LoggingUnbindParams {
o.SetConfig(config)
@@ -120,6 +133,15 @@ func (o *LoggingUnbindParams) WriteToRequest(r runtime.ClientRequest, reg strfmt
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.Config == nil {
o.Config = new(models.LoggingUnbindConfig)
}

View File

@@ -19,7 +19,7 @@ import (
// NewGetVCHInfoParams creates a new GetVCHInfoParams object
// with the default values initialized.
func NewGetVCHInfoParams() *GetVCHInfoParams {
var ()
return &GetVCHInfoParams{
timeout: cr.DefaultTimeout,
@@ -29,7 +29,7 @@ func NewGetVCHInfoParams() *GetVCHInfoParams {
// NewGetVCHInfoParamsWithTimeout creates a new GetVCHInfoParams object
// with the default values initialized, and the ability to set a timeout on a request
func NewGetVCHInfoParamsWithTimeout(timeout time.Duration) *GetVCHInfoParams {
var ()
return &GetVCHInfoParams{
timeout: timeout,
@@ -39,7 +39,7 @@ func NewGetVCHInfoParamsWithTimeout(timeout time.Duration) *GetVCHInfoParams {
// NewGetVCHInfoParamsWithContext creates a new GetVCHInfoParams object
// with the default values initialized, and the ability to set a context for a request
func NewGetVCHInfoParamsWithContext(ctx context.Context) *GetVCHInfoParams {
var ()
return &GetVCHInfoParams{
Context: ctx,
@@ -49,7 +49,7 @@ func NewGetVCHInfoParamsWithContext(ctx context.Context) *GetVCHInfoParams {
// NewGetVCHInfoParamsWithHTTPClient creates a new GetVCHInfoParams object
// with the default values initialized, and the ability to set a custom HTTPClient for a request
func NewGetVCHInfoParamsWithHTTPClient(client *http.Client) *GetVCHInfoParams {
var ()
return &GetVCHInfoParams{
HTTPClient: client,
}
@@ -59,6 +59,10 @@ func NewGetVCHInfoParamsWithHTTPClient(client *http.Client) *GetVCHInfoParams {
for the get v c h info operation typically these are written to a http.Request
*/
type GetVCHInfoParams struct {
/*OpID*/
OpID *string
timeout time.Duration
Context context.Context
HTTPClient *http.Client
@@ -97,12 +101,32 @@ func (o *GetVCHInfoParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the get v c h info params
func (o *GetVCHInfoParams) WithOpID(opID *string) *GetVCHInfoParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the get v c h info params
func (o *GetVCHInfoParams) SetOpID(opID *string) {
o.OpID = opID
}
// WriteToRequest writes these params to a swagger request
func (o *GetVCHInfoParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}

View File

@@ -62,6 +62,8 @@ for the add container operation typically these are written to a http.Request
*/
type AddContainerParams struct {
/*OpID*/
OpID *string
/*Config*/
Config *models.ScopesAddContainerConfig
/*Scope*/
@@ -105,6 +107,17 @@ func (o *AddContainerParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the add container params
func (o *AddContainerParams) WithOpID(opID *string) *AddContainerParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the add container params
func (o *AddContainerParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithConfig adds the config to the add container params
func (o *AddContainerParams) WithConfig(config *models.ScopesAddContainerConfig) *AddContainerParams {
o.SetConfig(config)
@@ -133,6 +146,15 @@ func (o *AddContainerParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.Config == nil {
o.Config = new(models.ScopesAddContainerConfig)
}

View File

@@ -60,6 +60,8 @@ for the bind container operation typically these are written to a http.Request
*/
type BindContainerParams struct {
/*OpID*/
OpID *string
/*Handle*/
Handle string
@@ -101,6 +103,17 @@ func (o *BindContainerParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the bind container params
func (o *BindContainerParams) WithOpID(opID *string) *BindContainerParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the bind container params
func (o *BindContainerParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithHandle adds the handle to the bind container params
func (o *BindContainerParams) WithHandle(handle string) *BindContainerParams {
o.SetHandle(handle)
@@ -118,6 +131,15 @@ func (o *BindContainerParams) WriteToRequest(r runtime.ClientRequest, reg strfmt
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param handle
if err := r.SetPathParam("handle", o.Handle); err != nil {
return err

View File

@@ -62,6 +62,8 @@ for the create scope operation typically these are written to a http.Request
*/
type CreateScopeParams struct {
/*OpID*/
OpID *string
/*Config*/
Config *models.ScopeConfig
@@ -103,6 +105,17 @@ func (o *CreateScopeParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the create scope params
func (o *CreateScopeParams) WithOpID(opID *string) *CreateScopeParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the create scope params
func (o *CreateScopeParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithConfig adds the config to the create scope params
func (o *CreateScopeParams) WithConfig(config *models.ScopeConfig) *CreateScopeParams {
o.SetConfig(config)
@@ -120,6 +133,15 @@ func (o *CreateScopeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.R
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.Config == nil {
o.Config = new(models.ScopeConfig)
}

View File

@@ -60,6 +60,8 @@ for the delete scope operation typically these are written to a http.Request
*/
type DeleteScopeParams struct {
/*OpID*/
OpID *string
/*IDName*/
IDName string
@@ -101,6 +103,17 @@ func (o *DeleteScopeParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the delete scope params
func (o *DeleteScopeParams) WithOpID(opID *string) *DeleteScopeParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the delete scope params
func (o *DeleteScopeParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithIDName adds the iDName to the delete scope params
func (o *DeleteScopeParams) WithIDName(iDName string) *DeleteScopeParams {
o.SetIDName(iDName)
@@ -118,6 +131,15 @@ func (o *DeleteScopeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.R
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param idName
if err := r.SetPathParam("idName", o.IDName); err != nil {
return err

View File

@@ -60,6 +60,8 @@ for the get container endpoints operation typically these are written to a http.
*/
type GetContainerEndpointsParams struct {
/*OpID*/
OpID *string
/*HandleOrID*/
HandleOrID string
@@ -101,6 +103,17 @@ func (o *GetContainerEndpointsParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the get container endpoints params
func (o *GetContainerEndpointsParams) WithOpID(opID *string) *GetContainerEndpointsParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the get container endpoints params
func (o *GetContainerEndpointsParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithHandleOrID adds the handleOrID to the get container endpoints params
func (o *GetContainerEndpointsParams) WithHandleOrID(handleOrID string) *GetContainerEndpointsParams {
o.SetHandleOrID(handleOrID)
@@ -118,6 +131,15 @@ func (o *GetContainerEndpointsParams) WriteToRequest(r runtime.ClientRequest, re
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param handleOrId
if err := r.SetPathParam("handleOrId", o.HandleOrID); err != nil {
return err

View File

@@ -19,7 +19,7 @@ import (
// NewListAllParams creates a new ListAllParams object
// with the default values initialized.
func NewListAllParams() *ListAllParams {
var ()
return &ListAllParams{
timeout: cr.DefaultTimeout,
@@ -29,7 +29,7 @@ func NewListAllParams() *ListAllParams {
// NewListAllParamsWithTimeout creates a new ListAllParams object
// with the default values initialized, and the ability to set a timeout on a request
func NewListAllParamsWithTimeout(timeout time.Duration) *ListAllParams {
var ()
return &ListAllParams{
timeout: timeout,
@@ -39,7 +39,7 @@ func NewListAllParamsWithTimeout(timeout time.Duration) *ListAllParams {
// NewListAllParamsWithContext creates a new ListAllParams object
// with the default values initialized, and the ability to set a context for a request
func NewListAllParamsWithContext(ctx context.Context) *ListAllParams {
var ()
return &ListAllParams{
Context: ctx,
@@ -49,7 +49,7 @@ func NewListAllParamsWithContext(ctx context.Context) *ListAllParams {
// NewListAllParamsWithHTTPClient creates a new ListAllParams object
// with the default values initialized, and the ability to set a custom HTTPClient for a request
func NewListAllParamsWithHTTPClient(client *http.Client) *ListAllParams {
var ()
return &ListAllParams{
HTTPClient: client,
}
@@ -59,6 +59,10 @@ func NewListAllParamsWithHTTPClient(client *http.Client) *ListAllParams {
for the list all operation typically these are written to a http.Request
*/
type ListAllParams struct {
/*OpID*/
OpID *string
timeout time.Duration
Context context.Context
HTTPClient *http.Client
@@ -97,12 +101,32 @@ func (o *ListAllParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the list all params
func (o *ListAllParams) WithOpID(opID *string) *ListAllParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the list all params
func (o *ListAllParams) SetOpID(opID *string) {
o.OpID = opID
}
// WriteToRequest writes these params to a swagger request
func (o *ListAllParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}

View File

@@ -60,6 +60,8 @@ for the list operation typically these are written to a http.Request
*/
type ListParams struct {
/*OpID*/
OpID *string
/*IDName*/
IDName string
@@ -101,6 +103,17 @@ func (o *ListParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the list params
func (o *ListParams) WithOpID(opID *string) *ListParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the list params
func (o *ListParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithIDName adds the iDName to the list params
func (o *ListParams) WithIDName(iDName string) *ListParams {
o.SetIDName(iDName)
@@ -118,6 +131,15 @@ func (o *ListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param idName
if err := r.SetPathParam("idName", o.IDName); err != nil {
return err

View File

@@ -60,6 +60,8 @@ for the remove container operation typically these are written to a http.Request
*/
type RemoveContainerParams struct {
/*OpID*/
OpID *string
/*Handle*/
Handle string
/*Scope*/
@@ -103,6 +105,17 @@ func (o *RemoveContainerParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the remove container params
func (o *RemoveContainerParams) WithOpID(opID *string) *RemoveContainerParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the remove container params
func (o *RemoveContainerParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithHandle adds the handle to the remove container params
func (o *RemoveContainerParams) WithHandle(handle string) *RemoveContainerParams {
o.SetHandle(handle)
@@ -131,6 +144,15 @@ func (o *RemoveContainerParams) WriteToRequest(r runtime.ClientRequest, reg strf
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param handle
if err := r.SetPathParam("handle", o.Handle); err != nil {
return err

View File

@@ -60,6 +60,8 @@ for the unbind container operation typically these are written to a http.Request
*/
type UnbindContainerParams struct {
/*OpID*/
OpID *string
/*Handle*/
Handle string
@@ -101,6 +103,17 @@ func (o *UnbindContainerParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the unbind container params
func (o *UnbindContainerParams) WithOpID(opID *string) *UnbindContainerParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the unbind container params
func (o *UnbindContainerParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithHandle adds the handle to the unbind container params
func (o *UnbindContainerParams) WithHandle(handle string) *UnbindContainerParams {
o.SetHandle(handle)
@@ -118,6 +131,15 @@ func (o *UnbindContainerParams) WriteToRequest(r runtime.ClientRequest, reg strf
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param handle
if err := r.SetPathParam("handle", o.Handle); err != nil {
return err

View File

@@ -62,6 +62,8 @@ for the create image store operation typically these are written to a http.Reque
*/
type CreateImageStoreParams struct {
/*OpID*/
OpID *string
/*Body*/
Body *models.ImageStore
@@ -103,6 +105,17 @@ func (o *CreateImageStoreParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the create image store params
func (o *CreateImageStoreParams) WithOpID(opID *string) *CreateImageStoreParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the create image store params
func (o *CreateImageStoreParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithBody adds the body to the create image store params
func (o *CreateImageStoreParams) WithBody(body *models.ImageStore) *CreateImageStoreParams {
o.SetBody(body)
@@ -120,6 +133,15 @@ func (o *CreateImageStoreParams) WriteToRequest(r runtime.ClientRequest, reg str
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.Body == nil {
o.Body = new(models.ImageStore)
}

View File

@@ -62,6 +62,8 @@ for the create volume operation typically these are written to a http.Request
*/
type CreateVolumeParams struct {
/*OpID*/
OpID *string
/*VolumeRequest*/
VolumeRequest *models.VolumeRequest
@@ -103,6 +105,17 @@ func (o *CreateVolumeParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the create volume params
func (o *CreateVolumeParams) WithOpID(opID *string) *CreateVolumeParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the create volume params
func (o *CreateVolumeParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithVolumeRequest adds the volumeRequest to the create volume params
func (o *CreateVolumeParams) WithVolumeRequest(volumeRequest *models.VolumeRequest) *CreateVolumeParams {
o.SetVolumeRequest(volumeRequest)
@@ -120,6 +133,15 @@ func (o *CreateVolumeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.VolumeRequest == nil {
o.VolumeRequest = new(models.VolumeRequest)
}

View File

@@ -61,6 +61,8 @@ for the delete image operation typically these are written to a http.Request
*/
type DeleteImageParams struct {
/*OpID*/
OpID *string
/*ID*/
ID string
/*KeepNodes*/
@@ -106,6 +108,17 @@ func (o *DeleteImageParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the delete image params
func (o *DeleteImageParams) WithOpID(opID *string) *DeleteImageParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the delete image params
func (o *DeleteImageParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithID adds the id to the delete image params
func (o *DeleteImageParams) WithID(id string) *DeleteImageParams {
o.SetID(id)
@@ -145,6 +158,15 @@ func (o *DeleteImageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.R
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param id
if err := r.SetPathParam("id", o.ID); err != nil {
return err

View File

@@ -61,6 +61,8 @@ for the export archive operation typically these are written to a http.Request
*/
type ExportArchiveParams struct {
/*OpID*/
OpID *string
/*Ancestor*/
Ancestor *string
/*AncestorStore*/
@@ -112,6 +114,17 @@ func (o *ExportArchiveParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the export archive params
func (o *ExportArchiveParams) WithOpID(opID *string) *ExportArchiveParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the export archive params
func (o *ExportArchiveParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithAncestor adds the ancestor to the export archive params
func (o *ExportArchiveParams) WithAncestor(ancestor *string) *ExportArchiveParams {
o.SetAncestor(ancestor)
@@ -184,6 +197,15 @@ func (o *ExportArchiveParams) WriteToRequest(r runtime.ClientRequest, reg strfmt
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.Ancestor != nil {
// query param ancestor

View File

@@ -60,6 +60,8 @@ for the get image operation typically these are written to a http.Request
*/
type GetImageParams struct {
/*OpID*/
OpID *string
/*ID*/
ID string
/*StoreName*/
@@ -103,6 +105,17 @@ func (o *GetImageParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the get image params
func (o *GetImageParams) WithOpID(opID *string) *GetImageParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the get image params
func (o *GetImageParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithID adds the id to the get image params
func (o *GetImageParams) WithID(id string) *GetImageParams {
o.SetID(id)
@@ -131,6 +144,15 @@ func (o *GetImageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Regi
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param id
if err := r.SetPathParam("id", o.ID); err != nil {
return err

View File

@@ -60,6 +60,8 @@ for the get image tar operation typically these are written to a http.Request
*/
type GetImageTarParams struct {
/*OpID*/
OpID *string
/*ID*/
ID string
/*StoreName*/
@@ -103,6 +105,17 @@ func (o *GetImageTarParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the get image tar params
func (o *GetImageTarParams) WithOpID(opID *string) *GetImageTarParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the get image tar params
func (o *GetImageTarParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithID adds the id to the get image tar params
func (o *GetImageTarParams) WithID(id string) *GetImageTarParams {
o.SetID(id)
@@ -131,6 +144,15 @@ func (o *GetImageTarParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.R
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param id
if err := r.SetPathParam("id", o.ID); err != nil {
return err

View File

@@ -60,6 +60,8 @@ for the get volume operation typically these are written to a http.Request
*/
type GetVolumeParams struct {
/*OpID*/
OpID *string
/*Name*/
Name string
@@ -101,6 +103,17 @@ func (o *GetVolumeParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the get volume params
func (o *GetVolumeParams) WithOpID(opID *string) *GetVolumeParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the get volume params
func (o *GetVolumeParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithName adds the name to the get volume params
func (o *GetVolumeParams) WithName(name string) *GetVolumeParams {
o.SetName(name)
@@ -118,6 +131,15 @@ func (o *GetVolumeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Reg
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param name
if err := r.SetPathParam("name", o.Name); err != nil {
return err

View File

@@ -62,6 +62,8 @@ for the image join operation typically these are written to a http.Request
*/
type ImageJoinParams struct {
/*OpID*/
OpID *string
/*Config*/
Config *models.ImageJoinConfig
/*ID*/
@@ -107,6 +109,17 @@ func (o *ImageJoinParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the image join params
func (o *ImageJoinParams) WithOpID(opID *string) *ImageJoinParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the image join params
func (o *ImageJoinParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithConfig adds the config to the image join params
func (o *ImageJoinParams) WithConfig(config *models.ImageJoinConfig) *ImageJoinParams {
o.SetConfig(config)
@@ -146,6 +159,15 @@ func (o *ImageJoinParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Reg
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.Config == nil {
o.Config = new(models.ImageJoinConfig)
}

View File

@@ -63,6 +63,8 @@ type ImportArchiveParams struct {
/*Archive*/
Archive io.ReadCloser
/*OpID*/
OpID *string
/*DeviceID*/
DeviceID string
/*FilterSpec*/
@@ -119,6 +121,17 @@ func (o *ImportArchiveParams) SetArchive(archive io.ReadCloser) {
o.Archive = archive
}
// WithOpID adds the opID to the import archive params
func (o *ImportArchiveParams) WithOpID(opID *string) *ImportArchiveParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the import archive params
func (o *ImportArchiveParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithDeviceID adds the deviceID to the import archive params
func (o *ImportArchiveParams) WithDeviceID(deviceID string) *ImportArchiveParams {
o.SetDeviceID(deviceID)
@@ -162,6 +175,15 @@ func (o *ImportArchiveParams) WriteToRequest(r runtime.ClientRequest, reg strfmt
return err
}
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// query param deviceID
qrDeviceID := o.DeviceID
qDeviceID := qrDeviceID

View File

@@ -61,6 +61,8 @@ for the list images operation typically these are written to a http.Request
*/
type ListImagesParams struct {
/*OpID*/
OpID *string
/*Ids*/
Ids []string
/*StoreName*/
@@ -104,6 +106,17 @@ func (o *ListImagesParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the list images params
func (o *ListImagesParams) WithOpID(opID *string) *ListImagesParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the list images params
func (o *ListImagesParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithIds adds the ids to the list images params
func (o *ListImagesParams) WithIds(ids []string) *ListImagesParams {
o.SetIds(ids)
@@ -132,6 +145,15 @@ func (o *ListImagesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Re
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
valuesIds := o.Ids
joinedIds := swag.JoinByFormat(valuesIds, "")

View File

@@ -60,6 +60,8 @@ for the list volumes operation typically these are written to a http.Request
*/
type ListVolumesParams struct {
/*OpID*/
OpID *string
/*FilterString*/
FilterString *string
@@ -101,6 +103,17 @@ func (o *ListVolumesParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the list volumes params
func (o *ListVolumesParams) WithOpID(opID *string) *ListVolumesParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the list volumes params
func (o *ListVolumesParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithFilterString adds the filterString to the list volumes params
func (o *ListVolumesParams) WithFilterString(filterString *string) *ListVolumesParams {
o.SetFilterString(filterString)
@@ -118,6 +131,15 @@ func (o *ListVolumesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.R
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if o.FilterString != nil {
// query param filterString

View File

@@ -60,6 +60,8 @@ for the remove volume operation typically these are written to a http.Request
*/
type RemoveVolumeParams struct {
/*OpID*/
OpID *string
/*Name*/
Name string
@@ -101,6 +103,17 @@ func (o *RemoveVolumeParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the remove volume params
func (o *RemoveVolumeParams) WithOpID(opID *string) *RemoveVolumeParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the remove volume params
func (o *RemoveVolumeParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithName adds the name to the remove volume params
func (o *RemoveVolumeParams) WithName(name string) *RemoveVolumeParams {
o.SetName(name)
@@ -118,6 +131,15 @@ func (o *RemoveVolumeParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param name
if err := r.SetPathParam("name", o.Name); err != nil {
return err

View File

@@ -60,6 +60,8 @@ for the stat path operation typically these are written to a http.Request
*/
type StatPathParams struct {
/*OpID*/
OpID *string
/*DeviceID*/
DeviceID string
/*FilterSpec*/
@@ -105,6 +107,17 @@ func (o *StatPathParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the stat path params
func (o *StatPathParams) WithOpID(opID *string) *StatPathParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the stat path params
func (o *StatPathParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithDeviceID adds the deviceID to the stat path params
func (o *StatPathParams) WithDeviceID(deviceID string) *StatPathParams {
o.SetDeviceID(deviceID)
@@ -144,6 +157,15 @@ func (o *StatPathParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Regi
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// query param deviceID
qrDeviceID := o.DeviceID
qDeviceID := qrDeviceID

View File

@@ -64,6 +64,8 @@ type VolumeJoinParams struct {
/*JoinArgs*/
JoinArgs *models.VolumeJoinConfig
/*OpID*/
OpID *string
/*Name*/
Name string
@@ -116,6 +118,17 @@ func (o *VolumeJoinParams) SetJoinArgs(joinArgs *models.VolumeJoinConfig) {
o.JoinArgs = joinArgs
}
// WithOpID adds the opID to the volume join params
func (o *VolumeJoinParams) WithOpID(opID *string) *VolumeJoinParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the volume join params
func (o *VolumeJoinParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithName adds the name to the volume join params
func (o *VolumeJoinParams) WithName(name string) *VolumeJoinParams {
o.SetName(name)
@@ -141,6 +154,15 @@ func (o *VolumeJoinParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Re
return err
}
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
// path param name
if err := r.SetPathParam("name", o.Name); err != nil {
return err

View File

@@ -19,7 +19,7 @@ import (
// NewVolumeStoresListParams creates a new VolumeStoresListParams object
// with the default values initialized.
func NewVolumeStoresListParams() *VolumeStoresListParams {
var ()
return &VolumeStoresListParams{
timeout: cr.DefaultTimeout,
@@ -29,7 +29,7 @@ func NewVolumeStoresListParams() *VolumeStoresListParams {
// NewVolumeStoresListParamsWithTimeout creates a new VolumeStoresListParams object
// with the default values initialized, and the ability to set a timeout on a request
func NewVolumeStoresListParamsWithTimeout(timeout time.Duration) *VolumeStoresListParams {
var ()
return &VolumeStoresListParams{
timeout: timeout,
@@ -39,7 +39,7 @@ func NewVolumeStoresListParamsWithTimeout(timeout time.Duration) *VolumeStoresLi
// NewVolumeStoresListParamsWithContext creates a new VolumeStoresListParams object
// with the default values initialized, and the ability to set a context for a request
func NewVolumeStoresListParamsWithContext(ctx context.Context) *VolumeStoresListParams {
var ()
return &VolumeStoresListParams{
Context: ctx,
@@ -49,7 +49,7 @@ func NewVolumeStoresListParamsWithContext(ctx context.Context) *VolumeStoresList
// NewVolumeStoresListParamsWithHTTPClient creates a new VolumeStoresListParams object
// with the default values initialized, and the ability to set a custom HTTPClient for a request
func NewVolumeStoresListParamsWithHTTPClient(client *http.Client) *VolumeStoresListParams {
var ()
return &VolumeStoresListParams{
HTTPClient: client,
}
@@ -59,6 +59,10 @@ func NewVolumeStoresListParamsWithHTTPClient(client *http.Client) *VolumeStoresL
for the volume stores list operation typically these are written to a http.Request
*/
type VolumeStoresListParams struct {
/*OpID*/
OpID *string
timeout time.Duration
Context context.Context
HTTPClient *http.Client
@@ -97,12 +101,32 @@ func (o *VolumeStoresListParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the volume stores list params
func (o *VolumeStoresListParams) WithOpID(opID *string) *VolumeStoresListParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the volume stores list params
func (o *VolumeStoresListParams) SetOpID(opID *string) {
o.OpID = opID
}
// WriteToRequest writes these params to a swagger request
func (o *VolumeStoresListParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}

View File

@@ -61,6 +61,8 @@ for the write image operation typically these are written to a http.Request
*/
type WriteImageParams struct {
/*OpID*/
OpID *string
/*ImageFile*/
ImageFile io.ReadCloser
/*ImageID*/
@@ -114,6 +116,17 @@ func (o *WriteImageParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithOpID adds the opID to the write image params
func (o *WriteImageParams) WithOpID(opID *string) *WriteImageParams {
o.SetOpID(opID)
return o
}
// SetOpID adds the opId to the write image params
func (o *WriteImageParams) SetOpID(opID *string) {
o.OpID = opID
}
// WithImageFile adds the imageFile to the write image params
func (o *WriteImageParams) WithImageFile(imageFile io.ReadCloser) *WriteImageParams {
o.SetImageFile(imageFile)
@@ -197,6 +210,15 @@ func (o *WriteImageParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Re
r.SetTimeout(o.timeout)
var res []error
if o.OpID != nil {
// header param Op-ID
if err := r.SetHeaderParam("Op-ID", *o.OpID); err != nil {
return err
}
}
if err := r.SetBodyParam(o.ImageFile); err != nil {
return err
}

Some files were not shown because too many files have changed in this diff Show More