diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/client.go b/vendor/github.com/aws/aws-sdk-go/aws/client/client.go index aeeada0..17fc76a 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/client.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/client/client.go @@ -24,6 +24,13 @@ type ConfigProvider interface { ClientConfig(serviceName string, cfgs ...*aws.Config) Config } +// ConfigNoResolveEndpointProvider same as ConfigProvider except it will not +// resolve the endpoint automatically. The service client's endpoint must be +// provided via the aws.Config.Endpoint field. +type ConfigNoResolveEndpointProvider interface { + ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) Config +} + // A Client implements the base client request and response handling // used by all service clients. type Client struct { diff --git a/vendor/github.com/aws/aws-sdk-go/aws/config.go b/vendor/github.com/aws/aws-sdk-go/aws/config.go index d58b812..948e0a6 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/config.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/config.go @@ -22,9 +22,9 @@ type RequestRetryer interface{} // // // Create Session with MaxRetry configuration to be shared by multiple // // service clients. -// sess, err := session.NewSession(&aws.Config{ +// sess := session.Must(session.NewSession(&aws.Config{ // MaxRetries: aws.Int(3), -// }) +// })) // // // Create S3 service client with a specific Region. // svc := s3.New(sess, &aws.Config{ @@ -154,7 +154,8 @@ type Config struct { // the EC2Metadata overriding the timeout for default credentials chain. // // Example: - // sess, err := session.NewSession(aws.NewConfig().WithEC2MetadataDiableTimeoutOverride(true)) + // sess := session.Must(session.NewSession(aws.NewConfig() + // .WithEC2MetadataDiableTimeoutOverride(true))) // // svc := s3.New(sess) // @@ -174,7 +175,7 @@ type Config struct { // // Only supported with. // - // sess, err := session.NewSession() + // sess := session.Must(session.NewSession()) // // svc := s3.New(sess, &aws.Config{ // UseDualStack: aws.Bool(true), @@ -186,13 +187,19 @@ type Config struct { // request delays. This value should only be used for testing. To adjust // the delay of a request see the aws/client.DefaultRetryer and // aws/request.Retryer. + // + // SleepDelay will prevent any Context from being used for canceling retry + // delay of an API operation. It is recommended to not use SleepDelay at all + // and specify a Retryer instead. SleepDelay func(time.Duration) // DisableRestProtocolURICleaning will not clean the URL path when making rest protocol requests. // Will default to false. This would only be used for empty directory names in s3 requests. // // Example: - // sess, err := session.NewSession(&aws.Config{DisableRestProtocolURICleaning: aws.Bool(true)) + // sess := session.Must(session.NewSession(&aws.Config{ + // DisableRestProtocolURICleaning: aws.Bool(true), + // })) // // svc := s3.New(sess) // out, err := svc.GetObject(&s3.GetObjectInput { @@ -207,9 +214,9 @@ type Config struct { // // // Create Session with MaxRetry configuration to be shared by multiple // // service clients. -// sess, err := session.NewSession(aws.NewConfig(). +// sess := session.Must(session.NewSession(aws.NewConfig(). // WithMaxRetries(3), -// ) +// )) // // // Create S3 service client with a specific Region. // svc := s3.New(sess, aws.NewConfig(). diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context.go b/vendor/github.com/aws/aws-sdk-go/aws/context.go new file mode 100644 index 0000000..79f4268 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/context.go @@ -0,0 +1,71 @@ +package aws + +import ( + "time" +) + +// Context is an copy of the Go v1.7 stdlib's context.Context interface. +// It is represented as a SDK interface to enable you to use the "WithContext" +// API methods with Go v1.6 and a Context type such as golang.org/x/net/context. +// +// See https://golang.org/pkg/context on how to use contexts. +type Context interface { + // Deadline returns the time when work done on behalf of this context + // should be canceled. Deadline returns ok==false when no deadline is + // set. Successive calls to Deadline return the same results. + Deadline() (deadline time.Time, ok bool) + + // Done returns a channel that's closed when work done on behalf of this + // context should be canceled. Done may return nil if this context can + // never be canceled. Successive calls to Done return the same value. + Done() <-chan struct{} + + // Err returns a non-nil error value after Done is closed. Err returns + // Canceled if the context was canceled or DeadlineExceeded if the + // context's deadline passed. No other values for Err are defined. + // After Done is closed, successive calls to Err return the same value. + Err() error + + // Value returns the value associated with this context for key, or nil + // if no value is associated with key. Successive calls to Value with + // the same key returns the same result. + // + // Use context values only for request-scoped data that transits + // processes and API boundaries, not for passing optional parameters to + // functions. + Value(key interface{}) interface{} +} + +// BackgroundContext returns a context that will never be canceled, has no +// values, and no deadline. This context is used by the SDK to provide +// backwards compatibility with non-context API operations and functionality. +// +// Go 1.6 and before: +// This context function is equivalent to context.Background in the Go stdlib. +// +// Go 1.7 and later: +// The context returned will be the value returned by context.Background() +// +// See https://golang.org/pkg/context for more information on Contexts. +func BackgroundContext() Context { + return backgroundCtx +} + +// SleepWithContext will wait for the timer duration to expire, or the context +// is canceled. Which ever happens first. If the context is canceled the Context's +// error will be returned. +// +// Expects Context to always return a non-nil error if the Done channel is closed. +func SleepWithContext(ctx Context, dur time.Duration) error { + t := time.NewTimer(dur) + defer t.Stop() + + select { + case <-t.C: + break + case <-ctx.Done(): + return ctx.Err() + } + + return nil +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go b/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go new file mode 100644 index 0000000..e8cf93d --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go @@ -0,0 +1,41 @@ +// +build !go1.7 + +package aws + +import "time" + +// An emptyCtx is a copy of the the Go 1.7 context.emptyCtx type. This +// is copied to provide a 1.6 and 1.5 safe version of context that is compatible +// with Go 1.7's Context. +// +// An emptyCtx is never canceled, has no values, and has no deadline. It is not +// struct{}, since vars of this type must have distinct addresses. +type emptyCtx int + +func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { + return +} + +func (*emptyCtx) Done() <-chan struct{} { + return nil +} + +func (*emptyCtx) Err() error { + return nil +} + +func (*emptyCtx) Value(key interface{}) interface{} { + return nil +} + +func (e *emptyCtx) String() string { + switch e { + case backgroundCtx: + return "aws.BackgroundContext" + } + return "unknown empty Context" +} + +var ( + backgroundCtx = new(emptyCtx) +) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go b/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go new file mode 100644 index 0000000..064f75c --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go @@ -0,0 +1,9 @@ +// +build go1.7 + +package aws + +import "context" + +var ( + backgroundCtx = context.Background() +) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go index 8a7bafc..08a6665 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go @@ -134,6 +134,16 @@ var SendHandler = request.NamedHandler{Name: "core.SendHandler", Fn: func(r *req // Catch all other request errors. r.Error = awserr.New("RequestError", "send request failed", err) r.Retryable = aws.Bool(true) // network errors are retryable + + // Override the error with a context canceled error, if that was canceled. + ctx := r.Context() + select { + case <-ctx.Done(): + r.Error = awserr.New(request.CanceledErrorCode, + "request context canceled", ctx.Err()) + r.Retryable = aws.Bool(false) + default: + } } }} @@ -156,7 +166,16 @@ var AfterRetryHandler = request.NamedHandler{Name: "core.AfterRetryHandler", Fn: if r.WillRetry() { r.RetryDelay = r.RetryRules(r) - r.Config.SleepDelay(r.RetryDelay) + + if sleepFn := r.Config.SleepDelay; sleepFn != nil { + // Support SleepDelay for backwards compatibility and testing + sleepFn(r.RetryDelay) + } else if err := aws.SleepWithContext(r.Context(), r.RetryDelay); err != nil { + r.Error = awserr.New(request.CanceledErrorCode, + "request context canceled", err) + r.Retryable = aws.Bool(false) + return + } // when the expired token exception occurs the credentials // need to be expired locally so that the next request to diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go index 7b8ebf5..c29baf0 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go @@ -88,7 +88,7 @@ type Value struct { // The Provider should not need to implement its own mutexes, because // that will be managed by Credentials. type Provider interface { - // Refresh returns nil if it successfully retrieved the value. + // Retrieve returns nil if it successfully retrieved the value. // Error is returned if the value were not obtainable, or empty. Retrieve() (Value, error) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go index 30c847a..b840623 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go @@ -1,7 +1,81 @@ -// Package stscreds are credential Providers to retrieve STS AWS credentials. -// -// STS provides multiple ways to retrieve credentials which can be used when making -// future AWS service API operation calls. +/* +Package stscreds are credential Providers to retrieve STS AWS credentials. + +STS provides multiple ways to retrieve credentials which can be used when making +future AWS service API operation calls. + +The SDK will ensure that per instance of credentials.Credentials all requests +to refresh the credentials will be synchronized. But, the SDK is unable to +ensure synchronous usage of the AssumeRoleProvider if the value is shared +between multiple Credentials, Sessions or service clients. + +Assume Role + +To assume an IAM role using STS with the SDK you can create a new Credentials +with the SDKs's stscreds package. + + // Initial credentials loaded from SDK's default credential chain. Such as + // the environment, shared credentials (~/.aws/credentials), or EC2 Instance + // Role. These credentials will be used to to make the STS Assume Role API. + sess := session.Must(session.NewSession()) + + // Create the credentials from AssumeRoleProvider to assume the role + // referenced by the "myRoleARN" ARN. + creds := stscreds.NewCredentials(sess, "myRoleArn") + + // Create service client value configured for credentials + // from assumed role. + svc := s3.New(sess, &aws.Config{Credentials: creds}) + +Assume Role with static MFA Token + +To assume an IAM role with a MFA token you can either specify a MFA token code +directly or provide a function to prompt the user each time the credentials +need to refresh the role's credentials. Specifying the TokenCode should be used +for short lived operations that will not need to be refreshed, and when you do +not want to have direct control over the user provides their MFA token. + +With TokenCode the AssumeRoleProvider will be not be able to refresh the role's +credentials. + + // Create the credentials from AssumeRoleProvider to assume the role + // referenced by the "myRoleARN" ARN using the MFA token code provided. + creds := stscreds.NewCredentials(sess, "myRoleArn", func(p *stscreds.AssumeRoleProvider) { + p.SerialNumber = aws.String("myTokenSerialNumber") + p.TokenCode = aws.String("00000000") + }) + + // Create service client value configured for credentials + // from assumed role. + svc := s3.New(sess, &aws.Config{Credentials: creds}) + +Assume Role with MFA Token Provider + +To assume an IAM role with MFA for longer running tasks where the credentials +may need to be refreshed setting the TokenProvider field of AssumeRoleProvider +will allow the credential provider to prompt for new MFA token code when the +role's credentials need to be refreshed. + +The StdinTokenProvider function is available to prompt on stdin to retrieve +the MFA token code from the user. You can also implement custom prompts by +satisfing the TokenProvider function signature. + +Using StdinTokenProvider with multiple AssumeRoleProviders, or Credentials will +have undesirable results as the StdinTokenProvider will not be synchronized. A +single Credentials with an AssumeRoleProvider can be shared safely. + + // Create the credentials from AssumeRoleProvider to assume the role + // referenced by the "myRoleARN" ARN. Prompting for MFA token from stdin. + creds := stscreds.NewCredentials(sess, "myRoleArn", func(p *stscreds.AssumeRoleProvider) { + p.SerialNumber = aws.String("myTokenSerialNumber") + p.TokenProvider = stscreds.StdinTokenProvider + }) + + // Create service client value configured for credentials + // from assumed role. + svc := s3.New(sess, &aws.Config{Credentials: creds}) + +*/ package stscreds import ( @@ -9,11 +83,31 @@ import ( "time" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/service/sts" ) +// StdinTokenProvider will prompt on stdout and read from stdin for a string value. +// An error is returned if reading from stdin fails. +// +// Use this function go read MFA tokens from stdin. The function makes no attempt +// to make atomic prompts from stdin across multiple gorouties. +// +// Using StdinTokenProvider with multiple AssumeRoleProviders, or Credentials will +// have undesirable results as the StdinTokenProvider will not be synchronized. A +// single Credentials with an AssumeRoleProvider can be shared safely +// +// Will wait forever until something is provided on the stdin. +func StdinTokenProvider() (string, error) { + var v string + fmt.Printf("Assume Role MFA token code: ") + _, err := fmt.Scanln(&v) + + return v, err +} + // ProviderName provides a name of AssumeRole provider const ProviderName = "AssumeRoleProvider" @@ -27,8 +121,15 @@ type AssumeRoler interface { var DefaultDuration = time.Duration(15) * time.Minute // AssumeRoleProvider retrieves temporary credentials from the STS service, and -// keeps track of their expiration time. This provider must be used explicitly, -// as it is not included in the credentials chain. +// keeps track of their expiration time. +// +// This credential provider will be used by the SDKs default credential change +// when shared configuration is enabled, and the shared config or shared credentials +// file configure assume role. See Session docs for how to do this. +// +// AssumeRoleProvider does not provide any synchronization and it is not safe +// to share this value across multiple Credentials, Sessions, or service clients +// without also sharing the same Credentials instance. type AssumeRoleProvider struct { credentials.Expiry @@ -65,8 +166,23 @@ type AssumeRoleProvider struct { // assumed requires MFA (that is, if the policy includes a condition that tests // for MFA). If the role being assumed requires MFA and if the TokenCode value // is missing or expired, the AssumeRole call returns an "access denied" error. + // + // If SerialNumber is set and neither TokenCode nor TokenProvider are also + // set an error will be returned. TokenCode *string + // Async method of providing MFA token code for assuming an IAM role with MFA. + // The value returned by the function will be used as the TokenCode in the Retrieve + // call. See StdinTokenProvider for a provider that prompts and reads from stdin. + // + // This token provider will be called when ever the assumed role's + // credentials need to be refreshed when SerialNumber is also set and + // TokenCode is not set. + // + // If both TokenCode and TokenProvider is set, TokenProvider will be used and + // TokenCode is ignored. + TokenProvider func() (string, error) + // ExpiryWindow will allow the credentials to trigger refreshing prior to // the credentials actually expiring. This is beneficial so race conditions // with expiring credentials do not cause request to fail unexpectedly @@ -85,6 +201,10 @@ type AssumeRoleProvider struct { // // Takes a Config provider to create the STS client. The ConfigProvider is // satisfied by the session.Session type. +// +// It is safe to share the returned Credentials with multiple Sessions and +// service clients. All access to the credentials and refreshing them +// will be synchronized. func NewCredentials(c client.ConfigProvider, roleARN string, options ...func(*AssumeRoleProvider)) *credentials.Credentials { p := &AssumeRoleProvider{ Client: sts.New(c), @@ -103,7 +223,11 @@ func NewCredentials(c client.ConfigProvider, roleARN string, options ...func(*As // AssumeRoleProvider. The credentials will expire every 15 minutes and the // role will be named after a nanosecond timestamp of this operation. // -// Takes an AssumeRoler which can be satisfiede by the STS client. +// Takes an AssumeRoler which can be satisfied by the STS client. +// +// It is safe to share the returned Credentials with multiple Sessions and +// service clients. All access to the credentials and refreshing them +// will be synchronized. func NewCredentialsWithClient(svc AssumeRoler, roleARN string, options ...func(*AssumeRoleProvider)) *credentials.Credentials { p := &AssumeRoleProvider{ Client: svc, @@ -139,12 +263,25 @@ func (p *AssumeRoleProvider) Retrieve() (credentials.Value, error) { if p.Policy != nil { input.Policy = p.Policy } - if p.SerialNumber != nil && p.TokenCode != nil { - input.SerialNumber = p.SerialNumber - input.TokenCode = p.TokenCode + if p.SerialNumber != nil { + if p.TokenCode != nil { + input.SerialNumber = p.SerialNumber + input.TokenCode = p.TokenCode + } else if p.TokenProvider != nil { + input.SerialNumber = p.SerialNumber + code, err := p.TokenProvider() + if err != nil { + return credentials.Value{ProviderName: ProviderName}, err + } + input.TokenCode = aws.String(code) + } else { + return credentials.Value{ProviderName: ProviderName}, + awserr.New("AssumeRoleTokenNotAvailable", + "assume role with MFA enabled, but neither TokenCode nor TokenProvider are set", nil) + } } - roleOutput, err := p.Client.AssumeRole(input) + roleOutput, err := p.Client.AssumeRole(input) if err != nil { return credentials.Value{ProviderName: ProviderName}, err } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go index 0ef5504..110ca83 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go @@ -56,7 +56,6 @@ func Config() *aws.Config { WithMaxRetries(aws.UseServiceDefaultRetries). WithLogger(aws.NewDefaultLogger()). WithLogLevel(aws.LogOff). - WithSleepDelay(time.Sleep). WithEndpointResolver(endpoints.DefaultResolver()) } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go index 987d928..4adca3a 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by aws/endpoints/v3model_codegen.go. DO NOT EDIT. package endpoints @@ -46,10 +46,11 @@ const ( AcmServiceID = "acm" // Acm. ApigatewayServiceID = "apigateway" // Apigateway. ApplicationAutoscalingServiceID = "application-autoscaling" // ApplicationAutoscaling. - AppstreamServiceID = "appstream" // Appstream. Appstream2ServiceID = "appstream2" // Appstream2. AutoscalingServiceID = "autoscaling" // Autoscaling. + BatchServiceID = "batch" // Batch. BudgetsServiceID = "budgets" // Budgets. + ClouddirectoryServiceID = "clouddirectory" // Clouddirectory. CloudformationServiceID = "cloudformation" // Cloudformation. CloudfrontServiceID = "cloudfront" // Cloudfront. CloudhsmServiceID = "cloudhsm" // Cloudhsm. @@ -63,6 +64,7 @@ const ( CognitoIdpServiceID = "cognito-idp" // CognitoIdp. CognitoSyncServiceID = "cognito-sync" // CognitoSync. ConfigServiceID = "config" // Config. + CurServiceID = "cur" // Cur. DatapipelineServiceID = "datapipeline" // Datapipeline. DevicefarmServiceID = "devicefarm" // Devicefarm. DirectconnectServiceID = "directconnect" // Directconnect. @@ -102,8 +104,10 @@ const ( MeteringMarketplaceServiceID = "metering.marketplace" // MeteringMarketplace. MobileanalyticsServiceID = "mobileanalytics" // Mobileanalytics. MonitoringServiceID = "monitoring" // Monitoring. + MturkRequesterServiceID = "mturk-requester" // MturkRequester. OpsworksServiceID = "opsworks" // Opsworks. OpsworksCmServiceID = "opsworks-cm" // OpsworksCm. + OrganizationsServiceID = "organizations" // Organizations. PinpointServiceID = "pinpoint" // Pinpoint. PollyServiceID = "polly" // Polly. RdsServiceID = "rds" // Rds. @@ -111,6 +115,7 @@ const ( RekognitionServiceID = "rekognition" // Rekognition. Route53ServiceID = "route53" // Route53. Route53domainsServiceID = "route53domains" // Route53domains. + RuntimeLexServiceID = "runtime.lex" // RuntimeLex. S3ServiceID = "s3" // S3. SdbServiceID = "sdb" // Sdb. ServicecatalogServiceID = "servicecatalog" // Servicecatalog. @@ -126,8 +131,10 @@ const ( StsServiceID = "sts" // Sts. SupportServiceID = "support" // Support. SwfServiceID = "swf" // Swf. + TaggingServiceID = "tagging" // Tagging. WafServiceID = "waf" // Waf. WafRegionalServiceID = "waf-regional" // WafRegional. + WorkdocsServiceID = "workdocs" // Workdocs. WorkspacesServiceID = "workspaces" // Workspaces. XrayServiceID = "xray" // Xray. ) @@ -243,10 +250,12 @@ var awsPartition = partition{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-1": endpoint{}, @@ -278,13 +287,6 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "appstream": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "us-east-1": endpoint{}, - }, - }, "appstream2": service{ Defaults: endpoint{ Protocols: []string{"https"}, @@ -320,6 +322,12 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "batch": service{ + + Endpoints: endpoints{ + "us-east-1": endpoint{}, + }, + }, "budgets": service{ PartitionEndpoint: "aws-global", IsRegionalized: boxedFalse, @@ -333,6 +341,17 @@ var awsPartition = partition{ }, }, }, + "clouddirectory": service{ + + Endpoints: endpoints{ + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, + }, + }, "cloudformation": service{ Endpoints: endpoints{ @@ -418,9 +437,14 @@ var awsPartition = partition{ "codebuild": service{ Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, + "ap-northeast-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, }, }, "codecommit": service{ @@ -473,6 +497,7 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-2": endpoint{}, @@ -486,6 +511,7 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-2": endpoint{}, @@ -499,6 +525,7 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-2": endpoint{}, @@ -523,6 +550,12 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "cur": service{ + + Endpoints: endpoints{ + "us-east-1": endpoint{}, + }, + }, "datapipeline": service{ Endpoints: endpoints{ @@ -728,10 +761,11 @@ var awsPartition = partition{ "elasticfilesystem": service{ Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, }, }, "elasticloadbalancing": service{ @@ -827,8 +861,10 @@ var awsPartition = partition{ "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -936,6 +972,7 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-2": endpoint{}, @@ -992,10 +1029,12 @@ var awsPartition = partition{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-1": endpoint{}, @@ -1041,10 +1080,26 @@ var awsPartition = partition{ }, }, "metering.marketplace": service{ - + Defaults: endpoint{ + CredentialScope: credentialScope{ + Service: "aws-marketplace", + }, + }, Endpoints: endpoints{ - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "mobileanalytics": service{ @@ -1074,6 +1129,16 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "mturk-requester": service{ + IsRegionalized: boxedFalse, + + Endpoints: endpoints{ + "sandbox": endpoint{ + Hostname: "mturk-requester-sandbox.us-east-1.amazonaws.com", + }, + "us-east-1": endpoint{}, + }, + }, "opsworks": service{ Endpoints: endpoints{ @@ -1100,6 +1165,19 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "organizations": service{ + PartitionEndpoint: "aws-global", + IsRegionalized: boxedFalse, + + Endpoints: endpoints{ + "aws-global": endpoint{ + Hostname: "organizations.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + }, + }, "pinpoint": service{ Defaults: endpoint{ CredentialScope: credentialScope{ @@ -1186,6 +1264,16 @@ var awsPartition = partition{ "us-east-1": endpoint{}, }, }, + "runtime.lex": service{ + Defaults: endpoint{ + CredentialScope: credentialScope{ + Service: "lex", + }, + }, + Endpoints: endpoints{ + "us-east-1": endpoint{}, + }, + }, "s3": service{ PartitionEndpoint: "us-east-1", IsRegionalized: boxedTrue, @@ -1300,7 +1388,6 @@ var awsPartition = partition{ Endpoints: endpoints{ "ap-south-1": endpoint{}, "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, @@ -1375,6 +1462,7 @@ var awsPartition = partition{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, + "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, @@ -1486,6 +1574,25 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "tagging": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, "waf": service{ PartitionEndpoint: "aws-global", IsRegionalized: boxedFalse, @@ -1508,6 +1615,17 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "workdocs": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, "workspaces": service{ Endpoints: endpoints{ @@ -1586,6 +1704,12 @@ var awscnPartition = partition{ "cn-north-1": endpoint{}, }, }, + "codedeploy": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + }, + }, "config": service{ Endpoints: endpoints{ @@ -1763,6 +1887,12 @@ var awscnPartition = partition{ }, "swf": service{ + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + }, + }, + "tagging": service{ + Endpoints: endpoints{ "cn-north-1": endpoint{}, }, @@ -1900,6 +2030,12 @@ var awsusgovPartition = partition{ }, }, }, + "kinesis": service{ + + Endpoints: endpoints{ + "us-gov-west-1": endpoint{}, + }, + }, "kms": service{ Endpoints: endpoints{ diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go index 3adec13..37e19ab 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go @@ -27,6 +27,25 @@ type Options struct { // error will be returned. This option will prevent returning endpoints // that look valid, but may not resolve to any real endpoint. StrictMatching bool + + // Enables resolving a service endpoint based on the region provided if the + // service does not exist. The service endpoint ID will be used as the service + // domain name prefix. By default the endpoint resolver requires the service + // to be known when resolving endpoints. + // + // If resolving an endpoint on the partition list the provided region will + // be used to determine which partition's domain name pattern to the service + // endpoint ID with. If both the service and region are unkonwn and resolving + // the endpoint on partition list an UnknownEndpointError error will be returned. + // + // If resolving and endpoint on a partition specific resolver that partition's + // domain name pattern will be used with the service endpoint ID. If both + // region and service do not exist when resolving an endpoint on a specific + // partition the partition's domain pattern will be used to combine the + // endpoint and region together. + // + // This option is ignored if StrictMatching is enabled. + ResolveUnknownService bool } // Set combines all of the option functions together. @@ -54,6 +73,12 @@ func StrictMatchingOption(o *Options) { o.StrictMatching = true } +// ResolveUnknownServiceOption sets the ResolveUnknownService option. Can be used +// as a functional option when resolving endpoints. +func ResolveUnknownServiceOption(o *Options) { + o.ResolveUnknownService = true +} + // A Resolver provides the interface for functionality to resolve endpoints. // The build in Partition and DefaultResolver return value satisfy this interface. type Resolver interface { @@ -114,15 +139,18 @@ func (p *Partition) ID() string { return p.id } // // If the service cannot be found in the metadata the UnknownServiceError // error will be returned. This validation will occur regardless if -// StrictMatching is enabled. +// StrictMatching is enabled. To enable resolving unknown services set the +// "ResolveUnknownService" option to true. When StrictMatching is disabled +// this option allows the partition resolver to resolve a endpoint based on +// the service endpoint ID provided. // // When resolving endpoints you can choose to enable StrictMatching. This will // require the provided service and region to be known by the partition. // If the endpoint cannot be strictly resolved an error will be returned. This // mode is useful to ensure the endpoint resolved is valid. Without -// StrictMatching enabled the enpoint returned my look valid but may not work. +// StrictMatching enabled the endpoint returned my look valid but may not work. // StrictMatching requires the SDK to be updated if you want to take advantage -// of new regions and services expantions. +// of new regions and services expansions. // // Errors that can be returned. // * UnknownServiceError diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go index 6522ce9..13d968a 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go @@ -79,7 +79,9 @@ func (p partition) EndpointFor(service, region string, opts ...func(*Options)) ( opt.Set(opts...) s, hasService := p.Services[service] - if !hasService { + if !(hasService || opt.ResolveUnknownService) { + // Only return error if the resolver will not fallback to creating + // endpoint based on service endpoint ID passed in. return resolved, NewUnknownServiceError(p.ID, service, serviceList(p.Services)) } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go index 1e7369d..fc7eada 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go @@ -158,7 +158,7 @@ var funcMap = template.FuncMap{ const v3Tmpl = ` {{ define "defaults" -}} -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by aws/endpoints/v3model_codegen.go. DO NOT EDIT. package endpoints diff --git a/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go b/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go new file mode 100644 index 0000000..a94f041 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go @@ -0,0 +1,11 @@ +package aws + +// JSONValue is a representation of a grab bag type that will be marshaled +// into a json string. This type can be used just like any other map. +// +// Example: +// values := JSONValue{ +// "Foo": "Bar", +// } +// values["Baz"] = "Qux" +type JSONValue map[string]interface{} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go b/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go index 5279c19..6c14336 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go @@ -18,6 +18,7 @@ type Handlers struct { UnmarshalError HandlerList Retry HandlerList AfterRetry HandlerList + Complete HandlerList } // Copy returns of this handler's lists. @@ -33,6 +34,7 @@ func (h *Handlers) Copy() Handlers { UnmarshalMeta: h.UnmarshalMeta.copy(), Retry: h.Retry.copy(), AfterRetry: h.AfterRetry.copy(), + Complete: h.Complete.copy(), } } @@ -48,6 +50,7 @@ func (h *Handlers) Clear() { h.ValidateResponse.Clear() h.Retry.Clear() h.AfterRetry.Clear() + h.Complete.Clear() } // A HandlerListRunItem represents an entry in the HandlerList which @@ -85,13 +88,17 @@ func (l *HandlerList) copy() HandlerList { n := HandlerList{ AfterEachFn: l.AfterEachFn, } - n.list = append([]NamedHandler{}, l.list...) + if len(l.list) == 0 { + return n + } + + n.list = append(make([]NamedHandler, 0, len(l.list)), l.list...) return n } // Clear clears the handler list. func (l *HandlerList) Clear() { - l.list = []NamedHandler{} + l.list = l.list[0:0] } // Len returns the number of handlers in the list. @@ -101,33 +108,54 @@ func (l *HandlerList) Len() int { // PushBack pushes handler f to the back of the handler list. func (l *HandlerList) PushBack(f func(*Request)) { - l.list = append(l.list, NamedHandler{"__anonymous", f}) -} - -// PushFront pushes handler f to the front of the handler list. -func (l *HandlerList) PushFront(f func(*Request)) { - l.list = append([]NamedHandler{{"__anonymous", f}}, l.list...) + l.PushBackNamed(NamedHandler{"__anonymous", f}) } // PushBackNamed pushes named handler f to the back of the handler list. func (l *HandlerList) PushBackNamed(n NamedHandler) { + if cap(l.list) == 0 { + l.list = make([]NamedHandler, 0, 5) + } l.list = append(l.list, n) } +// PushFront pushes handler f to the front of the handler list. +func (l *HandlerList) PushFront(f func(*Request)) { + l.PushFrontNamed(NamedHandler{"__anonymous", f}) +} + // PushFrontNamed pushes named handler f to the front of the handler list. func (l *HandlerList) PushFrontNamed(n NamedHandler) { - l.list = append([]NamedHandler{n}, l.list...) + if cap(l.list) == len(l.list) { + // Allocating new list required + l.list = append([]NamedHandler{n}, l.list...) + } else { + // Enough room to prepend into list. + l.list = append(l.list, NamedHandler{}) + copy(l.list[1:], l.list) + l.list[0] = n + } } // Remove removes a NamedHandler n func (l *HandlerList) Remove(n NamedHandler) { - newlist := []NamedHandler{} - for _, m := range l.list { - if m.Name != n.Name { - newlist = append(newlist, m) + l.RemoveByName(n.Name) +} + +// RemoveByName removes a NamedHandler by name. +func (l *HandlerList) RemoveByName(name string) { + for i := 0; i < len(l.list); i++ { + m := l.list[i] + if m.Name == name { + // Shift array preventing creating new arrays + copy(l.list[i:], l.list[i+1:]) + l.list[len(l.list)-1] = NamedHandler{} + l.list = l.list[:len(l.list)-1] + + // decrement list so next check to length is correct + i-- } } - l.list = newlist } // Run executes all handlers in the list with a given request object. @@ -163,6 +191,16 @@ func HandlerListStopOnError(item HandlerListRunItem) bool { return item.Request.Error == nil } +// WithAppendUserAgent will add a string to the user agent prefixed with a +// single white space. +func WithAppendUserAgent(s string) Option { + return func(r *Request) { + r.Handlers.Build.PushBack(func(r2 *Request) { + AddToUserAgent(r, s) + }) + } +} + // MakeAddToUserAgentHandler will add the name/version pair to the User-Agent request // header. If the extra parameters are provided they will be added as metadata to the // name/version pair resulting in the following format. diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request.go index 77312bb..1f131df 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/request.go @@ -16,6 +16,21 @@ import ( "github.com/aws/aws-sdk-go/aws/client/metadata" ) +const ( + // ErrCodeSerialization is the serialization error code that is received + // during protocol unmarshaling. + ErrCodeSerialization = "SerializationError" + + // ErrCodeResponseTimeout is the connection timeout error that is recieved + // during body reads. + ErrCodeResponseTimeout = "ResponseTimeout" + + // CanceledErrorCode is the error code that will be returned by an + // API request that was canceled. Requests given a aws.Context may + // return this error when canceled. + CanceledErrorCode = "RequestCanceled" +) + // A Request is the service request to be made. type Request struct { Config aws.Config @@ -41,12 +56,14 @@ type Request struct { SignedHeaderVals http.Header LastSignedAt time.Time + context aws.Context + built bool - // Need to persist an intermideant body betweend the input Body and HTTP + // Need to persist an intermediate body between the input Body and HTTP // request body because the HTTP Client's transport can maintain a reference // to the HTTP request's body after the client has returned. This value is - // safe to use concurrently and rewraps the input Body for each HTTP request. + // safe to use concurrently and wrap the input Body for each HTTP request. safeBody *offsetReader } @@ -60,14 +77,6 @@ type Operation struct { BeforePresignFn func(r *Request) error } -// Paginator keeps track of pagination configuration for an API operation. -type Paginator struct { - InputTokens []string - OutputTokens []string - LimitToken string - TruncationToken string -} - // New returns a new Request pointer for the service API // operation and parameters. // @@ -111,6 +120,94 @@ func New(cfg aws.Config, clientInfo metadata.ClientInfo, handlers Handlers, return r } +// A Option is a functional option that can augment or modify a request when +// using a WithContext API operation method. +type Option func(*Request) + +// WithGetResponseHeader builds a request Option which will retrieve a single +// header value from the HTTP Response. If there are multiple values for the +// header key use WithGetResponseHeaders instead to access the http.Header +// map directly. The passed in val pointer must be non-nil. +// +// This Option can be used multiple times with a single API operation. +// +// var id2, versionID string +// svc.PutObjectWithContext(ctx, params, +// request.WithGetResponseHeader("x-amz-id-2", &id2), +// request.WithGetResponseHeader("x-amz-version-id", &versionID), +// ) +func WithGetResponseHeader(key string, val *string) Option { + return func(r *Request) { + r.Handlers.Complete.PushBack(func(req *Request) { + *val = req.HTTPResponse.Header.Get(key) + }) + } +} + +// WithGetResponseHeaders builds a request Option which will retrieve the +// headers from the HTTP response and assign them to the passed in headers +// variable. The passed in headers pointer must be non-nil. +// +// var headers http.Header +// svc.PutObjectWithContext(ctx, params, request.WithGetResponseHeaders(&headers)) +func WithGetResponseHeaders(headers *http.Header) Option { + return func(r *Request) { + r.Handlers.Complete.PushBack(func(req *Request) { + *headers = req.HTTPResponse.Header + }) + } +} + +// WithLogLevel is a request option that will set the request to use a specific +// log level when the request is made. +// +// svc.PutObjectWithContext(ctx, params, request.WithLogLevel(aws.LogDebugWithHTTPBody) +func WithLogLevel(l aws.LogLevelType) Option { + return func(r *Request) { + r.Config.LogLevel = aws.LogLevel(l) + } +} + +// ApplyOptions will apply each option to the request calling them in the order +// the were provided. +func (r *Request) ApplyOptions(opts ...Option) { + for _, opt := range opts { + opt(r) + } +} + +// Context will always returns a non-nil context. If Request does not have a +// context aws.BackgroundContext will be returned. +func (r *Request) Context() aws.Context { + if r.context != nil { + return r.context + } + return aws.BackgroundContext() +} + +// SetContext adds a Context to the current request that can be used to cancel +// a in-flight request. The Context value must not be nil, or this method will +// panic. +// +// Unlike http.Request.WithContext, SetContext does not return a copy of the +// Request. It is not safe to use use a single Request value for multiple +// requests. A new Request should be created for each API operation request. +// +// Go 1.6 and below: +// The http.Request's Cancel field will be set to the Done() value of +// the context. This will overwrite the Cancel field's value. +// +// Go 1.7 and above: +// The http.Request.WithContext will be used to set the context on the underlying +// http.Request. This will create a shallow copy of the http.Request. The SDK +// may create sub contexts in the future for nested requests such as retries. +func (r *Request) SetContext(ctx aws.Context) { + if ctx == nil { + panic("context cannot be nil") + } + setRequestContext(r, ctx) +} + // WillRetry returns if the request's can be retried. func (r *Request) WillRetry() bool { return r.Error != nil && aws.BoolValue(r.Retryable) && r.RetryCount < r.MaxRetries() @@ -262,7 +359,7 @@ func (r *Request) ResetBody() { // Related golang/go#18257 l, err := computeBodyLength(r.Body) if err != nil { - r.Error = awserr.New("SerializationError", "failed to compute request body size", err) + r.Error = awserr.New(ErrCodeSerialization, "failed to compute request body size", err) return } @@ -344,6 +441,12 @@ func (r *Request) GetBody() io.ReadSeeker { // // Send will not close the request.Request's body. func (r *Request) Send() error { + defer func() { + // Regardless of success or failure of the request trigger the Complete + // request handlers. + r.Handlers.Complete.Run(r) + }() + for { if aws.BoolValue(r.Retryable) { if r.Config.LogLevel.Matches(aws.LogDebugWithRequestRetries) { @@ -446,6 +549,9 @@ func shouldRetryCancel(r *Request) bool { timeoutErr := false errStr := r.Error.Error() if ok { + if awsErr.Code() == CanceledErrorCode { + return false + } err := awsErr.OrigErr() netErr, netOK := err.(net.Error) timeoutErr = netOK && netErr.Temporary() diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go new file mode 100644 index 0000000..a7365cd --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go @@ -0,0 +1,14 @@ +// +build go1.7 + +package request + +import "github.com/aws/aws-sdk-go/aws" + +// setContext updates the Request to use the passed in context for cancellation. +// Context will also be used for request retry delay. +// +// Creates shallow copy of the http.Request with the WithContext method. +func setRequestContext(r *Request, ctx aws.Context) { + r.context = ctx + r.HTTPRequest = r.HTTPRequest.WithContext(ctx) +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go new file mode 100644 index 0000000..307fa07 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go @@ -0,0 +1,14 @@ +// +build !go1.7 + +package request + +import "github.com/aws/aws-sdk-go/aws" + +// setContext updates the Request to use the passed in context for cancellation. +// Context will also be used for request retry delay. +// +// Creates shallow copy of the http.Request with the WithContext method. +func setRequestContext(r *Request, ctx aws.Context) { + r.context = ctx + r.HTTPRequest.Cancel = ctx.Done() +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go index 2939ec4..59de673 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go @@ -2,29 +2,125 @@ package request import ( "reflect" + "sync/atomic" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" ) -//type Paginater interface { -// HasNextPage() bool -// NextPage() *Request -// EachPage(fn func(data interface{}, isLastPage bool) (shouldContinue bool)) error -//} +// A Pagination provides paginating of SDK API operations which are paginatable. +// Generally you should not use this type directly, but use the "Pages" API +// operations method to automatically perform pagination for you. Such as, +// "S3.ListObjectsPages", and "S3.ListObjectsPagesWithContext" methods. +// +// Pagination differs from a Paginator type in that pagination is the type that +// does the pagination between API operations, and Paginator defines the +// configuration that will be used per page request. +// +// cont := true +// for p.Next() && cont { +// data := p.Page().(*s3.ListObjectsOutput) +// // process the page's data +// } +// return p.Err() +// +// See service client API operation Pages methods for examples how the SDK will +// use the Pagination type. +type Pagination struct { + // Function to return a Request value for each pagination request. + // Any configuration or handlers that need to be applied to the request + // prior to getting the next page should be done here before the request + // returned. + // + // NewRequest should always be built from the same API operations. It is + // undefined if different API operations are returned on subsequent calls. + NewRequest func() (*Request, error) -// HasNextPage returns true if this request has more pages of data available. -func (r *Request) HasNextPage() bool { - return len(r.nextPageTokens()) > 0 + started bool + nextTokens []interface{} + + err error + curPage interface{} } -// nextPageTokens returns the tokens to use when asking for the next page of -// data. +// HasNextPage will return true if Pagination is able to determine that the API +// operation has additional pages. False will be returned if there are no more +// pages remaining. +// +// Will always return true if Next has not been called yet. +func (p *Pagination) HasNextPage() bool { + return !(p.started && len(p.nextTokens) == 0) +} + +// Err returns the error Pagination encountered when retrieving the next page. +func (p *Pagination) Err() error { + return p.err +} + +// Page returns the current page. Page should only be called after a successful +// call to Next. It is undefined what Page will return if Page is called after +// Next returns false. +func (p *Pagination) Page() interface{} { + return p.curPage +} + +// Next will attempt to retrieve the next page for the API operation. When a page +// is retrieved true will be returned. If the page cannot be retrieved, or there +// are no more pages false will be returned. +// +// Use the Page method to retrieve the current page data. The data will need +// to be cast to the API operation's output type. +// +// Use the Err method to determine if an error occurred if Page returns false. +func (p *Pagination) Next() bool { + if !p.HasNextPage() { + return false + } + + req, err := p.NewRequest() + if err != nil { + p.err = err + return false + } + + if p.started { + for i, intok := range req.Operation.InputTokens { + awsutil.SetValueAtPath(req.Params, intok, p.nextTokens[i]) + } + } + p.started = true + + err = req.Send() + if err != nil { + p.err = err + return false + } + + p.nextTokens = req.nextPageTokens() + p.curPage = req.Data + + return true +} + +// A Paginator is the configuration data that defines how an API operation +// should be paginated. This type is used by the API service models to define +// the generated pagination config for service APIs. +// +// The Pagination type is what provides iterating between pages of an API. It +// is only used to store the token metadata the SDK should use for performing +// pagination. +type Paginator struct { + InputTokens []string + OutputTokens []string + LimitToken string + TruncationToken string +} + +// nextPageTokens returns the tokens to use when asking for the next page of data. func (r *Request) nextPageTokens() []interface{} { if r.Operation.Paginator == nil { return nil } - if r.Operation.TruncationToken != "" { tr, _ := awsutil.ValuesAtPath(r.Data, r.Operation.TruncationToken) if len(tr) == 0 { @@ -61,9 +157,40 @@ func (r *Request) nextPageTokens() []interface{} { return tokens } +// Ensure a deprecated item is only logged once instead of each time its used. +func logDeprecatedf(logger aws.Logger, flag *int32, msg string) { + if logger == nil { + return + } + if atomic.CompareAndSwapInt32(flag, 0, 1) { + logger.Log(msg) + } +} + +var ( + logDeprecatedHasNextPage int32 + logDeprecatedNextPage int32 + logDeprecatedEachPage int32 +) + +// HasNextPage returns true if this request has more pages of data available. +// +// Deprecated Use Pagination type for configurable pagination of API operations +func (r *Request) HasNextPage() bool { + logDeprecatedf(r.Config.Logger, &logDeprecatedHasNextPage, + "Request.HasNextPage deprecated. Use Pagination type for configurable pagination of API operations") + + return len(r.nextPageTokens()) > 0 +} + // NextPage returns a new Request that can be executed to return the next // page of result data. Call .Send() on this request to execute it. +// +// Deprecated Use Pagination type for configurable pagination of API operations func (r *Request) NextPage() *Request { + logDeprecatedf(r.Config.Logger, &logDeprecatedNextPage, + "Request.NextPage deprecated. Use Pagination type for configurable pagination of API operations") + tokens := r.nextPageTokens() if len(tokens) == 0 { return nil @@ -90,7 +217,12 @@ func (r *Request) NextPage() *Request { // as the structure "T". The lastPage value represents whether the page is // the last page of data or not. The return value of this function should // return true to keep iterating or false to stop. +// +// Deprecated Use Pagination type for configurable pagination of API operations func (r *Request) EachPage(fn func(data interface{}, isLastPage bool) (shouldContinue bool)) error { + logDeprecatedf(r.Config.Logger, &logDeprecatedEachPage, + "Request.EachPage deprecated. Use Pagination type for configurable pagination of API operations") + for page := r; page != nil; page = page.NextPage() { if err := page.Send(); err != nil { return err diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go b/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go index ebd60cc..632cd70 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go @@ -1,6 +1,9 @@ package request import ( + "net" + "os" + "syscall" "time" "github.com/aws/aws-sdk-go/aws" @@ -26,8 +29,10 @@ func WithRetryer(cfg *aws.Config, retryer Retryer) *aws.Config { // retryableCodes is a collection of service response codes which are retry-able // without any further action. var retryableCodes = map[string]struct{}{ - "RequestError": {}, - "RequestTimeout": {}, + "RequestError": {}, + "RequestTimeout": {}, + ErrCodeResponseTimeout: {}, + "RequestTimeoutException": {}, // Glacier's flavor of RequestTimeout } var throttleCodes = map[string]struct{}{ @@ -68,12 +73,32 @@ func isCodeExpiredCreds(code string) bool { return ok } +func isSerializationErrorRetryable(err error) bool { + if err == nil { + return false + } + + if aerr, ok := err.(awserr.Error); ok { + return isCodeRetryable(aerr.Code()) + } + + if opErr, ok := err.(*net.OpError); ok { + if sysErr, ok := opErr.Err.(*os.SyscallError); ok { + return sysErr.Err == syscall.ECONNRESET + } + } + + return false +} + // IsErrorRetryable returns whether the error is retryable, based on its Code. // Returns false if the request has no Error set. func (r *Request) IsErrorRetryable() bool { if r.Error != nil { - if err, ok := r.Error.(awserr.Error); ok { + if err, ok := r.Error.(awserr.Error); ok && err.Code() != ErrCodeSerialization { return isCodeRetryable(err.Code()) + } else if ok { + return isSerializationErrorRetryable(err.OrigErr()) } } return false diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go b/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go new file mode 100644 index 0000000..09a44eb --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go @@ -0,0 +1,94 @@ +package request + +import ( + "io" + "time" + + "github.com/aws/aws-sdk-go/aws/awserr" +) + +var timeoutErr = awserr.New( + ErrCodeResponseTimeout, + "read on body has reached the timeout limit", + nil, +) + +type readResult struct { + n int + err error +} + +// timeoutReadCloser will handle body reads that take too long. +// We will return a ErrReadTimeout error if a timeout occurs. +type timeoutReadCloser struct { + reader io.ReadCloser + duration time.Duration +} + +// Read will spin off a goroutine to call the reader's Read method. We will +// select on the timer's channel or the read's channel. Whoever completes first +// will be returned. +func (r *timeoutReadCloser) Read(b []byte) (int, error) { + timer := time.NewTimer(r.duration) + c := make(chan readResult, 1) + + go func() { + n, err := r.reader.Read(b) + timer.Stop() + c <- readResult{n: n, err: err} + }() + + select { + case data := <-c: + return data.n, data.err + case <-timer.C: + return 0, timeoutErr + } +} + +func (r *timeoutReadCloser) Close() error { + return r.reader.Close() +} + +const ( + // HandlerResponseTimeout is what we use to signify the name of the + // response timeout handler. + HandlerResponseTimeout = "ResponseTimeoutHandler" +) + +// adaptToResponseTimeoutError is a handler that will replace any top level error +// to a ErrCodeResponseTimeout, if its child is that. +func adaptToResponseTimeoutError(req *Request) { + if err, ok := req.Error.(awserr.Error); ok { + aerr, ok := err.OrigErr().(awserr.Error) + if ok && aerr.Code() == ErrCodeResponseTimeout { + req.Error = aerr + } + } +} + +// WithResponseReadTimeout is a request option that will wrap the body in a timeout read closer. +// This will allow for per read timeouts. If a timeout occurred, we will return the +// ErrCodeResponseTimeout. +// +// svc.PutObjectWithContext(ctx, params, request.WithTimeoutReadCloser(30 * time.Second) +func WithResponseReadTimeout(duration time.Duration) Option { + return func(r *Request) { + + var timeoutHandler = NamedHandler{ + HandlerResponseTimeout, + func(req *Request) { + req.HTTPResponse.Body = &timeoutReadCloser{ + reader: req.HTTPResponse.Body, + duration: duration, + } + }} + + // remove the handler so we are not stomping over any new durations. + r.Handlers.Send.RemoveByName(HandlerResponseTimeout) + r.Handlers.Send.PushBackNamed(timeoutHandler) + + r.Handlers.Unmarshal.PushBack(adaptToResponseTimeoutError) + r.Handlers.UnmarshalError.PushBack(adaptToResponseTimeoutError) + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go b/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go new file mode 100644 index 0000000..354c381 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go @@ -0,0 +1,293 @@ +package request + +import ( + "fmt" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/awsutil" +) + +// WaiterResourceNotReadyErrorCode is the error code returned by a waiter when +// the waiter's max attempts have been exhausted. +const WaiterResourceNotReadyErrorCode = "ResourceNotReady" + +// A WaiterOption is a function that will update the Waiter value's fields to +// configure the waiter. +type WaiterOption func(*Waiter) + +// WithWaiterMaxAttempts returns the maximum number of times the waiter should +// attempt to check the resource for the target state. +func WithWaiterMaxAttempts(max int) WaiterOption { + return func(w *Waiter) { + w.MaxAttempts = max + } +} + +// WaiterDelay will return a delay the waiter should pause between attempts to +// check the resource state. The passed in attempt is the number of times the +// Waiter has checked the resource state. +// +// Attempt is the number of attempts the Waiter has made checking the resource +// state. +type WaiterDelay func(attempt int) time.Duration + +// ConstantWaiterDelay returns a WaiterDelay that will always return a constant +// delay the waiter should use between attempts. It ignores the number of +// attempts made. +func ConstantWaiterDelay(delay time.Duration) WaiterDelay { + return func(attempt int) time.Duration { + return delay + } +} + +// WithWaiterDelay will set the Waiter to use the WaiterDelay passed in. +func WithWaiterDelay(delayer WaiterDelay) WaiterOption { + return func(w *Waiter) { + w.Delay = delayer + } +} + +// WithWaiterLogger returns a waiter option to set the logger a waiter +// should use to log warnings and errors to. +func WithWaiterLogger(logger aws.Logger) WaiterOption { + return func(w *Waiter) { + w.Logger = logger + } +} + +// WithWaiterRequestOptions returns a waiter option setting the request +// options for each request the waiter makes. Appends to waiter's request +// options already set. +func WithWaiterRequestOptions(opts ...Option) WaiterOption { + return func(w *Waiter) { + w.RequestOptions = append(w.RequestOptions, opts...) + } +} + +// A Waiter provides the functionality to performing blocking call which will +// wait for an resource state to be satisfied a service. +// +// This type should not be used directly. The API operations provided in the +// service packages prefixed with "WaitUntil" should be used instead. +type Waiter struct { + Name string + Acceptors []WaiterAcceptor + Logger aws.Logger + + MaxAttempts int + Delay WaiterDelay + + RequestOptions []Option + NewRequest func([]Option) (*Request, error) +} + +// ApplyOptions updates the waiter with the list of waiter options provided. +func (w *Waiter) ApplyOptions(opts ...WaiterOption) { + for _, fn := range opts { + fn(w) + } +} + +// WaiterState are states the waiter uses based on WaiterAcceptor definitions +// to identify if the resource state the waiter is waiting on has occurred. +type WaiterState int + +// String returns the string representation of the waiter state. +func (s WaiterState) String() string { + switch s { + case SuccessWaiterState: + return "success" + case FailureWaiterState: + return "failure" + case RetryWaiterState: + return "retry" + default: + return "unknown waiter state" + } +} + +// States the waiter acceptors will use to identify target resource states. +const ( + SuccessWaiterState WaiterState = iota // waiter successful + FailureWaiterState // waiter failed + RetryWaiterState // waiter needs to be retried +) + +// WaiterMatchMode is the mode that the waiter will use to match the WaiterAcceptor +// definition's Expected attribute. +type WaiterMatchMode int + +// Modes the waiter will use when inspecting API response to identify target +// resource states. +const ( + PathAllWaiterMatch WaiterMatchMode = iota // match on all paths + PathWaiterMatch // match on specific path + PathAnyWaiterMatch // match on any path + PathListWaiterMatch // match on list of paths + StatusWaiterMatch // match on status code + ErrorWaiterMatch // match on error +) + +// String returns the string representation of the waiter match mode. +func (m WaiterMatchMode) String() string { + switch m { + case PathAllWaiterMatch: + return "pathAll" + case PathWaiterMatch: + return "path" + case PathAnyWaiterMatch: + return "pathAny" + case PathListWaiterMatch: + return "pathList" + case StatusWaiterMatch: + return "status" + case ErrorWaiterMatch: + return "error" + default: + return "unknown waiter match mode" + } +} + +// WaitWithContext will make requests for the API operation using NewRequest to +// build API requests. The request's response will be compared against the +// Waiter's Acceptors to determine the successful state of the resource the +// waiter is inspecting. +// +// The passed in context must not be nil. If it is nil a panic will occur. The +// Context will be used to cancel the waiter's pending requests and retry delays. +// Use aws.BackgroundContext if no context is available. +// +// The waiter will continue until the target state defined by the Acceptors, +// or the max attempts expires. +// +// Will return the WaiterResourceNotReadyErrorCode error code if the waiter's +// retryer ShouldRetry returns false. This normally will happen when the max +// wait attempts expires. +func (w Waiter) WaitWithContext(ctx aws.Context) error { + + for attempt := 1; ; attempt++ { + req, err := w.NewRequest(w.RequestOptions) + if err != nil { + waiterLogf(w.Logger, "unable to create request %v", err) + return err + } + req.Handlers.Build.PushBack(MakeAddToUserAgentFreeFormHandler("Waiter")) + err = req.Send() + + // See if any of the acceptors match the request's response, or error + for _, a := range w.Acceptors { + var matched bool + matched, err = a.match(w.Name, w.Logger, req, err) + if err != nil { + // Error occurred during current waiter call + return err + } else if matched { + // Match was found can stop here and return + return nil + } + } + + // The Waiter should only check the resource state MaxAttempts times + // This is here instead of in the for loop above to prevent delaying + // unnecessary when the waiter will not retry. + if attempt == w.MaxAttempts { + break + } + + // Delay to wait before inspecting the resource again + delay := w.Delay(attempt) + if sleepFn := req.Config.SleepDelay; sleepFn != nil { + // Support SleepDelay for backwards compatibility and testing + sleepFn(delay) + } else if err := aws.SleepWithContext(ctx, delay); err != nil { + return awserr.New(CanceledErrorCode, "waiter context canceled", err) + } + } + + return awserr.New(WaiterResourceNotReadyErrorCode, "exceeded wait attempts", nil) +} + +// A WaiterAcceptor provides the information needed to wait for an API operation +// to complete. +type WaiterAcceptor struct { + State WaiterState + Matcher WaiterMatchMode + Argument string + Expected interface{} +} + +// match returns if the acceptor found a match with the passed in request +// or error. True is returned if the acceptor made a match, error is returned +// if there was an error attempting to perform the match. +func (a *WaiterAcceptor) match(name string, l aws.Logger, req *Request, err error) (bool, error) { + result := false + var vals []interface{} + + switch a.Matcher { + case PathAllWaiterMatch, PathWaiterMatch: + // Require all matches to be equal for result to match + vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) + if len(vals) == 0 { + break + } + result = true + for _, val := range vals { + if !awsutil.DeepEqual(val, a.Expected) { + result = false + break + } + } + case PathAnyWaiterMatch: + // Only a single match needs to equal for the result to match + vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) + for _, val := range vals { + if awsutil.DeepEqual(val, a.Expected) { + result = true + break + } + } + case PathListWaiterMatch: + // ignored matcher + case StatusWaiterMatch: + s := a.Expected.(int) + result = s == req.HTTPResponse.StatusCode + case ErrorWaiterMatch: + if aerr, ok := err.(awserr.Error); ok { + result = aerr.Code() == a.Expected.(string) + } + default: + waiterLogf(l, "WARNING: Waiter %s encountered unexpected matcher: %s", + name, a.Matcher) + } + + if !result { + // If there was no matching result found there is nothing more to do + // for this response, retry the request. + return false, nil + } + + switch a.State { + case SuccessWaiterState: + // waiter completed + return true, nil + case FailureWaiterState: + // Waiter failure state triggered + return false, awserr.New("ResourceNotReady", + "failed waiting for successful resource state", err) + case RetryWaiterState: + // clear the error and retry the operation + return false, nil + default: + waiterLogf(l, "WARNING: Waiter %s encountered unexpected state: %s", + name, a.State) + return false, nil + } +} + +func waiterLogf(logger aws.Logger, msg string, args ...interface{}) { + if logger != nil { + logger.Log(fmt.Sprintf(msg, args...)) + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go index d3dc840..660d9be 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go @@ -45,16 +45,16 @@ region, and profile loaded from the environment and shared config automatically. Requires the AWS_PROFILE to be set, or "default" is used. // Create Session - sess, err := session.NewSession() + sess := session.Must(session.NewSession()) // Create a Session with a custom region - sess, err := session.NewSession(&aws.Config{Region: aws.String("us-east-1")}) + sess := session.Must(session.NewSession(&aws.Config{ + Region: aws.String("us-east-1"), + })) // Create a S3 client instance from a session - sess, err := session.NewSession() - if err != nil { - // Handle Session creation error - } + sess := session.Must(session.NewSession()) + svc := s3.New(sess) Create Session With Option Overrides @@ -67,23 +67,25 @@ Use NewSessionWithOptions when you want to provide the config profile, or override the shared config state (AWS_SDK_LOAD_CONFIG). // Equivalent to session.NewSession() - sess, err := session.NewSessionWithOptions(session.Options{}) + sess := session.Must(session.NewSessionWithOptions(session.Options{ + // Options + })) // Specify profile to load for the session's config - sess, err := session.NewSessionWithOptions(session.Options{ + sess := session.Must(session.NewSessionWithOptions(session.Options{ Profile: "profile_name", - }) + })) // Specify profile for config and region for requests - sess, err := session.NewSessionWithOptions(session.Options{ + sess := session.Must(session.NewSessionWithOptions(session.Options{ Config: aws.Config{Region: aws.String("us-east-1")}, Profile: "profile_name", - }) + })) // Force enable Shared Config support - sess, err := session.NewSessionWithOptions(session.Options{ + sess := session.Must(session.NewSessionWithOptions(session.Options{ SharedConfigState: SharedConfigEnable, - }) + })) Adding Handlers @@ -93,7 +95,8 @@ handler logs every request and its payload made by a service client: // Create a session, and add additional handlers for all service // clients created with the Session to inherit. Adds logging handler. - sess, err := session.NewSession() + sess := session.Must(session.NewSession()) + sess.Handlers.Send.PushFront(func(r *request.Request) { // Log every request made and its payload logger.Println("Request: %s/%s, Payload: %s", @@ -138,15 +141,14 @@ the other two fields are also provided. Assume Role values allow you to configure the SDK to assume an IAM role using a set of credentials provided in a config file via the source_profile field. -Both "role_arn" and "source_profile" are required. The SDK does not support -assuming a role with MFA token Via the Session's constructor. You can use the -stscreds.AssumeRoleProvider credentials provider to specify custom -configuration and support for MFA. +Both "role_arn" and "source_profile" are required. The SDK supports assuming +a role with MFA token if the session option AssumeRoleTokenProvider +is set. role_arn = arn:aws:iam:::role/ source_profile = profile_with_creds external_id = 1234 - mfa_serial = not supported! + mfa_serial = role_session_name = session_name Region is the region the SDK should use for looking up AWS service endpoints @@ -154,6 +156,37 @@ and signing requests. region = us-east-1 +Assume Role with MFA token + +To create a session with support for assuming an IAM role with MFA set the +session option AssumeRoleTokenProvider to a function that will prompt for the +MFA token code when the SDK assumes the role and refreshes the role's credentials. +This allows you to configure the SDK via the shared config to assumea role +with MFA tokens. + +In order for the SDK to assume a role with MFA the SharedConfigState +session option must be set to SharedConfigEnable, or AWS_SDK_LOAD_CONFIG +environment variable set. + +The shared configuration instructs the SDK to assume an IAM role with MFA +when the mfa_serial configuration field is set in the shared config +(~/.aws/config) or shared credentials (~/.aws/credentials) file. + +If mfa_serial is set in the configuration, the SDK will assume the role, and +the AssumeRoleTokenProvider session option is not set an an error will +be returned when creating the session. + + sess := session.Must(session.NewSessionWithOptions(session.Options{ + AssumeRoleTokenProvider: stscreds.StdinTokenProvider, + })) + + // Create service client value configured for credentials + // from assumed role. + svc := s3.New(sess) + +To setup assume role outside of a session see the stscrds.AssumeRoleProvider +documentation. + Environment Variables When a Session is created several environment variables can be set to adjust @@ -218,6 +251,24 @@ $HOME/.aws/config on Linux/Unix based systems, and AWS_CONFIG_FILE=$HOME/my_shared_config +Path to a custom Credentials Authority (CA) bundle PEM file that the SDK +will use instead of the default system's root CA bundle. Use this only +if you want to replace the CA bundle the SDK uses for TLS requests. + + AWS_CA_BUNDLE=$HOME/my_custom_ca_bundle + +Enabling this option will attempt to merge the Transport into the SDK's HTTP +client. If the client's Transport is not a http.Transport an error will be +returned. If the Transport's TLS config is set this option will cause the SDK +to overwrite the Transport's TLS config's RootCAs value. If the CA bundle file +contains multiple certificates all of them will be loaded. + +The Session option CustomCABundle is also available when creating sessions +to also enable this feature. CustomCABundle session option field has priority +over the AWS_CA_BUNDLE environment variable, and will be used if both are set. +Setting a custom HTTPClient in the aws.Config options will override this setting. +To use this option and custom HTTP client, the HTTP client needs to be provided +when creating the session. Not the service client. */ package session diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go b/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go index d2f0c84..e6278a7 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go @@ -75,6 +75,24 @@ type envConfig struct { // // AWS_CONFIG_FILE=$HOME/my_shared_config SharedConfigFile string + + // Sets the path to a custom Credentials Authroity (CA) Bundle PEM file + // that the SDK will use instead of the the system's root CA bundle. + // Only use this if you want to configure the SDK to use a custom set + // of CAs. + // + // Enabling this option will attempt to merge the Transport + // into the SDK's HTTP client. If the client's Transport is + // not a http.Transport an error will be returned. If the + // Transport's TLS config is set this option will cause the + // SDK to overwrite the Transport's TLS config's RootCAs value. + // + // Setting a custom HTTPClient in the aws.Config options will override this setting. + // To use this option and custom HTTP client, the HTTP client needs to be provided + // when creating the session. Not the service client. + // + // AWS_CA_BUNDLE=$HOME/my_custom_ca_bundle + CustomCABundle string } var ( @@ -150,6 +168,8 @@ func envConfigLoad(enableSharedConfig bool) envConfig { cfg.SharedCredentialsFile = sharedCredentialsFilename() cfg.SharedConfigFile = sharedConfigFilename() + cfg.CustomCABundle = os.Getenv("AWS_CA_BUNDLE") + return cfg } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/session.go b/vendor/github.com/aws/aws-sdk-go/aws/session/session.go index c9427e9..96c740d 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/session.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/session/session.go @@ -1,7 +1,13 @@ package session import ( + "crypto/tls" + "crypto/x509" "fmt" + "io" + "io/ioutil" + "net/http" + "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" @@ -40,7 +46,7 @@ type Session struct { // // If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value // the shared config file (~/.aws/config) will also be loaded, in addition to -// the shared credentials file (~/.aws/config). Values set in both the +// the shared credentials file (~/.aws/credentials). Values set in both the // shared config, and shared credentials will be taken from the shared // credentials file. // @@ -52,7 +58,7 @@ func New(cfgs ...*aws.Config) *Session { envCfg := loadEnvConfig() if envCfg.EnableSharedConfig { - s, err := newSession(envCfg, cfgs...) + s, err := newSession(Options{}, envCfg, cfgs...) if err != nil { // Old session.New expected all errors to be discovered when // a request is made, and would report the errors then. This @@ -73,7 +79,7 @@ func New(cfgs ...*aws.Config) *Session { return s } - return oldNewSession(cfgs...) + return deprecatedNewSession(cfgs...) } // NewSession returns a new Session created from SDK defaults, config files, @@ -83,7 +89,7 @@ func New(cfgs ...*aws.Config) *Session { // // If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value // the shared config file (~/.aws/config) will also be loaded in addition to -// the shared credentials file (~/.aws/config). Values set in both the +// the shared credentials file (~/.aws/credentials). Values set in both the // shared config, and shared credentials will be taken from the shared // credentials file. Enabling the Shared Config will also allow the Session // to be built with retrieving credentials with AssumeRole set in the config. @@ -92,9 +98,10 @@ func New(cfgs ...*aws.Config) *Session { // control through code how the Session will be created. Such as specifying the // config profile, and controlling if shared config is enabled or not. func NewSession(cfgs ...*aws.Config) (*Session, error) { - envCfg := loadEnvConfig() + opts := Options{} + opts.Config.MergeIn(cfgs...) - return newSession(envCfg, cfgs...) + return NewSessionWithOptions(opts) } // SharedConfigState provides the ability to optionally override the state @@ -147,6 +154,41 @@ type Options struct { // will allow you to override the AWS_SDK_LOAD_CONFIG environment variable // and enable or disable the shared config functionality. SharedConfigState SharedConfigState + + // When the SDK's shared config is configured to assume a role with MFA + // this option is required in order to provide the mechanism that will + // retrieve the MFA token. There is no default value for this field. If + // it is not set an error will be returned when creating the session. + // + // This token provider will be called when ever the assumed role's + // credentials need to be refreshed. Within the context of service clients + // all sharing the same session the SDK will ensure calls to the token + // provider are atomic. When sharing a token provider across multiple + // sessions additional synchronization logic is needed to ensure the + // token providers do not introduce race conditions. It is recommend to + // share the session where possible. + // + // stscreds.StdinTokenProvider is a basic implementation that will prompt + // from stdin for the MFA token code. + // + // This field is only used if the shared configuration is enabled, and + // the config enables assume role wit MFA via the mfa_serial field. + AssumeRoleTokenProvider func() (string, error) + + // Reader for a custom Credentials Authority (CA) bundle in PEM format that + // the SDK will use instead of the default system's root CA bundle. Use this + // only if you want to replace the CA bundle the SDK uses for TLS requests. + // + // Enabling this option will attempt to merge the Transport into the SDK's HTTP + // client. If the client's Transport is not a http.Transport an error will be + // returned. If the Transport's TLS config is set this option will cause the SDK + // to overwrite the Transport's TLS config's RootCAs value. If the CA + // bundle reader contains multiple certificates all of them will be loaded. + // + // The Session option CustomCABundle is also available when creating sessions + // to also enable this feature. CustomCABundle session option field has priority + // over the AWS_CA_BUNDLE environment variable, and will be used if both are set. + CustomCABundle io.Reader } // NewSessionWithOptions returns a new Session created from SDK defaults, config files, @@ -155,29 +197,29 @@ type Options struct { // // If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value // the shared config file (~/.aws/config) will also be loaded in addition to -// the shared credentials file (~/.aws/config). Values set in both the +// the shared credentials file (~/.aws/credentials). Values set in both the // shared config, and shared credentials will be taken from the shared // credentials file. Enabling the Shared Config will also allow the Session // to be built with retrieving credentials with AssumeRole set in the config. // // // Equivalent to session.New -// sess, err := session.NewSessionWithOptions(session.Options{}) +// sess := session.Must(session.NewSessionWithOptions(session.Options{})) // // // Specify profile to load for the session's config -// sess, err := session.NewSessionWithOptions(session.Options{ +// sess := session.Must(session.NewSessionWithOptions(session.Options{ // Profile: "profile_name", -// }) +// })) // // // Specify profile for config and region for requests -// sess, err := session.NewSessionWithOptions(session.Options{ +// sess := session.Must(session.NewSessionWithOptions(session.Options{ // Config: aws.Config{Region: aws.String("us-east-1")}, // Profile: "profile_name", -// }) +// })) // // // Force enable Shared Config support -// sess, err := session.NewSessionWithOptions(session.Options{ +// sess := session.Must(session.NewSessionWithOptions(session.Options{ // SharedConfigState: SharedConfigEnable, -// }) +// })) func NewSessionWithOptions(opts Options) (*Session, error) { var envCfg envConfig if opts.SharedConfigState == SharedConfigEnable { @@ -197,7 +239,18 @@ func NewSessionWithOptions(opts Options) (*Session, error) { envCfg.EnableSharedConfig = true } - return newSession(envCfg, &opts.Config) + // Only use AWS_CA_BUNDLE if session option is not provided. + if len(envCfg.CustomCABundle) != 0 && opts.CustomCABundle == nil { + f, err := os.Open(envCfg.CustomCABundle) + if err != nil { + return nil, awserr.New("LoadCustomCABundleError", + "failed to open custom CA bundle PEM file", err) + } + defer f.Close() + opts.CustomCABundle = f + } + + return newSession(opts, envCfg, &opts.Config) } // Must is a helper function to ensure the Session is valid and there was no @@ -215,7 +268,7 @@ func Must(sess *Session, err error) *Session { return sess } -func oldNewSession(cfgs ...*aws.Config) *Session { +func deprecatedNewSession(cfgs ...*aws.Config) *Session { cfg := defaults.Config() handlers := defaults.Handlers() @@ -242,7 +295,7 @@ func oldNewSession(cfgs ...*aws.Config) *Session { return s } -func newSession(envCfg envConfig, cfgs ...*aws.Config) (*Session, error) { +func newSession(opts Options, envCfg envConfig, cfgs ...*aws.Config) (*Session, error) { cfg := defaults.Config() handlers := defaults.Handlers() @@ -266,7 +319,9 @@ func newSession(envCfg envConfig, cfgs ...*aws.Config) (*Session, error) { return nil, err } - mergeConfigSrcs(cfg, userCfg, envCfg, sharedCfg, handlers) + if err := mergeConfigSrcs(cfg, userCfg, envCfg, sharedCfg, handlers, opts); err != nil { + return nil, err + } s := &Session{ Config: cfg, @@ -275,10 +330,62 @@ func newSession(envCfg envConfig, cfgs ...*aws.Config) (*Session, error) { initHandlers(s) + // Setup HTTP client with custom cert bundle if enabled + if opts.CustomCABundle != nil { + if err := loadCustomCABundle(s, opts.CustomCABundle); err != nil { + return nil, err + } + } + return s, nil } -func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig, handlers request.Handlers) { +func loadCustomCABundle(s *Session, bundle io.Reader) error { + var t *http.Transport + switch v := s.Config.HTTPClient.Transport.(type) { + case *http.Transport: + t = v + default: + if s.Config.HTTPClient.Transport != nil { + return awserr.New("LoadCustomCABundleError", + "unable to load custom CA bundle, HTTPClient's transport unsupported type", nil) + } + } + if t == nil { + t = &http.Transport{} + } + + p, err := loadCertPool(bundle) + if err != nil { + return err + } + if t.TLSClientConfig == nil { + t.TLSClientConfig = &tls.Config{} + } + t.TLSClientConfig.RootCAs = p + + s.Config.HTTPClient.Transport = t + + return nil +} + +func loadCertPool(r io.Reader) (*x509.CertPool, error) { + b, err := ioutil.ReadAll(r) + if err != nil { + return nil, awserr.New("LoadCustomCABundleError", + "failed to read custom CA bundle PEM file", err) + } + + p := x509.NewCertPool() + if !p.AppendCertsFromPEM(b) { + return nil, awserr.New("LoadCustomCABundleError", + "failed to load custom CA bundle PEM file", err) + } + + return p, nil +} + +func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig, handlers request.Handlers, sessOpts Options) error { // Merge in user provided configuration cfg.MergeIn(userCfg) @@ -302,6 +409,11 @@ func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg share cfgCp.Credentials = credentials.NewStaticCredentialsFromCreds( sharedCfg.AssumeRoleSource.Creds, ) + if len(sharedCfg.AssumeRole.MFASerial) > 0 && sessOpts.AssumeRoleTokenProvider == nil { + // AssumeRole Token provider is required if doing Assume Role + // with MFA. + return AssumeRoleTokenProviderNotSetError{} + } cfg.Credentials = stscreds.NewCredentials( &Session{ Config: &cfgCp, @@ -311,11 +423,16 @@ func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg share func(opt *stscreds.AssumeRoleProvider) { opt.RoleSessionName = sharedCfg.AssumeRole.RoleSessionName + // Assume role with external ID if len(sharedCfg.AssumeRole.ExternalID) > 0 { opt.ExternalID = aws.String(sharedCfg.AssumeRole.ExternalID) } - // MFA not supported + // Assume role with MFA + if len(sharedCfg.AssumeRole.MFASerial) > 0 { + opt.SerialNumber = aws.String(sharedCfg.AssumeRole.MFASerial) + opt.TokenProvider = sessOpts.AssumeRoleTokenProvider + } }, ) } else if len(sharedCfg.Creds.AccessKeyID) > 0 { @@ -336,6 +453,33 @@ func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg share }) } } + + return nil +} + +// AssumeRoleTokenProviderNotSetError is an error returned when creating a session when the +// MFAToken option is not set when shared config is configured load assume a +// role with an MFA token. +type AssumeRoleTokenProviderNotSetError struct{} + +// Code is the short id of the error. +func (e AssumeRoleTokenProviderNotSetError) Code() string { + return "AssumeRoleTokenProviderNotSetError" +} + +// Message is the description of the error +func (e AssumeRoleTokenProviderNotSetError) Message() string { + return fmt.Sprintf("assume role with MFA enabled, but AssumeRoleTokenProvider session option not set.") +} + +// OrigErr is the underlying error that caused the failure. +func (e AssumeRoleTokenProviderNotSetError) OrigErr() error { + return nil +} + +// Error satisfies the error interface. +func (e AssumeRoleTokenProviderNotSetError) Error() string { + return awserr.SprintError(e.Code(), e.Message(), "", nil) } type credProviderError struct { @@ -404,6 +548,10 @@ func (s *Session) clientConfigWithErr(serviceName string, cfgs ...*aws.Config) ( func(opt *endpoints.Options) { opt.DisableSSL = aws.BoolValue(s.Config.DisableSSL) opt.UseDualStack = aws.BoolValue(s.Config.UseDualStack) + + // Support the condition where the service is modeled but its + // endpoint metadata is not available. + opt.ResolveUnknownService = true }, ) } @@ -416,3 +564,27 @@ func (s *Session) clientConfigWithErr(serviceName string, cfgs ...*aws.Config) ( SigningName: resolved.SigningName, }, err } + +// ClientConfigNoResolveEndpoint is the same as ClientConfig with the exception +// that the EndpointResolver will not be used to resolve the endpoint. The only +// endpoint set must come from the aws.Config.Endpoint field. +func (s *Session) ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) client.Config { + s = s.Copy(cfgs...) + + var resolved endpoints.ResolvedEndpoint + + region := aws.StringValue(s.Config.Region) + + if ep := aws.StringValue(s.Config.Endpoint); len(ep) > 0 { + resolved.URL = endpoints.AddScheme(ep, aws.BoolValue(s.Config.DisableSSL)) + resolved.SigningRegion = region + } + + return client.Config{ + Config: s.Config, + Handlers: s.Handlers, + Endpoint: resolved.URL, + SigningRegion: resolved.SigningRegion, + SigningName: resolved.SigningName, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go new file mode 100644 index 0000000..6aa2ed2 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go @@ -0,0 +1,7 @@ +package v4 + +// WithUnsignedPayload will enable and set the UnsignedPayload field to +// true of the signer. +func WithUnsignedPayload(v4 *Signer) { + v4.UnsignedPayload = true +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go index 98bfe74..434ac87 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go @@ -194,6 +194,10 @@ type Signer struct { // This value should only be used for testing. If it is nil the default // time.Now will be used. currentTimeFn func() time.Time + + // UnsignedPayload will prevent signing of the payload. This will only + // work for services that have support for this. + UnsignedPayload bool } // NewSigner returns a Signer pointer configured with the credentials and optional @@ -227,6 +231,7 @@ type signingCtx struct { isPresign bool formattedTime string formattedShortTime string + unsignedPayload bool bodyDigest string signedHeaders string @@ -317,6 +322,7 @@ func (v4 Signer) signWithBody(r *http.Request, body io.ReadSeeker, service, regi ServiceName: service, Region: region, DisableURIPathEscaping: v4.DisableURIPathEscaping, + unsignedPayload: v4.UnsignedPayload, } for key := range ctx.Query { @@ -409,7 +415,18 @@ var SignRequestHandler = request.NamedHandler{ func SignSDKRequest(req *request.Request) { signSDKRequestWithCurrTime(req, time.Now) } -func signSDKRequestWithCurrTime(req *request.Request, curTimeFn func() time.Time) { + +// BuildNamedHandler will build a generic handler for signing. +func BuildNamedHandler(name string, opts ...func(*Signer)) request.NamedHandler { + return request.NamedHandler{ + Name: name, + Fn: func(req *request.Request) { + signSDKRequestWithCurrTime(req, time.Now, opts...) + }, + } +} + +func signSDKRequestWithCurrTime(req *request.Request, curTimeFn func() time.Time, opts ...func(*Signer)) { // If the request does not need to be signed ignore the signing of the // request if the AnonymousCredentials object is used. if req.Config.Credentials == credentials.AnonymousCredentials { @@ -441,6 +458,10 @@ func signSDKRequestWithCurrTime(req *request.Request, curTimeFn func() time.Time v4.DisableRequestBodyOverwrite = true }) + for _, opt := range opts { + opt(v4) + } + signingTime := req.Time if !req.LastSignedAt.IsZero() { signingTime = req.LastSignedAt @@ -634,14 +655,14 @@ func (ctx *signingCtx) buildSignature() { func (ctx *signingCtx) buildBodyDigest() { hash := ctx.Request.Header.Get("X-Amz-Content-Sha256") if hash == "" { - if ctx.isPresign && ctx.ServiceName == "s3" { + if ctx.unsignedPayload || (ctx.isPresign && ctx.ServiceName == "s3") { hash = "UNSIGNED-PAYLOAD" } else if ctx.Body == nil { hash = emptyStringSHA256 } else { hash = hex.EncodeToString(makeSha256Reader(ctx.Body)) } - if ctx.ServiceName == "s3" || ctx.ServiceName == "glacier" { + if ctx.unsignedPayload || ctx.ServiceName == "s3" || ctx.ServiceName == "glacier" { ctx.Request.Header.Set("X-Amz-Content-Sha256", hash) } } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/types.go b/vendor/github.com/aws/aws-sdk-go/aws/types.go index 9ca685e..0e2d864 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/types.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/types.go @@ -114,5 +114,5 @@ func (b *WriteAtBuffer) WriteAt(p []byte, pos int64) (n int, err error) { func (b *WriteAtBuffer) Bytes() []byte { b.m.Lock() defer b.m.Unlock() - return b.buf[:len(b.buf):len(b.buf)] + return b.buf } diff --git a/vendor/github.com/aws/aws-sdk-go/aws/version.go b/vendor/github.com/aws/aws-sdk-go/aws/version.go index 33622b3..bf77141 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/version.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/version.go @@ -5,4 +5,4 @@ package aws const SDKName = "aws-sdk-go" // SDKVersion is the version of this SDK -const SDKVersion = "1.6.8" +const SDKVersion = "1.8.10" diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go index e166a85..6efe43d 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go @@ -4,7 +4,9 @@ package jsonutil import ( "bytes" "encoding/base64" + "encoding/json" "fmt" + "math" "reflect" "sort" "strconv" @@ -25,6 +27,7 @@ func BuildJSON(v interface{}) ([]byte, error) { } func buildAny(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { + origVal := value value = reflect.Indirect(value) if !value.IsValid() { return nil @@ -61,7 +64,7 @@ func buildAny(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) err case "map": return buildMap(value, buf, tag) default: - return buildScalar(value, buf, tag) + return buildScalar(origVal, buf, tag) } } @@ -87,6 +90,10 @@ func buildStruct(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) first := true for i := 0; i < t.NumField(); i++ { member := value.Field(i) + + // This allocates the most memory. + // Additionally, we cannot skip nil fields due to + // idempotency auto filling. field := t.Field(i) if field.PkgPath != "" { @@ -182,21 +189,32 @@ func buildMap(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) err return nil } -func buildScalar(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { - switch value.Kind() { +func buildScalar(v reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { + // prevents allocation on the heap. + scratch := [64]byte{} + switch value := reflect.Indirect(v); value.Kind() { case reflect.String: writeString(value.String(), buf) case reflect.Bool: - buf.WriteString(strconv.FormatBool(value.Bool())) + if value.Bool() { + buf.WriteString("true") + } else { + buf.WriteString("false") + } case reflect.Int64: - buf.WriteString(strconv.FormatInt(value.Int(), 10)) + buf.Write(strconv.AppendInt(scratch[:0], value.Int(), 10)) case reflect.Float64: - buf.WriteString(strconv.FormatFloat(value.Float(), 'f', -1, 64)) + f := value.Float() + if math.IsInf(f, 0) || math.IsNaN(f) { + return &json.UnsupportedValueError{Value: v, Str: strconv.FormatFloat(f, 'f', -1, 64)} + } + buf.Write(strconv.AppendFloat(scratch[:0], f, 'f', -1, 64)) default: switch value.Type() { case timeType: - converted := value.Interface().(time.Time) - buf.WriteString(strconv.FormatInt(converted.UTC().Unix(), 10)) + converted := v.Interface().(*time.Time) + + buf.Write(strconv.AppendInt(scratch[:0], converted.UTC().Unix(), 10)) case byteSliceType: if !value.IsNil() { converted := value.Interface().([]byte) @@ -222,27 +240,31 @@ func buildScalar(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) return nil } +var hex = "0123456789abcdef" + func writeString(s string, buf *bytes.Buffer) { buf.WriteByte('"') - for _, r := range s { - if r == '"' { + for i := 0; i < len(s); i++ { + if s[i] == '"' { buf.WriteString(`\"`) - } else if r == '\\' { + } else if s[i] == '\\' { buf.WriteString(`\\`) - } else if r == '\b' { + } else if s[i] == '\b' { buf.WriteString(`\b`) - } else if r == '\f' { + } else if s[i] == '\f' { buf.WriteString(`\f`) - } else if r == '\r' { + } else if s[i] == '\r' { buf.WriteString(`\r`) - } else if r == '\t' { + } else if s[i] == '\t' { buf.WriteString(`\t`) - } else if r == '\n' { + } else if s[i] == '\n' { buf.WriteString(`\n`) - } else if r < 32 { - fmt.Fprintf(buf, "\\u%0.4x", r) + } else if s[i] < 32 { + buf.WriteString("\\u00") + buf.WriteByte(hex[s[i]>>4]) + buf.WriteByte(hex[s[i]&0xF]) } else { - buf.WriteRune(r) + buf.WriteByte(s[i]) } } buf.WriteByte('"') diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go index f434ab7..524ca95 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go @@ -80,7 +80,6 @@ func (q *queryParser) parseStruct(v url.Values, value reflect.Value, prefix stri continue } - if protocol.CanSetIdempotencyToken(value.Field(i), field) { token := protocol.GetIdempotencyToken() elemValue = reflect.ValueOf(token) @@ -124,7 +123,11 @@ func (q *queryParser) parseList(v url.Values, value reflect.Value, prefix string // check for unflattened list member if !q.isEC2 && tag.Get("flattened") == "" { - prefix += ".member" + if listName := tag.Get("locationNameList"); listName == "" { + prefix += ".member" + } else { + prefix += "." + listName + } } for i := 0; i < value.Len(); i++ { diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go index 20a41d4..7161835 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go @@ -4,6 +4,7 @@ package rest import ( "bytes" "encoding/base64" + "encoding/json" "fmt" "io" "net/http" @@ -82,8 +83,12 @@ func buildLocationElements(r *request.Request, v reflect.Value, buildGETQuery bo if name == "" { name = field.Name } - if m.Kind() == reflect.Ptr { + if kind := m.Kind(); kind == reflect.Ptr { m = m.Elem() + } else if kind == reflect.Interface { + if !m.Elem().IsValid() { + continue + } } if !m.IsValid() { continue @@ -95,16 +100,16 @@ func buildLocationElements(r *request.Request, v reflect.Value, buildGETQuery bo var err error switch field.Tag.Get("location") { case "headers": // header maps - err = buildHeaderMap(&r.HTTPRequest.Header, m, field.Tag.Get("locationName")) + err = buildHeaderMap(&r.HTTPRequest.Header, m, field.Tag) case "header": - err = buildHeader(&r.HTTPRequest.Header, m, name) + err = buildHeader(&r.HTTPRequest.Header, m, name, field.Tag) case "uri": - err = buildURI(r.HTTPRequest.URL, m, name) + err = buildURI(r.HTTPRequest.URL, m, name, field.Tag) case "querystring": - err = buildQueryString(query, m, name) + err = buildQueryString(query, m, name, field.Tag) default: if buildGETQuery { - err = buildQueryString(query, m, name) + err = buildQueryString(query, m, name, field.Tag) } } r.Error = err @@ -145,8 +150,8 @@ func buildBody(r *request.Request, v reflect.Value) { } } -func buildHeader(header *http.Header, v reflect.Value, name string) error { - str, err := convertType(v) +func buildHeader(header *http.Header, v reflect.Value, name string, tag reflect.StructTag) error { + str, err := convertType(v, tag) if err == errValueNotSet { return nil } else if err != nil { @@ -158,9 +163,10 @@ func buildHeader(header *http.Header, v reflect.Value, name string) error { return nil } -func buildHeaderMap(header *http.Header, v reflect.Value, prefix string) error { +func buildHeaderMap(header *http.Header, v reflect.Value, tag reflect.StructTag) error { + prefix := tag.Get("locationName") for _, key := range v.MapKeys() { - str, err := convertType(v.MapIndex(key)) + str, err := convertType(v.MapIndex(key), tag) if err == errValueNotSet { continue } else if err != nil { @@ -173,8 +179,8 @@ func buildHeaderMap(header *http.Header, v reflect.Value, prefix string) error { return nil } -func buildURI(u *url.URL, v reflect.Value, name string) error { - value, err := convertType(v) +func buildURI(u *url.URL, v reflect.Value, name string, tag reflect.StructTag) error { + value, err := convertType(v, tag) if err == errValueNotSet { return nil } else if err != nil { @@ -190,7 +196,7 @@ func buildURI(u *url.URL, v reflect.Value, name string) error { return nil } -func buildQueryString(query url.Values, v reflect.Value, name string) error { +func buildQueryString(query url.Values, v reflect.Value, name string, tag reflect.StructTag) error { switch value := v.Interface().(type) { case []*string: for _, item := range value { @@ -207,7 +213,7 @@ func buildQueryString(query url.Values, v reflect.Value, name string) error { } } default: - str, err := convertType(v) + str, err := convertType(v, tag) if err == errValueNotSet { return nil } else if err != nil { @@ -246,7 +252,7 @@ func EscapePath(path string, encodeSep bool) string { return buf.String() } -func convertType(v reflect.Value) (string, error) { +func convertType(v reflect.Value, tag reflect.StructTag) (string, error) { v = reflect.Indirect(v) if !v.IsValid() { return "", errValueNotSet @@ -266,6 +272,16 @@ func convertType(v reflect.Value) (string, error) { str = strconv.FormatFloat(value, 'f', -1, 64) case time.Time: str = value.UTC().Format(RFC822) + case aws.JSONValue: + b, err := json.Marshal(value) + if err != nil { + return "", err + } + if tag.Get("location") == "header" { + str = base64.StdEncoding.EncodeToString(b) + } else { + str = string(b) + } default: err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type()) return "", err diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go index 9c00921..7a779ee 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go @@ -3,6 +3,7 @@ package rest import ( "bytes" "encoding/base64" + "encoding/json" "fmt" "io" "io/ioutil" @@ -12,6 +13,7 @@ import ( "strings" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/request" ) @@ -111,7 +113,7 @@ func unmarshalLocationElements(r *request.Request, v reflect.Value) { case "statusCode": unmarshalStatusCode(m, r.HTTPResponse.StatusCode) case "header": - err := unmarshalHeader(m, r.HTTPResponse.Header.Get(name)) + err := unmarshalHeader(m, r.HTTPResponse.Header.Get(name), field.Tag) if err != nil { r.Error = awserr.New("SerializationError", "failed to decode REST response", err) break @@ -158,8 +160,13 @@ func unmarshalHeaderMap(r reflect.Value, headers http.Header, prefix string) err return nil } -func unmarshalHeader(v reflect.Value, header string) error { - if !v.IsValid() || (header == "" && v.Elem().Kind() != reflect.String) { +func unmarshalHeader(v reflect.Value, header string, tag reflect.StructTag) error { + isJSONValue := tag.Get("type") == "jsonvalue" + if isJSONValue { + if len(header) == 0 { + return nil + } + } else if !v.IsValid() || (header == "" && v.Elem().Kind() != reflect.String) { return nil } @@ -196,6 +203,22 @@ func unmarshalHeader(v reflect.Value, header string) error { return err } v.Set(reflect.ValueOf(&t)) + case aws.JSONValue: + b := []byte(header) + var err error + if tag.Get("location") == "header" { + b, err = base64.StdEncoding.DecodeString(header) + if err != nil { + return err + } + } + + m := aws.JSONValue{} + err = json.Unmarshal(b, &m) + if err != nil { + return err + } + v.Set(reflect.ValueOf(m)) default: err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type()) return err diff --git a/vendor/github.com/aws/aws-sdk-go/private/waiter/waiter.go b/vendor/github.com/aws/aws-sdk-go/private/waiter/waiter.go deleted file mode 100644 index b51e944..0000000 --- a/vendor/github.com/aws/aws-sdk-go/private/waiter/waiter.go +++ /dev/null @@ -1,134 +0,0 @@ -package waiter - -import ( - "fmt" - "reflect" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/request" -) - -// A Config provides a collection of configuration values to setup a generated -// waiter code with. -type Config struct { - Name string - Delay int - MaxAttempts int - Operation string - Acceptors []WaitAcceptor -} - -// A WaitAcceptor provides the information needed to wait for an API operation -// to complete. -type WaitAcceptor struct { - Expected interface{} - Matcher string - State string - Argument string -} - -// A Waiter provides waiting for an operation to complete. -type Waiter struct { - Config - Client interface{} - Input interface{} -} - -// Wait waits for an operation to complete, expire max attempts, or fail. Error -// is returned if the operation fails. -func (w *Waiter) Wait() error { - client := reflect.ValueOf(w.Client) - in := reflect.ValueOf(w.Input) - method := client.MethodByName(w.Config.Operation + "Request") - - for i := 0; i < w.MaxAttempts; i++ { - res := method.Call([]reflect.Value{in}) - req := res[0].Interface().(*request.Request) - req.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Waiter")) - - err := req.Send() - for _, a := range w.Acceptors { - result := false - var vals []interface{} - switch a.Matcher { - case "pathAll", "path": - // Require all matches to be equal for result to match - vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) - if len(vals) == 0 { - break - } - result = true - for _, val := range vals { - if !awsutil.DeepEqual(val, a.Expected) { - result = false - break - } - } - case "pathAny": - // Only a single match needs to equal for the result to match - vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) - for _, val := range vals { - if awsutil.DeepEqual(val, a.Expected) { - result = true - break - } - } - case "status": - s := a.Expected.(int) - result = s == req.HTTPResponse.StatusCode - case "error": - if aerr, ok := err.(awserr.Error); ok { - result = aerr.Code() == a.Expected.(string) - } - case "pathList": - // ignored matcher - default: - logf(client, "WARNING: Waiter for %s encountered unexpected matcher: %s", - w.Config.Operation, a.Matcher) - } - - if !result { - // If there was no matching result found there is nothing more to do - // for this response, retry the request. - continue - } - - switch a.State { - case "success": - // waiter completed - return nil - case "failure": - // Waiter failure state triggered - return awserr.New("ResourceNotReady", - fmt.Sprintf("failed waiting for successful resource state"), err) - case "retry": - // clear the error and retry the operation - err = nil - default: - logf(client, "WARNING: Waiter for %s encountered unexpected state: %s", - w.Config.Operation, a.State) - } - } - if err != nil { - return err - } - - time.Sleep(time.Second * time.Duration(w.Delay)) - } - - return awserr.New("ResourceNotReady", - fmt.Sprintf("exceeded %d wait attempts", w.MaxAttempts), nil) -} - -func logf(client reflect.Value, msg string, args ...interface{}) { - cfgVal := client.FieldByName("Config") - if !cfgVal.IsValid() { - return - } - if cfg, ok := cfgVal.Interface().(*aws.Config); ok && cfg.Logger != nil { - cfg.Logger.Log(fmt.Sprintf(msg, args...)) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/api.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/api.go index 992eb19..95b35ba 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/api.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. // Package dynamodb provides a client for Amazon DynamoDB. package dynamodb @@ -7,8 +7,11 @@ import ( "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/private/protocol" + "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) const opBatchGetItem = "BatchGetItem" @@ -55,9 +58,8 @@ func (c *DynamoDB) BatchGetItemRequest(input *BatchGetItemInput) (req *request.R input = &BatchGetItemInput{} } - req = c.newRequest(op, input, output) output = &BatchGetItemOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -105,7 +107,7 @@ func (c *DynamoDB) BatchGetItemRequest(input *BatchGetItemInput) (req *request.R // // When designing your application, keep in mind that DynamoDB does not return // items in any particular order. To help parse the response by item, include -// the primary key values for the items in your request in the AttributesToGet +// the primary key values for the items in your request in the ProjectionExpression // parameter. // // If a requested item does not exist, it is not returned in the result. Requests @@ -121,26 +123,41 @@ func (c *DynamoDB) BatchGetItemRequest(input *BatchGetItemInput) (req *request.R // API operation BatchGetItem for usage and error information. // // Returned Error Codes: -// * ProvisionedThroughputExceededException +// * ErrCodeProvisionedThroughputExceededException "ProvisionedThroughputExceededException" // Your request rate is too high. The AWS SDKs for DynamoDB automatically retry // requests that receive this exception. Your request is eventually successful, // unless your retry queue is too large to finish. Reduce the frequency of requests // and use exponential backoff. For more information, go to Error Retries and -// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#APIRetries) +// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff) // in the Amazon DynamoDB Developer Guide. // -// * ResourceNotFoundException +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" // The operation tried to access a nonexistent table or index. The resource // might not be specified correctly, or its status might not be ACTIVE. // -// * InternalServerError +// * ErrCodeInternalServerError "InternalServerError" // An error occurred on the server side. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/BatchGetItem func (c *DynamoDB) BatchGetItem(input *BatchGetItemInput) (*BatchGetItemOutput, error) { req, out := c.BatchGetItemRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchGetItemWithContext is the same as BatchGetItem with the addition of +// the ability to pass a context and additional request options. +// +// See BatchGetItem for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) BatchGetItemWithContext(ctx aws.Context, input *BatchGetItemInput, opts ...request.Option) (*BatchGetItemOutput, error) { + req, out := c.BatchGetItemRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // BatchGetItemPages iterates over the pages of a BatchGetItem operation, @@ -160,12 +177,37 @@ func (c *DynamoDB) BatchGetItem(input *BatchGetItemInput) (*BatchGetItemOutput, // return pageNum <= 3 // }) // -func (c *DynamoDB) BatchGetItemPages(input *BatchGetItemInput, fn func(p *BatchGetItemOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.BatchGetItemRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*BatchGetItemOutput), lastPage) - }) +func (c *DynamoDB) BatchGetItemPages(input *BatchGetItemInput, fn func(*BatchGetItemOutput, bool) bool) error { + return c.BatchGetItemPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// BatchGetItemPagesWithContext same as BatchGetItemPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) BatchGetItemPagesWithContext(ctx aws.Context, input *BatchGetItemInput, fn func(*BatchGetItemOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *BatchGetItemInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.BatchGetItemRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*BatchGetItemOutput), !p.HasNextPage()) + } + return p.Err() } const opBatchWriteItem = "BatchWriteItem" @@ -206,9 +248,8 @@ func (c *DynamoDB) BatchWriteItemRequest(input *BatchWriteItemInput) (req *reque input = &BatchWriteItemInput{} } - req = c.newRequest(op, input, output) output = &BatchWriteItemOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -219,7 +260,7 @@ func (c *DynamoDB) BatchWriteItemRequest(input *BatchWriteItemInput) (req *reque // can comprise as many as 25 put or delete requests. Individual items to be // written can be as large as 400 KB. // -// BatchWriteItem cannot update items. To update items, use the UpdateItem API. +// BatchWriteItem cannot update items. To update items, use the UpdateItem action. // // The individual PutItem and DeleteItem operations specified in BatchWriteItem // are atomic; however BatchWriteItem as a whole is not. If any requested operations @@ -256,9 +297,9 @@ func (c *DynamoDB) BatchWriteItemRequest(input *BatchWriteItemInput) (req *reque // threads to write items in parallel. Your application must include the necessary // logic to manage the threads. With languages that don't support threading, // you must update or delete the specified items one at a time. In both situations, -// BatchWriteItem provides an alternative where the API performs the specified -// put and delete operations in parallel, giving you the power of the thread -// pool approach without having to introduce complexity into your application. +// BatchWriteItem performs the specified put and delete operations in parallel, +// giving you the power of the thread pool approach without having to introduce +// complexity into your application. // // Parallel processing reduces latency, but each specified put and delete request // consumes the same number of write capacity units whether it is processed @@ -292,30 +333,45 @@ func (c *DynamoDB) BatchWriteItemRequest(input *BatchWriteItemInput) (req *reque // API operation BatchWriteItem for usage and error information. // // Returned Error Codes: -// * ProvisionedThroughputExceededException +// * ErrCodeProvisionedThroughputExceededException "ProvisionedThroughputExceededException" // Your request rate is too high. The AWS SDKs for DynamoDB automatically retry // requests that receive this exception. Your request is eventually successful, // unless your retry queue is too large to finish. Reduce the frequency of requests // and use exponential backoff. For more information, go to Error Retries and -// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#APIRetries) +// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff) // in the Amazon DynamoDB Developer Guide. // -// * ResourceNotFoundException +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" // The operation tried to access a nonexistent table or index. The resource // might not be specified correctly, or its status might not be ACTIVE. // -// * ItemCollectionSizeLimitExceededException +// * ErrCodeItemCollectionSizeLimitExceededException "ItemCollectionSizeLimitExceededException" // An item collection is too large. This exception is only returned for tables // that have one or more local secondary indexes. // -// * InternalServerError +// * ErrCodeInternalServerError "InternalServerError" // An error occurred on the server side. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/BatchWriteItem func (c *DynamoDB) BatchWriteItem(input *BatchWriteItemInput) (*BatchWriteItemOutput, error) { req, out := c.BatchWriteItemRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// BatchWriteItemWithContext is the same as BatchWriteItem with the addition of +// the ability to pass a context and additional request options. +// +// See BatchWriteItem for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) BatchWriteItemWithContext(ctx aws.Context, input *BatchWriteItemInput, opts ...request.Option) (*BatchWriteItemOutput, error) { + req, out := c.BatchWriteItemRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateTable = "CreateTable" @@ -356,9 +412,8 @@ func (c *DynamoDB) CreateTableRequest(input *CreateTableInput) (req *request.Req input = &CreateTableInput{} } - req = c.newRequest(op, input, output) output = &CreateTableOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -378,7 +433,7 @@ func (c *DynamoDB) CreateTableRequest(input *CreateTableInput) (req *request.Req // indexes on them, you must create the tables sequentially. Only one table // with secondary indexes can be in the CREATING state at any given time. // -// You can use the DescribeTable API to check the table status. +// You can use the DescribeTable action to check the table status. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -388,12 +443,12 @@ func (c *DynamoDB) CreateTableRequest(input *CreateTableInput) (req *request.Req // API operation CreateTable for usage and error information. // // Returned Error Codes: -// * ResourceInUseException +// * ErrCodeResourceInUseException "ResourceInUseException" // The operation conflicts with the resource's availability. For example, you // attempted to recreate an existing table, or tried to delete a table currently // in the CREATING state. // -// * LimitExceededException +// * ErrCodeLimitExceededException "LimitExceededException" // The number of concurrent table requests (cumulative number of tables in the // CREATING, DELETING or UPDATING state) exceeds the maximum allowed of 10. // @@ -403,14 +458,29 @@ func (c *DynamoDB) CreateTableRequest(input *CreateTableInput) (req *request.Req // // The total limit of tables in the ACTIVE state is 250. // -// * InternalServerError +// * ErrCodeInternalServerError "InternalServerError" // An error occurred on the server side. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/CreateTable func (c *DynamoDB) CreateTable(input *CreateTableInput) (*CreateTableOutput, error) { req, out := c.CreateTableRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateTableWithContext is the same as CreateTable with the addition of +// the ability to pass a context and additional request options. +// +// See CreateTable for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) CreateTableWithContext(ctx aws.Context, input *CreateTableInput, opts ...request.Option) (*CreateTableOutput, error) { + req, out := c.CreateTableRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteItem = "DeleteItem" @@ -451,9 +521,8 @@ func (c *DynamoDB) DeleteItemRequest(input *DeleteItemInput) (req *request.Reque input = &DeleteItemInput{} } - req = c.newRequest(op, input, output) output = &DeleteItemOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -482,33 +551,48 @@ func (c *DynamoDB) DeleteItemRequest(input *DeleteItemInput) (req *request.Reque // API operation DeleteItem for usage and error information. // // Returned Error Codes: -// * ConditionalCheckFailedException +// * ErrCodeConditionalCheckFailedException "ConditionalCheckFailedException" // A condition specified in the operation could not be evaluated. // -// * ProvisionedThroughputExceededException +// * ErrCodeProvisionedThroughputExceededException "ProvisionedThroughputExceededException" // Your request rate is too high. The AWS SDKs for DynamoDB automatically retry // requests that receive this exception. Your request is eventually successful, // unless your retry queue is too large to finish. Reduce the frequency of requests // and use exponential backoff. For more information, go to Error Retries and -// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#APIRetries) +// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff) // in the Amazon DynamoDB Developer Guide. // -// * ResourceNotFoundException +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" // The operation tried to access a nonexistent table or index. The resource // might not be specified correctly, or its status might not be ACTIVE. // -// * ItemCollectionSizeLimitExceededException +// * ErrCodeItemCollectionSizeLimitExceededException "ItemCollectionSizeLimitExceededException" // An item collection is too large. This exception is only returned for tables // that have one or more local secondary indexes. // -// * InternalServerError +// * ErrCodeInternalServerError "InternalServerError" // An error occurred on the server side. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DeleteItem func (c *DynamoDB) DeleteItem(input *DeleteItemInput) (*DeleteItemOutput, error) { req, out := c.DeleteItemRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteItemWithContext is the same as DeleteItem with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteItem for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) DeleteItemWithContext(ctx aws.Context, input *DeleteItemInput, opts ...request.Option) (*DeleteItemOutput, error) { + req, out := c.DeleteItemRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteTable = "DeleteTable" @@ -549,9 +633,8 @@ func (c *DynamoDB) DeleteTableRequest(input *DeleteTableInput) (req *request.Req input = &DeleteTableInput{} } - req = c.newRequest(op, input, output) output = &DeleteTableOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -574,7 +657,7 @@ func (c *DynamoDB) DeleteTableRequest(input *DeleteTableInput) (req *request.Req // stream on that table goes into the DISABLED state, and the stream is automatically // deleted after 24 hours. // -// Use the DescribeTable API to check the status of the table. +// Use the DescribeTable action to check the status of the table. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about @@ -584,16 +667,16 @@ func (c *DynamoDB) DeleteTableRequest(input *DeleteTableInput) (req *request.Req // API operation DeleteTable for usage and error information. // // Returned Error Codes: -// * ResourceInUseException +// * ErrCodeResourceInUseException "ResourceInUseException" // The operation conflicts with the resource's availability. For example, you // attempted to recreate an existing table, or tried to delete a table currently // in the CREATING state. // -// * ResourceNotFoundException +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" // The operation tried to access a nonexistent table or index. The resource // might not be specified correctly, or its status might not be ACTIVE. // -// * LimitExceededException +// * ErrCodeLimitExceededException "LimitExceededException" // The number of concurrent table requests (cumulative number of tables in the // CREATING, DELETING or UPDATING state) exceeds the maximum allowed of 10. // @@ -603,14 +686,29 @@ func (c *DynamoDB) DeleteTableRequest(input *DeleteTableInput) (req *request.Req // // The total limit of tables in the ACTIVE state is 250. // -// * InternalServerError +// * ErrCodeInternalServerError "InternalServerError" // An error occurred on the server side. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DeleteTable func (c *DynamoDB) DeleteTable(input *DeleteTableInput) (*DeleteTableOutput, error) { req, out := c.DeleteTableRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteTableWithContext is the same as DeleteTable with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteTable for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) DeleteTableWithContext(ctx aws.Context, input *DeleteTableInput, opts ...request.Option) (*DeleteTableOutput, error) { + req, out := c.DeleteTableRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeLimits = "DescribeLimits" @@ -651,9 +749,8 @@ func (c *DynamoDB) DescribeLimitsRequest(input *DescribeLimitsInput) (req *reque input = &DescribeLimitsInput{} } - req = c.newRequest(op, input, output) output = &DescribeLimitsOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -672,7 +769,7 @@ func (c *DynamoDB) DescribeLimitsRequest(input *DescribeLimitsInput) (req *reque // // Although you can increase these limits by filing a case at AWS Support Center // (https://console.aws.amazon.com/support/home#/), obtaining the increase is -// not instantaneous. The DescribeLimits API lets you write code to compare +// not instantaneous. The DescribeLimits action lets you write code to compare // the capacity you are currently using to those limits imposed by your account // so that you have enough time to apply for an increase before you hit a limit. // @@ -725,14 +822,29 @@ func (c *DynamoDB) DescribeLimitsRequest(input *DescribeLimitsInput) (req *reque // API operation DescribeLimits for usage and error information. // // Returned Error Codes: -// * InternalServerError +// * ErrCodeInternalServerError "InternalServerError" // An error occurred on the server side. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeLimits func (c *DynamoDB) DescribeLimits(input *DescribeLimitsInput) (*DescribeLimitsOutput, error) { req, out := c.DescribeLimitsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeLimitsWithContext is the same as DescribeLimits with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeLimits for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) DescribeLimitsWithContext(ctx aws.Context, input *DescribeLimitsInput, opts ...request.Option) (*DescribeLimitsOutput, error) { + req, out := c.DescribeLimitsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeTable = "DescribeTable" @@ -773,9 +885,8 @@ func (c *DynamoDB) DescribeTableRequest(input *DescribeTableInput) (req *request input = &DescribeTableInput{} } - req = c.newRequest(op, input, output) output = &DescribeTableOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -799,18 +910,117 @@ func (c *DynamoDB) DescribeTableRequest(input *DescribeTableInput) (req *request // API operation DescribeTable for usage and error information. // // Returned Error Codes: -// * ResourceNotFoundException +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" // The operation tried to access a nonexistent table or index. The resource // might not be specified correctly, or its status might not be ACTIVE. // -// * InternalServerError +// * ErrCodeInternalServerError "InternalServerError" // An error occurred on the server side. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeTable func (c *DynamoDB) DescribeTable(input *DescribeTableInput) (*DescribeTableOutput, error) { req, out := c.DescribeTableRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeTableWithContext is the same as DescribeTable with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTable for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) DescribeTableWithContext(ctx aws.Context, input *DescribeTableInput, opts ...request.Option) (*DescribeTableOutput, error) { + req, out := c.DescribeTableRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opDescribeTimeToLive = "DescribeTimeToLive" + +// DescribeTimeToLiveRequest generates a "aws/request.Request" representing the +// client's request for the DescribeTimeToLive operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See DescribeTimeToLive for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the DescribeTimeToLive method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the DescribeTimeToLiveRequest method. +// req, resp := client.DescribeTimeToLiveRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeTimeToLive +func (c *DynamoDB) DescribeTimeToLiveRequest(input *DescribeTimeToLiveInput) (req *request.Request, output *DescribeTimeToLiveOutput) { + op := &request.Operation{ + Name: opDescribeTimeToLive, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DescribeTimeToLiveInput{} + } + + output = &DescribeTimeToLiveOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeTimeToLive API operation for Amazon DynamoDB. +// +// Gives a description of the Time to Live (TTL) status on the specified table. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon DynamoDB's +// API operation DescribeTimeToLive for usage and error information. +// +// Returned Error Codes: +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// The operation tried to access a nonexistent table or index. The resource +// might not be specified correctly, or its status might not be ACTIVE. +// +// * ErrCodeInternalServerError "InternalServerError" +// An error occurred on the server side. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeTimeToLive +func (c *DynamoDB) DescribeTimeToLive(input *DescribeTimeToLiveInput) (*DescribeTimeToLiveOutput, error) { + req, out := c.DescribeTimeToLiveRequest(input) + return out, req.Send() +} + +// DescribeTimeToLiveWithContext is the same as DescribeTimeToLive with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeTimeToLive for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) DescribeTimeToLiveWithContext(ctx aws.Context, input *DescribeTimeToLiveInput, opts ...request.Option) (*DescribeTimeToLiveOutput, error) { + req, out := c.DescribeTimeToLiveRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetItem = "GetItem" @@ -851,16 +1061,16 @@ func (c *DynamoDB) GetItemRequest(input *GetItemInput) (req *request.Request, ou input = &GetItemInput{} } - req = c.newRequest(op, input, output) output = &GetItemOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } // GetItem API operation for Amazon DynamoDB. // // The GetItem operation returns a set of attributes for the item with the given -// primary key. If there is no matching item, GetItem does not return any data. +// primary key. If there is no matching item, GetItem does not return any data +// and there will be no Item element in the response. // // GetItem provides an eventually consistent read by default. If your application // requires a strongly consistent read, set ConsistentRead to true. Although @@ -875,26 +1085,41 @@ func (c *DynamoDB) GetItemRequest(input *GetItemInput) (req *request.Request, ou // API operation GetItem for usage and error information. // // Returned Error Codes: -// * ProvisionedThroughputExceededException +// * ErrCodeProvisionedThroughputExceededException "ProvisionedThroughputExceededException" // Your request rate is too high. The AWS SDKs for DynamoDB automatically retry // requests that receive this exception. Your request is eventually successful, // unless your retry queue is too large to finish. Reduce the frequency of requests // and use exponential backoff. For more information, go to Error Retries and -// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#APIRetries) +// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff) // in the Amazon DynamoDB Developer Guide. // -// * ResourceNotFoundException +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" // The operation tried to access a nonexistent table or index. The resource // might not be specified correctly, or its status might not be ACTIVE. // -// * InternalServerError +// * ErrCodeInternalServerError "InternalServerError" // An error occurred on the server side. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/GetItem func (c *DynamoDB) GetItem(input *GetItemInput) (*GetItemOutput, error) { req, out := c.GetItemRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetItemWithContext is the same as GetItem with the addition of +// the ability to pass a context and additional request options. +// +// See GetItem for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) GetItemWithContext(ctx aws.Context, input *GetItemInput, opts ...request.Option) (*GetItemOutput, error) { + req, out := c.GetItemRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListTables = "ListTables" @@ -941,9 +1166,8 @@ func (c *DynamoDB) ListTablesRequest(input *ListTablesInput) (req *request.Reque input = &ListTablesInput{} } - req = c.newRequest(op, input, output) output = &ListTablesOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -961,14 +1185,29 @@ func (c *DynamoDB) ListTablesRequest(input *ListTablesInput) (req *request.Reque // API operation ListTables for usage and error information. // // Returned Error Codes: -// * InternalServerError +// * ErrCodeInternalServerError "InternalServerError" // An error occurred on the server side. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ListTables func (c *DynamoDB) ListTables(input *ListTablesInput) (*ListTablesOutput, error) { req, out := c.ListTablesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListTablesWithContext is the same as ListTables with the addition of +// the ability to pass a context and additional request options. +// +// See ListTables for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) ListTablesWithContext(ctx aws.Context, input *ListTablesInput, opts ...request.Option) (*ListTablesOutput, error) { + req, out := c.ListTablesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListTablesPages iterates over the pages of a ListTables operation, @@ -988,12 +1227,125 @@ func (c *DynamoDB) ListTables(input *ListTablesInput) (*ListTablesOutput, error) // return pageNum <= 3 // }) // -func (c *DynamoDB) ListTablesPages(input *ListTablesInput, fn func(p *ListTablesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListTablesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListTablesOutput), lastPage) - }) +func (c *DynamoDB) ListTablesPages(input *ListTablesInput, fn func(*ListTablesOutput, bool) bool) error { + return c.ListTablesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListTablesPagesWithContext same as ListTablesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) ListTablesPagesWithContext(ctx aws.Context, input *ListTablesInput, fn func(*ListTablesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListTablesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListTablesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListTablesOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListTagsOfResource = "ListTagsOfResource" + +// ListTagsOfResourceRequest generates a "aws/request.Request" representing the +// client's request for the ListTagsOfResource operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListTagsOfResource for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListTagsOfResource method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListTagsOfResourceRequest method. +// req, resp := client.ListTagsOfResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ListTagsOfResource +func (c *DynamoDB) ListTagsOfResourceRequest(input *ListTagsOfResourceInput) (req *request.Request, output *ListTagsOfResourceOutput) { + op := &request.Operation{ + Name: opListTagsOfResource, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ListTagsOfResourceInput{} + } + + output = &ListTagsOfResourceOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListTagsOfResource API operation for Amazon DynamoDB. +// +// List all tags on an Amazon DynamoDB resource. You can call ListTagsOfResource +// up to 10 times per second, per account. +// +// For an overview on tagging DynamoDB resources, see Tagging for DynamoDB (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tagging.html) +// in the Amazon DynamoDB Developer Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon DynamoDB's +// API operation ListTagsOfResource for usage and error information. +// +// Returned Error Codes: +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// The operation tried to access a nonexistent table or index. The resource +// might not be specified correctly, or its status might not be ACTIVE. +// +// * ErrCodeInternalServerError "InternalServerError" +// An error occurred on the server side. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ListTagsOfResource +func (c *DynamoDB) ListTagsOfResource(input *ListTagsOfResourceInput) (*ListTagsOfResourceOutput, error) { + req, out := c.ListTagsOfResourceRequest(input) + return out, req.Send() +} + +// ListTagsOfResourceWithContext is the same as ListTagsOfResource with the addition of +// the ability to pass a context and additional request options. +// +// See ListTagsOfResource for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) ListTagsOfResourceWithContext(ctx aws.Context, input *ListTagsOfResourceInput, opts ...request.Option) (*ListTagsOfResourceOutput, error) { + req, out := c.ListTagsOfResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutItem = "PutItem" @@ -1034,9 +1386,8 @@ func (c *DynamoDB) PutItemRequest(input *PutItemInput) (req *request.Request, ou input = &PutItemInput{} } - req = c.newRequest(op, input, output) output = &PutItemOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1057,17 +1408,13 @@ func (c *DynamoDB) PutItemRequest(input *PutItemInput) (req *request.Request, ou // must have lengths greater than zero. Set type attributes cannot be empty. // Requests with empty values will be rejected with a ValidationException exception. // -// You can request that PutItem return either a copy of the original item (before -// the update) or a copy of the updated item (after the update). For more information, -// see the ReturnValues description below. -// // To prevent a new item from replacing an existing item, use a conditional // expression that contains the attribute_not_exists function with the name // of the attribute being used as the partition key for the table. Since every // record must contain that attribute, the attribute_not_exists function will // only succeed if no matching item exists. // -// For more information about using this API, see Working with Items (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html) +// For more information about PutItem, see Working with Items (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html) // in the Amazon DynamoDB Developer Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -1078,33 +1425,48 @@ func (c *DynamoDB) PutItemRequest(input *PutItemInput) (req *request.Request, ou // API operation PutItem for usage and error information. // // Returned Error Codes: -// * ConditionalCheckFailedException +// * ErrCodeConditionalCheckFailedException "ConditionalCheckFailedException" // A condition specified in the operation could not be evaluated. // -// * ProvisionedThroughputExceededException +// * ErrCodeProvisionedThroughputExceededException "ProvisionedThroughputExceededException" // Your request rate is too high. The AWS SDKs for DynamoDB automatically retry // requests that receive this exception. Your request is eventually successful, // unless your retry queue is too large to finish. Reduce the frequency of requests // and use exponential backoff. For more information, go to Error Retries and -// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#APIRetries) +// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff) // in the Amazon DynamoDB Developer Guide. // -// * ResourceNotFoundException +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" // The operation tried to access a nonexistent table or index. The resource // might not be specified correctly, or its status might not be ACTIVE. // -// * ItemCollectionSizeLimitExceededException +// * ErrCodeItemCollectionSizeLimitExceededException "ItemCollectionSizeLimitExceededException" // An item collection is too large. This exception is only returned for tables // that have one or more local secondary indexes. // -// * InternalServerError +// * ErrCodeInternalServerError "InternalServerError" // An error occurred on the server side. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/PutItem func (c *DynamoDB) PutItem(input *PutItemInput) (*PutItemOutput, error) { req, out := c.PutItemRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutItemWithContext is the same as PutItem with the addition of +// the ability to pass a context and additional request options. +// +// See PutItem for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) PutItemWithContext(ctx aws.Context, input *PutItemInput, opts ...request.Option) (*PutItemOutput, error) { + req, out := c.PutItemRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opQuery = "Query" @@ -1151,9 +1513,8 @@ func (c *DynamoDB) QueryRequest(input *QueryInput) (req *request.Request, output input = &QueryInput{} } - req = c.newRequest(op, input, output) output = &QueryOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1194,26 +1555,41 @@ func (c *DynamoDB) QueryRequest(input *QueryInput) (req *request.Request, output // API operation Query for usage and error information. // // Returned Error Codes: -// * ProvisionedThroughputExceededException +// * ErrCodeProvisionedThroughputExceededException "ProvisionedThroughputExceededException" // Your request rate is too high. The AWS SDKs for DynamoDB automatically retry // requests that receive this exception. Your request is eventually successful, // unless your retry queue is too large to finish. Reduce the frequency of requests // and use exponential backoff. For more information, go to Error Retries and -// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#APIRetries) +// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff) // in the Amazon DynamoDB Developer Guide. // -// * ResourceNotFoundException +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" // The operation tried to access a nonexistent table or index. The resource // might not be specified correctly, or its status might not be ACTIVE. // -// * InternalServerError +// * ErrCodeInternalServerError "InternalServerError" // An error occurred on the server side. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/Query func (c *DynamoDB) Query(input *QueryInput) (*QueryOutput, error) { req, out := c.QueryRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// QueryWithContext is the same as Query with the addition of +// the ability to pass a context and additional request options. +// +// See Query for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) QueryWithContext(ctx aws.Context, input *QueryInput, opts ...request.Option) (*QueryOutput, error) { + req, out := c.QueryRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // QueryPages iterates over the pages of a Query operation, @@ -1233,12 +1609,37 @@ func (c *DynamoDB) Query(input *QueryInput) (*QueryOutput, error) { // return pageNum <= 3 // }) // -func (c *DynamoDB) QueryPages(input *QueryInput, fn func(p *QueryOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.QueryRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*QueryOutput), lastPage) - }) +func (c *DynamoDB) QueryPages(input *QueryInput, fn func(*QueryOutput, bool) bool) error { + return c.QueryPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// QueryPagesWithContext same as QueryPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) QueryPagesWithContext(ctx aws.Context, input *QueryInput, fn func(*QueryOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *QueryInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.QueryRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*QueryOutput), !p.HasNextPage()) + } + return p.Err() } const opScan = "Scan" @@ -1285,9 +1686,8 @@ func (c *DynamoDB) ScanRequest(input *ScanInput) (req *request.Request, output * input = &ScanInput{} } - req = c.newRequest(op, input, output) output = &ScanOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1295,7 +1695,7 @@ func (c *DynamoDB) ScanRequest(input *ScanInput) (req *request.Request, output * // // The Scan operation returns one or more items and item attributes by accessing // every item in a table or a secondary index. To have DynamoDB return fewer -// items, you can provide a ScanFilter operation. +// items, you can provide a FilterExpression operation. // // If the total number of scanned items exceeds the maximum data set size limit // of 1 MB, the scan stops and results are returned to the user as a LastEvaluatedKey @@ -1323,26 +1723,41 @@ func (c *DynamoDB) ScanRequest(input *ScanInput) (req *request.Request, output * // API operation Scan for usage and error information. // // Returned Error Codes: -// * ProvisionedThroughputExceededException +// * ErrCodeProvisionedThroughputExceededException "ProvisionedThroughputExceededException" // Your request rate is too high. The AWS SDKs for DynamoDB automatically retry // requests that receive this exception. Your request is eventually successful, // unless your retry queue is too large to finish. Reduce the frequency of requests // and use exponential backoff. For more information, go to Error Retries and -// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#APIRetries) +// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff) // in the Amazon DynamoDB Developer Guide. // -// * ResourceNotFoundException +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" // The operation tried to access a nonexistent table or index. The resource // might not be specified correctly, or its status might not be ACTIVE. // -// * InternalServerError +// * ErrCodeInternalServerError "InternalServerError" // An error occurred on the server side. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/Scan func (c *DynamoDB) Scan(input *ScanInput) (*ScanOutput, error) { req, out := c.ScanRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ScanWithContext is the same as Scan with the addition of +// the ability to pass a context and additional request options. +// +// See Scan for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) ScanWithContext(ctx aws.Context, input *ScanInput, opts ...request.Option) (*ScanOutput, error) { + req, out := c.ScanRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ScanPages iterates over the pages of a Scan operation, @@ -1362,104 +1777,355 @@ func (c *DynamoDB) Scan(input *ScanInput) (*ScanOutput, error) { // return pageNum <= 3 // }) // -func (c *DynamoDB) ScanPages(input *ScanInput, fn func(p *ScanOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ScanRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ScanOutput), lastPage) - }) +func (c *DynamoDB) ScanPages(input *ScanInput, fn func(*ScanOutput, bool) bool) error { + return c.ScanPagesWithContext(aws.BackgroundContext(), input, fn) } -const opUpdateItem = "UpdateItem" +// ScanPagesWithContext same as ScanPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) ScanPagesWithContext(ctx aws.Context, input *ScanInput, fn func(*ScanOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ScanInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ScanRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } -// UpdateItemRequest generates a "aws/request.Request" representing the -// client's request for the UpdateItem operation. The "output" return + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ScanOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opTagResource = "TagResource" + +// TagResourceRequest generates a "aws/request.Request" representing the +// client's request for the TagResource operation. The "output" return // value can be used to capture response data after the request's "Send" method // is called. // -// See UpdateItem for usage and error information. +// See TagResource for usage and error information. // // Creating a request object using this method should be used when you want to inject // custom logic into the request's lifecycle using a custom handler, or if you want to // access properties on the request object before or after sending the request. If -// you just want the service response, call the UpdateItem method directly +// you just want the service response, call the TagResource method directly // instead. // // Note: You must call the "Send" method on the returned request object in order // to execute the request. // -// // Example sending a request using the UpdateItemRequest method. -// req, resp := client.UpdateItemRequest(params) +// // Example sending a request using the TagResourceRequest method. +// req, resp := client.TagResourceRequest(params) // // err := req.Send() // if err == nil { // resp is now filled // fmt.Println(resp) // } // -// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateItem -func (c *DynamoDB) UpdateItemRequest(input *UpdateItemInput) (req *request.Request, output *UpdateItemOutput) { +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/TagResource +func (c *DynamoDB) TagResourceRequest(input *TagResourceInput) (req *request.Request, output *TagResourceOutput) { op := &request.Operation{ - Name: opUpdateItem, + Name: opTagResource, HTTPMethod: "POST", HTTPPath: "/", } if input == nil { - input = &UpdateItemInput{} + input = &TagResourceInput{} } + output = &TagResourceOutput{} req = c.newRequest(op, input, output) - output = &UpdateItemOutput{} - req.Data = output + req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) return } -// UpdateItem API operation for Amazon DynamoDB. +// TagResource API operation for Amazon DynamoDB. // -// Edits an existing item's attributes, or adds a new item to the table if it -// does not already exist. You can put, delete, or add attribute values. You -// can also perform a conditional update on an existing item (insert a new attribute -// name-value pair if it doesn't exist, or replace an existing name-value pair -// if it has certain expected attribute values). +// Associate a set of tags with an Amazon DynamoDB resource. You can then activate +// these user-defined tags so that they appear on the Billing and Cost Management +// console for cost allocation tracking. You can call TagResource up to 5 times +// per second, per account. // -// You can also return the item's attribute values in the same UpdateItem operation -// using the ReturnValues parameter. +// For an overview on tagging DynamoDB resources, see Tagging for DynamoDB (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tagging.html) +// in the Amazon DynamoDB Developer Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions // with awserr.Error's Code and Message methods to get detailed information about // the error. // // See the AWS API reference guide for Amazon DynamoDB's -// API operation UpdateItem for usage and error information. +// API operation TagResource for usage and error information. // // Returned Error Codes: -// * ConditionalCheckFailedException -// A condition specified in the operation could not be evaluated. +// * ErrCodeLimitExceededException "LimitExceededException" +// The number of concurrent table requests (cumulative number of tables in the +// CREATING, DELETING or UPDATING state) exceeds the maximum allowed of 10. // -// * ProvisionedThroughputExceededException -// Your request rate is too high. The AWS SDKs for DynamoDB automatically retry -// requests that receive this exception. Your request is eventually successful, -// unless your retry queue is too large to finish. Reduce the frequency of requests -// and use exponential backoff. For more information, go to Error Retries and -// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ErrorHandling.html#APIRetries) -// in the Amazon DynamoDB Developer Guide. +// Also, for tables with secondary indexes, only one of those tables can be +// in the CREATING state at any point in time. Do not attempt to create more +// than one such table simultaneously. +// +// The total limit of tables in the ACTIVE state is 250. // -// * ResourceNotFoundException +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" // The operation tried to access a nonexistent table or index. The resource // might not be specified correctly, or its status might not be ACTIVE. // -// * ItemCollectionSizeLimitExceededException +// * ErrCodeInternalServerError "InternalServerError" +// An error occurred on the server side. +// +// * ErrCodeResourceInUseException "ResourceInUseException" +// The operation conflicts with the resource's availability. For example, you +// attempted to recreate an existing table, or tried to delete a table currently +// in the CREATING state. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/TagResource +func (c *DynamoDB) TagResource(input *TagResourceInput) (*TagResourceOutput, error) { + req, out := c.TagResourceRequest(input) + return out, req.Send() +} + +// TagResourceWithContext is the same as TagResource with the addition of +// the ability to pass a context and additional request options. +// +// See TagResource for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) TagResourceWithContext(ctx aws.Context, input *TagResourceInput, opts ...request.Option) (*TagResourceOutput, error) { + req, out := c.TagResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUntagResource = "UntagResource" + +// UntagResourceRequest generates a "aws/request.Request" representing the +// client's request for the UntagResource operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UntagResource for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UntagResource method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UntagResourceRequest method. +// req, resp := client.UntagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UntagResource +func (c *DynamoDB) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) { + op := &request.Operation{ + Name: opUntagResource, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UntagResourceInput{} + } + + output = &UntagResourceOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + return +} + +// UntagResource API operation for Amazon DynamoDB. +// +// Removes the association of tags from an Amazon DynamoDB resource. You can +// call UntagResource up to 5 times per second, per account. +// +// For an overview on tagging DynamoDB resources, see Tagging for DynamoDB (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tagging.html) +// in the Amazon DynamoDB Developer Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon DynamoDB's +// API operation UntagResource for usage and error information. +// +// Returned Error Codes: +// * ErrCodeLimitExceededException "LimitExceededException" +// The number of concurrent table requests (cumulative number of tables in the +// CREATING, DELETING or UPDATING state) exceeds the maximum allowed of 10. +// +// Also, for tables with secondary indexes, only one of those tables can be +// in the CREATING state at any point in time. Do not attempt to create more +// than one such table simultaneously. +// +// The total limit of tables in the ACTIVE state is 250. +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// The operation tried to access a nonexistent table or index. The resource +// might not be specified correctly, or its status might not be ACTIVE. +// +// * ErrCodeInternalServerError "InternalServerError" +// An error occurred on the server side. +// +// * ErrCodeResourceInUseException "ResourceInUseException" +// The operation conflicts with the resource's availability. For example, you +// attempted to recreate an existing table, or tried to delete a table currently +// in the CREATING state. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UntagResource +func (c *DynamoDB) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) { + req, out := c.UntagResourceRequest(input) + return out, req.Send() +} + +// UntagResourceWithContext is the same as UntagResource with the addition of +// the ability to pass a context and additional request options. +// +// See UntagResource for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) UntagResourceWithContext(ctx aws.Context, input *UntagResourceInput, opts ...request.Option) (*UntagResourceOutput, error) { + req, out := c.UntagResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateItem = "UpdateItem" + +// UpdateItemRequest generates a "aws/request.Request" representing the +// client's request for the UpdateItem operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UpdateItem for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UpdateItem method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UpdateItemRequest method. +// req, resp := client.UpdateItemRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateItem +func (c *DynamoDB) UpdateItemRequest(input *UpdateItemInput) (req *request.Request, output *UpdateItemOutput) { + op := &request.Operation{ + Name: opUpdateItem, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateItemInput{} + } + + output = &UpdateItemOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateItem API operation for Amazon DynamoDB. +// +// Edits an existing item's attributes, or adds a new item to the table if it +// does not already exist. You can put, delete, or add attribute values. You +// can also perform a conditional update on an existing item (insert a new attribute +// name-value pair if it doesn't exist, or replace an existing name-value pair +// if it has certain expected attribute values). +// +// You can also return the item's attribute values in the same UpdateItem operation +// using the ReturnValues parameter. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon DynamoDB's +// API operation UpdateItem for usage and error information. +// +// Returned Error Codes: +// * ErrCodeConditionalCheckFailedException "ConditionalCheckFailedException" +// A condition specified in the operation could not be evaluated. +// +// * ErrCodeProvisionedThroughputExceededException "ProvisionedThroughputExceededException" +// Your request rate is too high. The AWS SDKs for DynamoDB automatically retry +// requests that receive this exception. Your request is eventually successful, +// unless your retry queue is too large to finish. Reduce the frequency of requests +// and use exponential backoff. For more information, go to Error Retries and +// Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff) +// in the Amazon DynamoDB Developer Guide. +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// The operation tried to access a nonexistent table or index. The resource +// might not be specified correctly, or its status might not be ACTIVE. +// +// * ErrCodeItemCollectionSizeLimitExceededException "ItemCollectionSizeLimitExceededException" // An item collection is too large. This exception is only returned for tables // that have one or more local secondary indexes. // -// * InternalServerError +// * ErrCodeInternalServerError "InternalServerError" // An error occurred on the server side. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateItem func (c *DynamoDB) UpdateItem(input *UpdateItemInput) (*UpdateItemOutput, error) { req, out := c.UpdateItemRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateItemWithContext is the same as UpdateItem with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateItem for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) UpdateItemWithContext(ctx aws.Context, input *UpdateItemInput, opts ...request.Option) (*UpdateItemOutput, error) { + req, out := c.UpdateItemRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateTable = "UpdateTable" @@ -1500,9 +2166,8 @@ func (c *DynamoDB) UpdateTableRequest(input *UpdateTableInput) (req *request.Req input = &UpdateTableInput{} } - req = c.newRequest(op, input, output) output = &UpdateTableOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1535,16 +2200,16 @@ func (c *DynamoDB) UpdateTableRequest(input *UpdateTableInput) (req *request.Req // API operation UpdateTable for usage and error information. // // Returned Error Codes: -// * ResourceInUseException +// * ErrCodeResourceInUseException "ResourceInUseException" // The operation conflicts with the resource's availability. For example, you // attempted to recreate an existing table, or tried to delete a table currently // in the CREATING state. // -// * ResourceNotFoundException +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" // The operation tried to access a nonexistent table or index. The resource // might not be specified correctly, or its status might not be ACTIVE. // -// * LimitExceededException +// * ErrCodeLimitExceededException "LimitExceededException" // The number of concurrent table requests (cumulative number of tables in the // CREATING, DELETING or UPDATING state) exceeds the maximum allowed of 10. // @@ -1554,14 +2219,155 @@ func (c *DynamoDB) UpdateTableRequest(input *UpdateTableInput) (req *request.Req // // The total limit of tables in the ACTIVE state is 250. // -// * InternalServerError +// * ErrCodeInternalServerError "InternalServerError" // An error occurred on the server side. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateTable func (c *DynamoDB) UpdateTable(input *UpdateTableInput) (*UpdateTableOutput, error) { req, out := c.UpdateTableRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateTableWithContext is the same as UpdateTable with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateTable for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) UpdateTableWithContext(ctx aws.Context, input *UpdateTableInput, opts ...request.Option) (*UpdateTableOutput, error) { + req, out := c.UpdateTableRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUpdateTimeToLive = "UpdateTimeToLive" + +// UpdateTimeToLiveRequest generates a "aws/request.Request" representing the +// client's request for the UpdateTimeToLive operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UpdateTimeToLive for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UpdateTimeToLive method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UpdateTimeToLiveRequest method. +// req, resp := client.UpdateTimeToLiveRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateTimeToLive +func (c *DynamoDB) UpdateTimeToLiveRequest(input *UpdateTimeToLiveInput) (req *request.Request, output *UpdateTimeToLiveOutput) { + op := &request.Operation{ + Name: opUpdateTimeToLive, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UpdateTimeToLiveInput{} + } + + output = &UpdateTimeToLiveOutput{} + req = c.newRequest(op, input, output) + return +} + +// UpdateTimeToLive API operation for Amazon DynamoDB. +// +// Specify the lifetime of individual table items. The database automatically +// removes the item at the expiration of the item. The UpdateTimeToLive method +// will enable or disable TTL for the specified table. A successful UpdateTimeToLive +// call returns the current TimeToLiveSpecification; it may take up to one hour +// for the change to fully process. +// +// TTL compares the current time in epoch time format to the time stored in +// the TTL attribute of an item. If the epoch time value stored in the attribute +// is less than the current time, the item is marked as expired and subsequently +// deleted. +// +// The epoch time format is the number of seconds elapsed since 12:00:00 AM +// January 1st, 1970 UTC. +// +// DynamoDB deletes expired items on a best-effort basis to ensure availability +// of throughput for other data operations. +// +// DynamoDB typically deletes expired items within two days of expiration. The +// exact duration within which an item gets deleted after expiration is specific +// to the nature of the workload. Items that have expired and not been deleted +// will still show up in reads, queries, and scans. +// +// As items are deleted, they are removed from any Local Secondary Index and +// Global Secondary Index immediately in the same eventually consistent way +// as a standard delete operation. +// +// For more information, see Time To Live (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html) +// in the Amazon DynamoDB Developer Guide. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for Amazon DynamoDB's +// API operation UpdateTimeToLive for usage and error information. +// +// Returned Error Codes: +// * ErrCodeResourceInUseException "ResourceInUseException" +// The operation conflicts with the resource's availability. For example, you +// attempted to recreate an existing table, or tried to delete a table currently +// in the CREATING state. +// +// * ErrCodeResourceNotFoundException "ResourceNotFoundException" +// The operation tried to access a nonexistent table or index. The resource +// might not be specified correctly, or its status might not be ACTIVE. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// The number of concurrent table requests (cumulative number of tables in the +// CREATING, DELETING or UPDATING state) exceeds the maximum allowed of 10. +// +// Also, for tables with secondary indexes, only one of those tables can be +// in the CREATING state at any point in time. Do not attempt to create more +// than one such table simultaneously. +// +// The total limit of tables in the ACTIVE state is 250. +// +// * ErrCodeInternalServerError "InternalServerError" +// An error occurred on the server side. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateTimeToLive +func (c *DynamoDB) UpdateTimeToLive(input *UpdateTimeToLiveInput) (*UpdateTimeToLiveOutput, error) { + req, out := c.UpdateTimeToLiveRequest(input) + return out, req.Send() +} + +// UpdateTimeToLiveWithContext is the same as UpdateTimeToLive with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateTimeToLive for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) UpdateTimeToLiveWithContext(ctx aws.Context, input *UpdateTimeToLiveInput, opts ...request.Option) (*UpdateTimeToLiveOutput, error) { + req, out := c.UpdateTimeToLiveRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Represents an attribute for describing the key schema for the table and indexes. @@ -1627,47 +2433,75 @@ func (s *AttributeDefinition) SetAttributeType(v string) *AttributeDefinition { return s } -// Represents the data for an attribute. You can set one, and only one, of the -// elements. +// Represents the data for an attribute. // -// Each attribute in an item is a name-value pair. An attribute can be single-valued -// or multi-valued set. For example, a book item can have title and authors -// attributes. Each book has one title but can have many authors. The multi-valued -// attribute is a set; duplicate values are not allowed. +// Each attribute value is described as a name-value pair. The name is the data +// type, and the value is the data itself. +// +// For more information, see Data Types (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes) +// in the Amazon DynamoDB Developer Guide. // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/AttributeValue type AttributeValue struct { _ struct{} `type:"structure"` - // A Binary data type. + // An attribute of type Binary. For example: + // + // "B": "dGhpcyB0ZXh0IGlzIGJhc2U2NC1lbmNvZGVk" // // B is automatically base64 encoded/decoded by the SDK. B []byte `type:"blob"` - // A Boolean data type. + // An attribute of type Boolean. For example: + // + // "BOOL": true BOOL *bool `type:"boolean"` - // A Binary Set data type. + // An attribute of type Binary Set. For example: + // + // "BS": ["U3Vubnk=", "UmFpbnk=", "U25vd3k="] BS [][]byte `type:"list"` - // A List of attribute values. + // An attribute of type List. For example: + // + // "L": ["Cookies", "Coffee", 3.14159] L []*AttributeValue `type:"list"` - // A Map of attribute values. + // An attribute of type Map. For example: + // + // "M": {"Name": {"S": "Joe"}, "Age": {"N": "35"}} M map[string]*AttributeValue `type:"map"` - // A Number data type. + // An attribute of type Number. For example: + // + // "N": "123.45" + // + // Numbers are sent across the network to DynamoDB as strings, to maximize compatibility + // across languages and libraries. However, DynamoDB treats them as number type + // attributes for mathematical operations. N *string `type:"string"` - // A Number Set data type. + // An attribute of type Number Set. For example: + // + // "NS": ["42.2", "-19", "7.5", "3.14"] + // + // Numbers are sent across the network to DynamoDB as strings, to maximize compatibility + // across languages and libraries. However, DynamoDB treats them as number type + // attributes for mathematical operations. NS []*string `type:"list"` - // A Null data type. + // An attribute of type Null. For example: + // + // "NULL": true NULL *bool `type:"boolean"` - // A String data type. + // An attribute of type String. For example: + // + // "S": "Hello" S *string `type:"string"` - // A String Set data type. + // An attribute of type String Set. For example: + // + // "SS": ["Giraffe", "Hippo" ,"Zebra"] SS []*string `type:"list"` } @@ -1820,13 +2654,13 @@ type AttributeValueUpdate struct { // are number and number set; no other data types can be specified. Action *string `type:"string" enum:"AttributeAction"` - // Represents the data for an attribute. You can set one, and only one, of the - // elements. + // Represents the data for an attribute. // - // Each attribute in an item is a name-value pair. An attribute can be single-valued - // or multi-valued set. For example, a book item can have title and authors - // attributes. Each book has one title but can have many authors. The multi-valued - // attribute is a set; duplicate values are not allowed. + // Each attribute value is described as a name-value pair. The name is the data + // type, and the value is the data itself. + // + // For more information, see Data TYpes (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes) + // in the Amazon DynamoDB Developer Guide. Value *AttributeValue `type:"structure"` } @@ -1920,23 +2754,9 @@ type BatchGetItemInput struct { // For more information, see Accessing Item Attributes (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html) // in the Amazon DynamoDB Developer Guide. // - // * AttributesToGet - - // - // This is a legacy parameter, for backward compatibility. New applications - // should use ProjectionExpression instead. Do not combine legacy parameters - // and expression parameters in a single API call; otherwise, DynamoDB will - // return a ValidationException exception. - // - // This parameter allows you to retrieve attributes of type List or Map; however, - // it cannot retrieve individual elements within a List or a Map. - // - // The names of one or more attributes to retrieve. If no attribute names are - // provided, then all attributes will be returned. If any of the requested - // attributes are not found, they will not appear in the result. - // - // Note that AttributesToGet has no effect on provisioned throughput consumption. - // DynamoDB determines capacity units consumed based on item size, not on - // the amount of data that is returned to an application. + // * AttributesToGet - This is a legacy parameter. Use ProjectionExpression + // instead. For more information, see AttributesToGet (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.AttributesToGet.html) + // in the Amazon DynamoDB Developer Guide. // // RequestItems is a required field RequestItems map[string]*KeysAndAttributes `min:"1" type:"map" required:"true"` @@ -2012,7 +2832,7 @@ func (s *BatchGetItemInput) SetReturnConsumedCapacity(v string) *BatchGetItemInp type BatchGetItemOutput struct { _ struct{} `type:"structure"` - // The read capacity units consumed by the operation. + // The read capacity units consumed by the entire BatchGetItem operation. // // Each element consists of: // @@ -2036,9 +2856,9 @@ type BatchGetItemOutput struct { // * Keys - An array of primary key attribute values that define specific // items in the table. // - // * AttributesToGet - One or more attributes to be retrieved from the table - // or index. By default, all attributes are returned. If a requested attribute - // is not found, it does not appear in the result. + // * ProjectionExpression - One or more attributes to be retrieved from the + // table or index. By default, all attributes are returned. If a requested + // attribute is not found, it does not appear in the result. // // * ConsistentRead - The consistency of a read operation. If set to true, // then a strongly consistent read is used; otherwise, an eventually consistent @@ -2185,7 +3005,7 @@ func (s *BatchWriteItemInput) SetReturnItemCollectionMetrics(v string) *BatchWri type BatchWriteItemOutput struct { _ struct{} `type:"structure"` - // The capacity units consumed by the operation. + // The capacity units consumed by the entire BatchWriteItem operation. // // Each element consists of: // @@ -2342,7 +3162,8 @@ type Condition struct { // // The following are descriptions of each comparison operator. // - // * EQ : Equal. EQ is supported for all datatypes, including lists and maps. + // * EQ : Equal. EQ is supported for all data types, including lists and + // maps. // // AttributeValueList can contain only one AttributeValue element of type String, // Number, Binary, String Set, Number Set, or Binary Set. If an item contains @@ -2350,8 +3171,8 @@ type Condition struct { // the request, the value does not match. For example, {"S":"6"} does not // equal {"N":"6"}. Also, {"N":"6"} does not equal {"NS":["6", "2", "1"]}. // - // * NE : Not equal. NE is supported for all datatypes, including lists and - // maps. + // * NE : Not equal. NE is supported for all data types, including lists + // and maps. // // * AttributeValueList can contain only one AttributeValue of type String, // Number, Binary, String Set, Number Set, or Binary Set. If an item contains @@ -2500,8 +3321,8 @@ type CreateGlobalSecondaryIndexAction struct { // Projection is a required field Projection *Projection `type:"structure" required:"true"` - // Represents the provisioned throughput settings for a specified table or index. - // The settings can be modified using the UpdateTable operation. + // Represents the provisioned throughput settings for the specified global secondary + // index. // // For current minimum and maximum provisioned throughput values, see Limits // (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html) @@ -2874,7 +3695,7 @@ func (s *CreateTableInput) SetTableName(v string) *CreateTableInput { type CreateTableOutput struct { _ struct{} `type:"structure"` - // Represents the properties of a table. + // Represents the properties of the table. TableDescription *TableDescription `type:"structure"` } @@ -2952,146 +3773,23 @@ type DeleteItemInput struct { // // These function names are case-sensitive. // - // * Comparison operators: = | <> | < | > | <= - // | >= | BETWEEN | IN + // * Comparison operators: = | <> | < | > | <= | >= | BETWEEN | IN // // * Logical operators: AND | OR | NOT // // For more information on condition expressions, see Specifying Conditions // (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html) // in the Amazon DynamoDB Developer Guide. - // - // ConditionExpression replaces the legacy ConditionalOperator and Expected - // parameters. ConditionExpression *string `type:"string"` - // This is a legacy parameter, for backward compatibility. New applications - // should use ConditionExpression instead. Do not combine legacy parameters - // and expression parameters in a single API call; otherwise, DynamoDB will - // return a ValidationException exception. - // - // A logical operator to apply to the conditions in the Expected map: - // - // * AND - If all of the conditions evaluate to true, then the entire map - // evaluates to true. - // - // * OR - If at least one of the conditions evaluate to true, then the entire - // map evaluates to true. - // - // If you omit ConditionalOperator, then AND is the default. - // - // The operation will succeed only if the entire map evaluates to true. - // - // This parameter does not support attributes of type List or Map. + // This is a legacy parameter. Use ConditionExpression instead. For more information, + // see ConditionalOperator (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.ConditionalOperator.html) + // in the Amazon DynamoDB Developer Guide. ConditionalOperator *string `type:"string" enum:"ConditionalOperator"` - // This is a legacy parameter, for backward compatibility. New applications - // should use ConditionExpression instead. Do not combine legacy parameters - // and expression parameters in a single API call; otherwise, DynamoDB will - // return a ValidationException exception. - // - // A map of attribute/condition pairs. Expected provides a conditional block - // for the DeleteItem operation. - // - // Each element of Expected consists of an attribute name, a comparison operator, - // and one or more values. DynamoDB compares the attribute with the value(s) - // you supplied, using the comparison operator. For each Expected element, the - // result of the evaluation is either true or false. - // - // If you specify more than one element in the Expected map, then by default - // all of the conditions must evaluate to true. In other words, the conditions - // are ANDed together. (You can use the ConditionalOperator parameter to OR - // the conditions instead. If you do this, then at least one of the conditions - // must evaluate to true, rather than all of them.) - // - // If the Expected map evaluates to true, then the conditional operation succeeds; - // otherwise, it fails. - // - // Expected contains the following: - // - // * AttributeValueList - One or more values to evaluate against the supplied - // attribute. The number of values in the list depends on the ComparisonOperator - // being used. - // - // For type Number, value comparisons are numeric. - // - // String value comparisons for greater than, equals, or less than are based - // on ASCII character code values. For example, a is greater than A, and - // a is greater than B. For a list of code values, see http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters - // (http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters). - // - // For type Binary, DynamoDB treats each byte of the binary data as unsigned - // when it compares binary values. - // - // * ComparisonOperator - A comparator for evaluating attributes in the AttributeValueList. - // When performing the comparison, DynamoDB uses strongly consistent reads. - // - // The following comparison operators are available: - // - // EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | - // BEGINS_WITH | IN | BETWEEN - // - // The following are descriptions of each comparison operator. - // - // EQ : Equal. EQ is supported for all datatypes, including lists and maps. - // - // AttributeValueList can contain only one AttributeValue element of type String, - // Number, Binary, String Set, Number Set, or Binary Set. If an item contains - // an AttributeValue element of a different type than the one provided in - // the request, the value does not match. For example, {"S":"6"} does not - // equal {"N":"6"}. Also, {"N":"6"} does not equal {"NS":["6", "2", "1"]}. - // - // NE : Not equal. NE is supported for all datatypes, including lists and maps. - // - // AttributeValueList can contain only one AttributeValue of type String, Number, - // Binary, String Set, Number Set, or Binary Set. If an item contains an - // AttributeValue of a different type than the one provided in the request, - // the value does not match. For example, {"S":"6"} does not equal {"N":"6"}. - // Also, {"N":"6"} does not equal {"NS":["6", "2", "1"]}. - // - // * LE : Less than or equal. - // - // AttributeValueList can contain only one AttributeValue element of type String, - // Number, or Binary (not a set type). If an item contains an AttributeValue - // element of a different type than the one provided in the request, the - // value does not match. For example, {"S":"6"} does not equal {"N":"6"}. - // Also, {"N":"6"} does not compare to {"NS":["6", "2", "1"]}. - // - // * LT : Less than. - // - // * AttributeValueList can contain only one AttributeValue of type String, - // Number, or Binary (not a set type). If an item contains an AttributeValue - // element of a different type than the one provided in the request, the - // value does not match. For example, {"S":"6"} does not equal {"N":"6"}. - // Also, {"N":"6"} does not compare to {"NS":["6", "2", "1"]}. - // - // * GE : Greater than or equal. - // - // AttributeValueList can contain only one AttributeValue element of type String, - // Number, or Binary (not a set type). If an item contains an AttributeValue - // element of a different type than the one provided in the request, the value - // does not match. For example, {"S":"6"} does not equal {"N":"6"}. Also, {"N":"6"} - // does not compare to {"NS":["6", "2", "1"]}. - // - // GT: Greater than. - // - // AttributeValueListcan contain only one AttributeValueelement of type String, Number, or Binary (not a set type). If an item contains - // an AttributeValueelement of a different type than the one provided in the request, the value - // does not match. For example, {"S":"6"}does not equal {"N":"6"}. Also, {"N":"6"}does not compare to {"NS":["6", "2", "1"]}. - // - // NOT_NULL - // : The attribute exists. NOT_NULL - // is supported for all datatypes, including lists and maps. - // - // This operator tests for the existence of an attribute, not its data type. - // If the data type of attribute "a" is null, and you evaluate it using NOT_NULL, the result is a Boolean true. This result is because the attribute "a" exists; its data type is not relevant to the NOT_NULLcomparison operator. - // - // NULL - // : The attribute does not exist. NULL - // is supported for all datatypes, including lists and maps. - // - // This operator tests for the nonexistence of an attribute, not its data type. - // If the data type of attribute "a" is null, and you evaluate it using NULL, the result is a Boolean false. This is because the attribute "a" exists; its data type is not relevant to the NULL + // This is a legacy parameter. Use ConditionExpresssion instead. For more information, + // see Expected (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.Expected.html) + // in the Amazon DynamoDB Developer Guide. Expected map[string]*ExpectedAttributeValue `type:"map"` // One or more substitution tokens for attribute names in an expression. The @@ -3304,18 +4002,18 @@ type DeleteItemOutput struct { // only if ReturnValues was specified as ALL_OLD in the request. Attributes map[string]*AttributeValue `type:"map"` - // The capacity units consumed by an operation. The data returned includes the - // total provisioned throughput consumed, along with statistics for the table - // and any indexes involved in the operation. ConsumedCapacity is only returned - // if the request asked for it. For more information, see Provisioned Throughput - // (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ProvisionedThroughputIntro.html) + // The capacity units consumed by the DeleteItem operation. The data returned + // includes the total provisioned throughput consumed, along with statistics + // for the table and any indexes involved in the operation. ConsumedCapacity + // is only returned if the ReturnConsumedCapacity parameter was specified. For + // more information, see Provisioned Throughput (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ProvisionedThroughputIntro.html) // in the Amazon DynamoDB Developer Guide. ConsumedCapacity *ConsumedCapacity `type:"structure"` - // Information about item collections, if any, that were affected by the operation. - // ItemCollectionMetrics is only returned if the request asked for it. If the - // table does not have any local secondary indexes, this information is not - // returned in the response. + // Information about item collections, if any, that were affected by the DeleteItem + // operation. ItemCollectionMetrics is only returned if the ReturnItemCollectionMetrics + // parameter was specified. If the table does not have any local secondary indexes, + // this information is not returned in the response. // // Each ItemCollectionMetrics element consists of: // @@ -3581,7 +4279,7 @@ func (s *DescribeTableInput) SetTableName(v string) *DescribeTableInput { type DescribeTableOutput struct { _ struct{} `type:"structure"` - // Represents the properties of a table. + // The properties of the table. Table *TableDescription `type:"structure"` } @@ -3601,6 +4299,71 @@ func (s *DescribeTableOutput) SetTable(v *TableDescription) *DescribeTableOutput return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeTimeToLiveInput +type DescribeTimeToLiveInput struct { + _ struct{} `type:"structure"` + + // The name of the table to be described. + // + // TableName is a required field + TableName *string `min:"3" type:"string" required:"true"` +} + +// String returns the string representation +func (s DescribeTimeToLiveInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeTimeToLiveInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeTimeToLiveInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeTimeToLiveInput"} + if s.TableName == nil { + invalidParams.Add(request.NewErrParamRequired("TableName")) + } + if s.TableName != nil && len(*s.TableName) < 3 { + invalidParams.Add(request.NewErrParamMinLen("TableName", 3)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetTableName sets the TableName field's value. +func (s *DescribeTimeToLiveInput) SetTableName(v string) *DescribeTimeToLiveInput { + s.TableName = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeTimeToLiveOutput +type DescribeTimeToLiveOutput struct { + _ struct{} `type:"structure"` + + TimeToLiveDescription *TimeToLiveDescription `type:"structure"` +} + +// String returns the string representation +func (s DescribeTimeToLiveOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeTimeToLiveOutput) GoString() string { + return s.String() +} + +// SetTimeToLiveDescription sets the TimeToLiveDescription field's value. +func (s *DescribeTimeToLiveOutput) SetTimeToLiveDescription(v *TimeToLiveDescription) *DescribeTimeToLiveOutput { + s.TimeToLiveDescription = v + return s +} + // Represents a condition to be compared with an attribute value. This condition // can be used with DeleteItem, PutItem or UpdateItem operations; if the comparison // evaluates to true, the operation succeeds; if not, the operation fails. You @@ -3652,7 +4415,8 @@ type ExpectedAttributeValue struct { // // The following are descriptions of each comparison operator. // - // * EQ : Equal. EQ is supported for all datatypes, including lists and maps. + // * EQ : Equal. EQ is supported for all data types, including lists and + // maps. // // AttributeValueList can contain only one AttributeValue element of type String, // Number, Binary, String Set, Number Set, or Binary Set. If an item contains @@ -3660,8 +4424,8 @@ type ExpectedAttributeValue struct { // the request, the value does not match. For example, {"S":"6"} does not // equal {"N":"6"}. Also, {"N":"6"} does not equal {"NS":["6", "2", "1"]}. // - // * NE : Not equal. NE is supported for all datatypes, including lists and - // maps. + // * NE : Not equal. NE is supported for all data types, including lists + // and maps. // // * AttributeValueList can contain only one AttributeValue of type String, // Number, Binary, String Set, Number Set, or Binary Set. If an item contains @@ -3708,13 +4472,13 @@ type ExpectedAttributeValue struct { // attribute to have a value, while also expecting it not to exist.) Exists *bool `type:"boolean"` - // Represents the data for an attribute. You can set one, and only one, of the - // elements. + // Represents the data for the expected attribute. // - // Each attribute in an item is a name-value pair. An attribute can be single-valued - // or multi-valued set. For example, a book item can have title and authors - // attributes. Each book has one title but can have many authors. The multi-valued - // attribute is a set; duplicate values are not allowed. + // Each attribute value is described as a name-value pair. The name is the data + // type, and the value is the data itself. + // + // For more information, see Data Types (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes) + // in the Amazon DynamoDB Developer Guide. Value *AttributeValue `type:"structure"` } @@ -3757,21 +4521,9 @@ func (s *ExpectedAttributeValue) SetValue(v *AttributeValue) *ExpectedAttributeV type GetItemInput struct { _ struct{} `type:"structure"` - // This is a legacy parameter, for backward compatibility. New applications - // should use ProjectionExpression instead. Do not combine legacy parameters - // and expression parameters in a single API call; otherwise, DynamoDB will - // return a ValidationException exception. - // - // This parameter allows you to retrieve attributes of type List or Map; however, - // it cannot retrieve individual elements within a List or a Map. - // - // The names of one or more attributes to retrieve. If no attribute names are - // provided, then all attributes will be returned. If any of the requested attributes - // are not found, they will not appear in the result. - // - // Note that AttributesToGet has no effect on provisioned throughput consumption. - // DynamoDB determines capacity units consumed based on item size, not on the - // amount of data that is returned to an application. + // This is a legacy parameter. Use ProjectionExpression instead. For more information, + // see AttributesToGet (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.AttributesToGet.html) + // in the Amazon DynamoDB Developer Guide. AttributesToGet []*string `min:"1" type:"list"` // Determines the read consistency model: If set to true, then the operation @@ -3837,8 +4589,6 @@ type GetItemInput struct { // // For more information, see Accessing Item Attributes (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html) // in the Amazon DynamoDB Developer Guide. - // - // ProjectionExpression replaces the legacy AttributesToGet parameter. ProjectionExpression *string `type:"string"` // Determines the level of detail about provisioned throughput consumption that @@ -3943,15 +4693,15 @@ func (s *GetItemInput) SetTableName(v string) *GetItemInput { type GetItemOutput struct { _ struct{} `type:"structure"` - // The capacity units consumed by an operation. The data returned includes the - // total provisioned throughput consumed, along with statistics for the table - // and any indexes involved in the operation. ConsumedCapacity is only returned - // if the request asked for it. For more information, see Provisioned Throughput - // (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ProvisionedThroughputIntro.html) + // The capacity units consumed by the GetItem operation. The data returned includes + // the total provisioned throughput consumed, along with statistics for the + // table and any indexes involved in the operation. ConsumedCapacity is only + // returned if the ReturnConsumedCapacity parameter was specified. For more + // information, see Provisioned Throughput (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ProvisionedThroughputIntro.html) // in the Amazon DynamoDB Developer Guide. ConsumedCapacity *ConsumedCapacity `type:"structure"` - // A map of attribute names to AttributeValue objects, as specified by AttributesToGet. + // A map of attribute names to AttributeValue objects, as specified by ProjectionExpression. Item map[string]*AttributeValue `type:"map"` } @@ -4007,15 +4757,15 @@ type GlobalSecondaryIndex struct { // KeySchema is a required field KeySchema []*KeySchemaElement `min:"1" type:"list" required:"true"` - // Represents attributes that are copied (projected) from the table into an - // index. These are in addition to the primary key attributes and index key - // attributes, which are automatically projected. + // Represents attributes that are copied (projected) from the table into the + // global secondary index. These are in addition to the primary key attributes + // and index key attributes, which are automatically projected. // // Projection is a required field Projection *Projection `type:"structure" required:"true"` - // Represents the provisioned throughput settings for a specified table or index. - // The settings can be modified using the UpdateTable operation. + // Represents the provisioned throughput settings for the specified global secondary + // index. // // For current minimum and maximum provisioned throughput values, see Limits // (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html) @@ -4166,13 +4916,17 @@ type GlobalSecondaryIndexDescription struct { // key physically close together, in sorted order by the sort key value. KeySchema []*KeySchemaElement `min:"1" type:"list"` - // Represents attributes that are copied (projected) from the table into an - // index. These are in addition to the primary key attributes and index key - // attributes, which are automatically projected. + // Represents attributes that are copied (projected) from the table into the + // global secondary index. These are in addition to the primary key attributes + // and index key attributes, which are automatically projected. Projection *Projection `type:"structure"` - // Represents the provisioned throughput settings for the table, consisting - // of read and write capacity units, along with data about increases and decreases. + // Represents the provisioned throughput settings for the specified global secondary + // index. + // + // For current minimum and maximum provisioned throughput values, see Limits + // (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html) + // in the Amazon DynamoDB Developer Guide. ProvisionedThroughput *ProvisionedThroughputDescription `type:"structure"` } @@ -4464,9 +5218,9 @@ func (s *KeySchemaElement) SetKeyType(v string) *KeySchemaElement { type KeysAndAttributes struct { _ struct{} `type:"structure"` - // One or more attributes to retrieve from the table or index. If no attribute - // names are specified then all attributes will be returned. If any of the specified - // attributes are not found, they will not appear in the result. + // This is a legacy parameter. Use ProjectionExpression instead. For more information, + // see Legacy Conditional Parameters (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.html) + // in the Amazon DynamoDB Developer Guide. AttributesToGet []*string `min:"1" type:"list"` // The consistency of a read operation. If set to true, then a strongly consistent @@ -4526,8 +5280,6 @@ type KeysAndAttributes struct { // // For more information, see Accessing Item Attributes (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html) // in the Amazon DynamoDB Developer Guide. - // - // ProjectionExpression replaces the legacy AttributesToGet parameter. ProjectionExpression *string `type:"string"` } @@ -4687,6 +5439,95 @@ func (s *ListTablesOutput) SetTableNames(v []*string) *ListTablesOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ListTagsOfResourceInput +type ListTagsOfResourceInput struct { + _ struct{} `type:"structure"` + + // An optional string that, if supplied, must be copied from the output of a + // previous call to ListTagOfResource. When provided in this manner, this API + // fetches the next page of results. + NextToken *string `type:"string"` + + // The Amazon DynamoDB resource with tags to be listed. This value is an Amazon + // Resource Name (ARN). + // + // ResourceArn is a required field + ResourceArn *string `min:"1" type:"string" required:"true"` +} + +// String returns the string representation +func (s ListTagsOfResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListTagsOfResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListTagsOfResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListTagsOfResourceInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetNextToken sets the NextToken field's value. +func (s *ListTagsOfResourceInput) SetNextToken(v string) *ListTagsOfResourceInput { + s.NextToken = &v + return s +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *ListTagsOfResourceInput) SetResourceArn(v string) *ListTagsOfResourceInput { + s.ResourceArn = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/ListTagsOfResourceOutput +type ListTagsOfResourceOutput struct { + _ struct{} `type:"structure"` + + // If this value is returned, there are additional results to be displayed. + // To retrieve them, call ListTagsOfResource again, with NextToken set to this + // value. + NextToken *string `type:"string"` + + // The tags currently associated with the Amazon DynamoDB resource. + Tags []*Tag `type:"list"` +} + +// String returns the string representation +func (s ListTagsOfResourceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListTagsOfResourceOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *ListTagsOfResourceOutput) SetNextToken(v string) *ListTagsOfResourceOutput { + s.NextToken = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *ListTagsOfResourceOutput) SetTags(v []*Tag) *ListTagsOfResourceOutput { + s.Tags = v + return s +} + // Represents the properties of a local secondary index. // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/LocalSecondaryIndex type LocalSecondaryIndex struct { @@ -4717,9 +5558,9 @@ type LocalSecondaryIndex struct { // KeySchema is a required field KeySchema []*KeySchemaElement `min:"1" type:"list" required:"true"` - // Represents attributes that are copied (projected) from the table into an - // index. These are in addition to the primary key attributes and index key - // attributes, which are automatically projected. + // Represents attributes that are copied (projected) from the table into the + // local secondary index. These are in addition to the primary key attributes + // and index key attributes, which are automatically projected. // // Projection is a required field Projection *Projection `type:"structure" required:"true"` @@ -4830,9 +5671,9 @@ type LocalSecondaryIndexDescription struct { // key physically close together, in sorted order by the sort key value. KeySchema []*KeySchemaElement `min:"1" type:"list"` - // Represents attributes that are copied (projected) from the table into an - // index. These are in addition to the primary key attributes and index key - // attributes, which are automatically projected. + // Represents attributes that are copied (projected) from the table into the + // global secondary index. These are in addition to the primary key attributes + // and index key attributes, which are automatically projected. Projection *Projection `type:"structure"` } @@ -5098,148 +5939,23 @@ type PutItemInput struct { // // These function names are case-sensitive. // - // * Comparison operators: = | <> | < | > | <= - // | >= | BETWEEN | IN + // * Comparison operators: = | <> | < | > | <= | >= | BETWEEN | IN // // * Logical operators: AND | OR | NOT // // For more information on condition expressions, see Specifying Conditions // (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html) // in the Amazon DynamoDB Developer Guide. - // - // ConditionExpression replaces the legacy ConditionalOperator and Expected - // parameters. ConditionExpression *string `type:"string"` - // This is a legacy parameter, for backward compatibility. New applications - // should use ConditionExpression instead. Do not combine legacy parameters - // and expression parameters in a single API call; otherwise, DynamoDB will - // return a ValidationException exception. - // - // A logical operator to apply to the conditions in the Expected map: - // - // * AND - If all of the conditions evaluate to true, then the entire map - // evaluates to true. - // - // * OR - If at least one of the conditions evaluate to true, then the entire - // map evaluates to true. - // - // If you omit ConditionalOperator, then AND is the default. - // - // The operation will succeed only if the entire map evaluates to true. - // - // This parameter does not support attributes of type List or Map. + // This is a legacy parameter. Use ConditionExpression instead. For more information, + // see ConditionalOperator (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.ConditionalOperator.html) + // in the Amazon DynamoDB Developer Guide. ConditionalOperator *string `type:"string" enum:"ConditionalOperator"` - // This is a legacy parameter, for backward compatibility. New applications - // should use ConditionExpression instead. Do not combine legacy parameters - // and expression parameters in a single API call; otherwise, DynamoDB will - // return a ValidationException exception. - // - // A map of attribute/condition pairs. Expected provides a conditional block - // for the PutItem operation. - // - // This parameter does not support attributes of type List or Map. - // - // Each element of Expected consists of an attribute name, a comparison operator, - // and one or more values. DynamoDB compares the attribute with the value(s) - // you supplied, using the comparison operator. For each Expected element, the - // result of the evaluation is either true or false. - // - // If you specify more than one element in the Expected map, then by default - // all of the conditions must evaluate to true. In other words, the conditions - // are ANDed together. (You can use the ConditionalOperator parameter to OR - // the conditions instead. If you do this, then at least one of the conditions - // must evaluate to true, rather than all of them.) - // - // If the Expected map evaluates to true, then the conditional operation succeeds; - // otherwise, it fails. - // - // Expected contains the following: - // - // * AttributeValueList - One or more values to evaluate against the supplied - // attribute. The number of values in the list depends on the ComparisonOperator - // being used. - // - // For type Number, value comparisons are numeric. - // - // String value comparisons for greater than, equals, or less than are based - // on ASCII character code values. For example, a is greater than A, and - // a is greater than B. For a list of code values, see http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters - // (http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters). - // - // For type Binary, DynamoDB treats each byte of the binary data as unsigned - // when it compares binary values. - // - // * ComparisonOperator - A comparator for evaluating attributes in the AttributeValueList. - // When performing the comparison, DynamoDB uses strongly consistent reads. - // - // The following comparison operators are available: - // - // EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | - // BEGINS_WITH | IN | BETWEEN - // - // The following are descriptions of each comparison operator. - // - // EQ : Equal. EQ is supported for all datatypes, including lists and maps. - // - // AttributeValueList can contain only one AttributeValue element of type String, - // Number, Binary, String Set, Number Set, or Binary Set. If an item contains - // an AttributeValue element of a different type than the one provided in - // the request, the value does not match. For example, {"S":"6"} does not - // equal {"N":"6"}. Also, {"N":"6"} does not equal {"NS":["6", "2", "1"]}. - // - // NE : Not equal. NE is supported for all datatypes, including lists and maps. - // - // AttributeValueList can contain only one AttributeValue of type String, Number, - // Binary, String Set, Number Set, or Binary Set. If an item contains an - // AttributeValue of a different type than the one provided in the request, - // the value does not match. For example, {"S":"6"} does not equal {"N":"6"}. - // Also, {"N":"6"} does not equal {"NS":["6", "2", "1"]}. - // - // * LE : Less than or equal. - // - // AttributeValueList can contain only one AttributeValue element of type String, - // Number, or Binary (not a set type). If an item contains an AttributeValue - // element of a different type than the one provided in the request, the - // value does not match. For example, {"S":"6"} does not equal {"N":"6"}. - // Also, {"N":"6"} does not compare to {"NS":["6", "2", "1"]}. - // - // * LT : Less than. - // - // * AttributeValueList can contain only one AttributeValue of type String, - // Number, or Binary (not a set type). If an item contains an AttributeValue - // element of a different type than the one provided in the request, the - // value does not match. For example, {"S":"6"} does not equal {"N":"6"}. - // Also, {"N":"6"} does not compare to {"NS":["6", "2", "1"]}. - // - // * GE : Greater than or equal. - // - // AttributeValueList can contain only one AttributeValue element of type String, - // Number, or Binary (not a set type). If an item contains an AttributeValue - // element of a different type than the one provided in the request, the value - // does not match. For example, {"S":"6"} does not equal {"N":"6"}. Also, {"N":"6"} - // does not compare to {"NS":["6", "2", "1"]}. - // - // GT: Greater than. - // - // AttributeValueListcan contain only one AttributeValueelement of type String, Number, or Binary (not a set type). If an item contains - // an AttributeValueelement of a different type than the one provided in the request, the value - // does not match. For example, {"S":"6"}does not equal {"N":"6"}. Also, {"N":"6"}does not compare to {"NS":["6", "2", "1"]}. - // - // NOT_NULL - // : The attribute exists. NOT_NULL - // is supported for all datatypes, including lists and maps. - // - // This operator tests for the existence of an attribute, not its data type. - // If the data type of attribute "a" is null, and you evaluate it using NOT_NULL, the result is a Boolean true. This result is because the attribute "a" exists; its data type is not relevant to the NOT_NULLcomparison operator. - // - // NULL - // : The attribute does not exist. NULL - // is supported for all datatypes, including lists and maps. - // - // This operator tests for the nonexistence of an attribute, not its data type. - // If the data type of attribute "a" is null, and you evaluate it using NULL, the result is a Boolean false. This is because the attribute "a" exists; its data type is not relevant to the NULL + // This is a legacy parameter. Use ConditionExpresssion instead. For more information, + // see Expected (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.Expected.html) + // in the Amazon DynamoDB Developer Guide. Expected map[string]*ExpectedAttributeValue `type:"map"` // One or more substitution tokens for attribute names in an expression. The @@ -5464,18 +6180,18 @@ type PutItemOutput struct { // of an attribute name and an attribute value. Attributes map[string]*AttributeValue `type:"map"` - // The capacity units consumed by an operation. The data returned includes the - // total provisioned throughput consumed, along with statistics for the table - // and any indexes involved in the operation. ConsumedCapacity is only returned - // if the request asked for it. For more information, see Provisioned Throughput - // (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ProvisionedThroughputIntro.html) + // The capacity units consumed by the PutItem operation. The data returned includes + // the total provisioned throughput consumed, along with statistics for the + // table and any indexes involved in the operation. ConsumedCapacity is only + // returned if the ReturnConsumedCapacity parameter was specified. For more + // information, see Provisioned Throughput (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ProvisionedThroughputIntro.html) // in the Amazon DynamoDB Developer Guide. ConsumedCapacity *ConsumedCapacity `type:"structure"` - // Information about item collections, if any, that were affected by the operation. - // ItemCollectionMetrics is only returned if the request asked for it. If the - // table does not have any local secondary indexes, this information is not - // returned in the response. + // Information about item collections, if any, that were affected by the PutItem + // operation. ItemCollectionMetrics is only returned if the ReturnItemCollectionMetrics + // parameter was specified. If the table does not have any local secondary indexes, + // this information is not returned in the response. // // Each ItemCollectionMetrics element consists of: // @@ -5558,56 +6274,14 @@ func (s *PutRequest) SetItem(v map[string]*AttributeValue) *PutRequest { type QueryInput struct { _ struct{} `type:"structure"` - // This is a legacy parameter, for backward compatibility. New applications - // should use ProjectionExpression instead. Do not combine legacy parameters - // and expression parameters in a single API call; otherwise, DynamoDB will - // return a ValidationException exception. - // - // This parameter allows you to retrieve attributes of type List or Map; however, - // it cannot retrieve individual elements within a List or a Map. - // - // The names of one or more attributes to retrieve. If no attribute names are - // provided, then all attributes will be returned. If any of the requested attributes - // are not found, they will not appear in the result. - // - // Note that AttributesToGet has no effect on provisioned throughput consumption. - // DynamoDB determines capacity units consumed based on item size, not on the - // amount of data that is returned to an application. - // - // You cannot use both AttributesToGet and Select together in a Query request, - // unless the value for Select is SPECIFIC_ATTRIBUTES. (This usage is equivalent - // to specifying AttributesToGet without any value for Select.) - // - // If you query a local secondary index and request only attributes that are - // projected into that index, the operation will read only the index and not - // the table. If any of the requested attributes are not projected into the - // local secondary index, DynamoDB will fetch each of these attributes from - // the parent table. This extra fetching incurs additional throughput cost and - // latency. - // - // If you query a global secondary index, you can only request attributes that - // are projected into the index. Global secondary index queries cannot fetch - // attributes from the parent table. + // This is a legacy parameter. Use ProjectionExpression instead. For more information, + // see AttributesToGet (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.AttributesToGet.html) + // in the Amazon DynamoDB Developer Guide. AttributesToGet []*string `min:"1" type:"list"` - // This is a legacy parameter, for backward compatibility. New applications - // should use FilterExpression instead. Do not combine legacy parameters and - // expression parameters in a single API call; otherwise, DynamoDB will return - // a ValidationException exception. - // - // A logical operator to apply to the conditions in a QueryFilter map: - // - // * AND - If all of the conditions evaluate to true, then the entire map - // evaluates to true. - // - // * OR - If at least one of the conditions evaluate to true, then the entire - // map evaluates to true. - // - // If you omit ConditionalOperator, then AND is the default. - // - // The operation will succeed only if the entire map evaluates to true. - // - // This parameter does not support attributes of type List or Map. + // This is a legacy parameter. Use FilterExpression instead. For more information, + // see ConditionalOperator (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.ConditionalOperator.html) + // in the Amazon DynamoDB Developer Guide. ConditionalOperator *string `type:"string" enum:"ConditionalOperator"` // Determines the read consistency model: If set to true, then the operation @@ -5689,14 +6363,14 @@ type QueryInput struct { // but before the data is returned to you. Items that do not satisfy the FilterExpression // criteria are not returned. // + // A FilterExpression does not allow key attributes. You cannot define a filter + // expression based on a partition key or a sort key. + // // A FilterExpression is applied after the items have already been read; the // process of filtering does not consume any additional read capacity units. // // For more information, see Filter Expressions (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html#FilteringResults) // in the Amazon DynamoDB Developer Guide. - // - // FilterExpression replaces the legacy QueryFilter and ConditionalOperator - // parameters. FilterExpression *string `type:"string"` // The name of an index to query. This index can be any local secondary index @@ -5770,98 +6444,11 @@ type QueryInput struct { // For more information on ExpressionAttributeNames and ExpressionAttributeValues, // see Using Placeholders for Attribute Names and Values (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ExpressionPlaceholders.html) // in the Amazon DynamoDB Developer Guide. - // - // KeyConditionExpression replaces the legacy KeyConditions parameter. KeyConditionExpression *string `type:"string"` - // This is a legacy parameter, for backward compatibility. New applications - // should use KeyConditionExpression instead. Do not combine legacy parameters - // and expression parameters in a single API call; otherwise, DynamoDB will - // return a ValidationException exception. - // - // The selection criteria for the query. For a query on a table, you can have - // conditions only on the table primary key attributes. You must provide the - // partition key name and value as an EQ condition. You can optionally provide - // a second condition, referring to the sort key. - // - // If you don't provide a sort key condition, all of the items that match the - // partition key will be retrieved. If a FilterExpression or QueryFilter is - // present, it will be applied after the items are retrieved. - // - // For a query on an index, you can have conditions only on the index key attributes. - // You must provide the index partition key name and value as an EQ condition. - // You can optionally provide a second condition, referring to the index sort - // key. - // - // Each KeyConditions element consists of an attribute name to compare, along - // with the following: - // - // * AttributeValueList - One or more values to evaluate against the supplied - // attribute. The number of values in the list depends on the ComparisonOperator - // being used. - // - // For type Number, value comparisons are numeric. - // - // String value comparisons for greater than, equals, or less than are based - // on ASCII character code values. For example, a is greater than A, and - // a is greater than B. For a list of code values, see http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters - // (http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters). - // - // For Binary, DynamoDB treats each byte of the binary data as unsigned when - // it compares binary values. - // - // * ComparisonOperator - A comparator for evaluating attributes, for example, - // equals, greater than, less than, and so on. - // - // For KeyConditions, only the following comparison operators are supported: - // - // EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN - // - // The following are descriptions of these comparison operators. - // - // EQ : Equal. - // - // AttributeValueList can contain only one AttributeValue of type String, Number, - // or Binary (not a set type). If an item contains an AttributeValue element - // of a different type than the one specified in the request, the value does - // not match. For example, {"S":"6"} does not equal {"N":"6"}. Also, {"N":"6"} - // does not equal {"NS":["6", "2", "1"]}. - // - // LE : Less than or equal. - // - // AttributeValueList can contain only one AttributeValue element of type String, - // Number, or Binary (not a set type). If an item contains an AttributeValue - // element of a different type than the one provided in the request, the - // value does not match. For example, {"S":"6"} does not equal {"N":"6"}. - // Also, {"N":"6"} does not compare to {"NS":["6", "2", "1"]}. - // - // * LT : Less than. - // - // AttributeValueList can contain only one AttributeValue of type String, Number, - // or Binary (not a set type). If an item contains an AttributeValue element - // of a different type than the one provided in the request, the value does - // not match. For example, {"S":"6"} does not equal {"N":"6"}. Also, {"N":"6"} - // does not compare to {"NS":["6", "2", "1"]}. - // - // * GE : Greater than or equal. - // - // * AttributeValueList can contain only one AttributeValue element of type - // String, Number, or Binary (not a set type). If an item contains an AttributeValue - // element of a different type than the one provided in the request, the - // value does not match. For example, {"S":"6"} does not equal {"N":"6"}. - // Also, {"N":"6"} does not compare to {"NS":["6", "2", "1"]}. - // - // * GT : Greater than. - // - // AttributeValueList can contain only one AttributeValue element of type String, - // Number, or Binary (not a set type). If an item contains an AttributeValue - // element of a different type than the one provided in the request, the value - // does not match. For example, {"S":"6"} does not equal {"N":"6"}. Also, {"N":"6"} - // does not compare to {"NS":["6", "2", "1"]}. - // - // BEGINS_WITH: Checks for a prefix. - // - // AttributeValueListcan contain only one AttributeValue + // This is a legacy parameter. Use KeyConditionExpression instead. For more + // information, see KeyConditions (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.KeyConditions.html) + // in the Amazon DynamoDB Developer Guide. KeyConditions map[string]*Condition `type:"map"` // The maximum number of items to evaluate (not necessarily the number of matching @@ -5886,63 +6473,11 @@ type QueryInput struct { // // For more information, see Accessing Item Attributes (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html) // in the Amazon DynamoDB Developer Guide. - // - // ProjectionExpression replaces the legacy AttributesToGet parameter. ProjectionExpression *string `type:"string"` - // This is a legacy parameter, for backward compatibility. New applications - // should use FilterExpression instead. Do not combine legacy parameters and - // expression parameters in a single API call; otherwise, DynamoDB will return - // a ValidationException exception. - // - // A condition that evaluates the query results after the items are read and - // returns only the desired values. - // - // This parameter does not support attributes of type List or Map. - // - // A QueryFilter is applied after the items have already been read; the process - // of filtering does not consume any additional read capacity units. - // - // If you provide more than one condition in the QueryFilter map, then by default - // all of the conditions must evaluate to true. In other words, the conditions - // are ANDed together. (You can use the ConditionalOperator parameter to OR - // the conditions instead. If you do this, then at least one of the conditions - // must evaluate to true, rather than all of them.) - // - // Note that QueryFilter does not allow key attributes. You cannot define a - // filter condition on a partition key or a sort key. - // - // Each QueryFilter element consists of an attribute name to compare, along - // with the following: - // - // * AttributeValueList - One or more values to evaluate against the supplied - // attribute. The number of values in the list depends on the operator specified - // in ComparisonOperator. - // - // For type Number, value comparisons are numeric. - // - // String value comparisons for greater than, equals, or less than are based - // on ASCII character code values. For example, a is greater than A, and - // a is greater than B. For a list of code values, see http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters - // (http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters). - // - // For type Binary, DynamoDB treats each byte of the binary data as unsigned - // when it compares binary values. - // - // For information on specifying data types in JSON, see JSON Data Format (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html) - // in the Amazon DynamoDB Developer Guide. - // - // * ComparisonOperator - A comparator for evaluating attributes. For example, - // equals, greater than, less than, etc. - // - // The following comparison operators are available: - // - // EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | - // BEGINS_WITH | IN | BETWEEN - // - // For complete descriptions of all comparison operators, see the Condition - // (http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html) - // data type. + // This is a legacy parameter. Use FilterExpression instead. For more information, + // see QueryFilter (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.QueryFilter.html) + // in the Amazon DynamoDB Developer Guide. QueryFilter map[string]*Condition `type:"map"` // Determines the level of detail about provisioned throughput consumption that @@ -6001,16 +6536,16 @@ type QueryInput struct { // This return value is equivalent to specifying AttributesToGet without // specifying any value for Select. // - // If you query a local secondary index and request only attributes that are - // projected into that index, the operation will read only the index and - // not the table. If any of the requested attributes are not projected into - // the local secondary index, DynamoDB will fetch each of these attributes + // If you query or scan a local secondary index and request only attributes + // that are projected into that index, the operation will read only the index + // and not the table. If any of the requested attributes are not projected + // into the local secondary index, DynamoDB will fetch each of these attributes // from the parent table. This extra fetching incurs additional throughput // cost and latency. // - // If you query a global secondary index, you can only request attributes that - // are projected into the index. Global secondary index queries cannot fetch - // attributes from the parent table. + // If you query or scan a global secondary index, you can only request attributes + // that are projected into the index. Global secondary index queries cannot + // fetch attributes from the parent table. // // If neither Select nor AttributesToGet are specified, DynamoDB defaults to // ALL_ATTRIBUTES when accessing a table, and ALL_PROJECTED_ATTRIBUTES when @@ -6192,11 +6727,11 @@ func (s *QueryInput) SetTableName(v string) *QueryInput { type QueryOutput struct { _ struct{} `type:"structure"` - // The capacity units consumed by an operation. The data returned includes the - // total provisioned throughput consumed, along with statistics for the table - // and any indexes involved in the operation. ConsumedCapacity is only returned - // if the request asked for it. For more information, see Provisioned Throughput - // (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ProvisionedThroughputIntro.html) + // The capacity units consumed by the Query operation. The data returned includes + // the total provisioned throughput consumed, along with statistics for the + // table and any indexes involved in the operation. ConsumedCapacity is only + // returned if the ReturnConsumedCapacity parameter was specified For more information, + // see Provisioned Throughput (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ProvisionedThroughputIntro.html) // in the Amazon DynamoDB Developer Guide. ConsumedCapacity *ConsumedCapacity `type:"structure"` @@ -6281,41 +6816,14 @@ func (s *QueryOutput) SetScannedCount(v int64) *QueryOutput { type ScanInput struct { _ struct{} `type:"structure"` - // This is a legacy parameter, for backward compatibility. New applications - // should use ProjectionExpression instead. Do not combine legacy parameters - // and expression parameters in a single API call; otherwise, DynamoDB will - // return a ValidationException exception. - // - // This parameter allows you to retrieve attributes of type List or Map; however, - // it cannot retrieve individual elements within a List or a Map. - // - // The names of one or more attributes to retrieve. If no attribute names are - // provided, then all attributes will be returned. If any of the requested attributes - // are not found, they will not appear in the result. - // - // Note that AttributesToGet has no effect on provisioned throughput consumption. - // DynamoDB determines capacity units consumed based on item size, not on the - // amount of data that is returned to an application. + // This is a legacy parameter. Use ProjectionExpression instead. For more information, + // see AttributesToGet (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.AttributesToGet.html) + // in the Amazon DynamoDB Developer Guide. AttributesToGet []*string `min:"1" type:"list"` - // This is a legacy parameter, for backward compatibility. New applications - // should use FilterExpression instead. Do not combine legacy parameters and - // expression parameters in a single API call; otherwise, DynamoDB will return - // a ValidationException exception. - // - // A logical operator to apply to the conditions in a ScanFilter map: - // - // * AND - If all of the conditions evaluate to true, then the entire map - // evaluates to true. - // - // * OR - If at least one of the conditions evaluate to true, then the entire - // map evaluates to true. - // - // If you omit ConditionalOperator, then AND is the default. - // - // The operation will succeed only if the entire map evaluates to true. - // - // This parameter does not support attributes of type List or Map. + // This is a legacy parameter. Use FilterExpression instead. For more information, + // see ConditionalOperator (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.ConditionalOperator.html) + // in the Amazon DynamoDB Developer Guide. ConditionalOperator *string `type:"string" enum:"ConditionalOperator"` // A Boolean value that determines the read consistency model during the scan: @@ -6413,8 +6921,6 @@ type ScanInput struct { // // For more information, see Filter Expressions (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html#FilteringResults) // in the Amazon DynamoDB Developer Guide. - // - // FilterExpression replaces the legacy ScanFilter and ConditionalOperator parameters. FilterExpression *string `type:"string"` // The name of a secondary index to scan. This index can be any local secondary @@ -6444,8 +6950,6 @@ type ScanInput struct { // // For more information, see Accessing Item Attributes (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html) // in the Amazon DynamoDB Developer Guide. - // - // ProjectionExpression replaces the legacy AttributesToGet parameter. ProjectionExpression *string `type:"string"` // Determines the level of detail about provisioned throughput consumption that @@ -6465,51 +6969,9 @@ type ScanInput struct { // * NONE - No ConsumedCapacity details are included in the response. ReturnConsumedCapacity *string `type:"string" enum:"ReturnConsumedCapacity"` - // This is a legacy parameter, for backward compatibility. New applications - // should use FilterExpression instead. Do not combine legacy parameters and - // expression parameters in a single API call; otherwise, DynamoDB will return - // a ValidationException exception. - // - // A condition that evaluates the scan results and returns only the desired - // values. - // - // This parameter does not support attributes of type List or Map. - // - // If you specify more than one condition in the ScanFilter map, then by default - // all of the conditions must evaluate to true. In other words, the conditions - // are ANDed together. (You can use the ConditionalOperator parameter to OR - // the conditions instead. If you do this, then at least one of the conditions - // must evaluate to true, rather than all of them.) - // - // Each ScanFilter element consists of an attribute name to compare, along with - // the following: - // - // * AttributeValueList - One or more values to evaluate against the supplied - // attribute. The number of values in the list depends on the operator specified - // in ComparisonOperator . - // - // For type Number, value comparisons are numeric. - // - // String value comparisons for greater than, equals, or less than are based - // on ASCII character code values. For example, a is greater than A, and - // a is greater than B. For a list of code values, see http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters - // (http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters). - // - // For Binary, DynamoDB treats each byte of the binary data as unsigned when - // it compares binary values. - // - // For information on specifying data types in JSON, see JSON Data Format (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DataFormat.html) - // in the Amazon DynamoDB Developer Guide. - // - // * ComparisonOperator - A comparator for evaluating attributes. For example, - // equals, greater than, less than, etc. - // - // The following comparison operators are available: - // - // EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | - // BEGINS_WITH | IN | BETWEEN - // - // For complete descriptions of all comparison operators, see Condition (http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html). + // This is a legacy parameter. Use FilterExpression instead. For more information, + // see ScanFilter (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.ScanFilter.html) + // in the Amazon DynamoDB Developer Guide. ScanFilter map[string]*Condition `type:"map"` // For a parallel Scan request, Segment identifies an individual segment to @@ -6531,9 +6993,15 @@ type ScanInput struct { Segment *int64 `type:"integer"` // The attributes to be returned in the result. You can retrieve all item attributes, - // specific item attributes, or the count of matching items. + // specific item attributes, the count of matching items, or in the case of + // an index, some or all of the attributes projected into the index. // - // * ALL_ATTRIBUTES - Returns all of the item attributes. + // * ALL_ATTRIBUTES - Returns all of the item attributes from the specified + // table or index. If you query a local secondary index, then for each matching + // item in the index DynamoDB will fetch the entire item from the parent + // table. If the index is configured to project all item attributes, then + // all of the data can be obtained from the local secondary index, and no + // fetching is required. // // * ALL_PROJECTED_ATTRIBUTES - Allowed only when querying an index. Retrieves // all attributes that have been projected into the index. If the index is @@ -6547,10 +7015,27 @@ type ScanInput struct { // This return value is equivalent to specifying AttributesToGet without // specifying any value for Select. // + // If you query or scan a local secondary index and request only attributes + // that are projected into that index, the operation will read only the index + // and not the table. If any of the requested attributes are not projected + // into the local secondary index, DynamoDB will fetch each of these attributes + // from the parent table. This extra fetching incurs additional throughput + // cost and latency. + // + // If you query or scan a global secondary index, you can only request attributes + // that are projected into the index. Global secondary index queries cannot + // fetch attributes from the parent table. + // // If neither Select nor AttributesToGet are specified, DynamoDB defaults to - // ALL_ATTRIBUTES. You cannot use both AttributesToGet and Select together in - // a single request, unless the value for Select is SPECIFIC_ATTRIBUTES. (This - // usage is equivalent to specifying AttributesToGet without any value for Select.) + // ALL_ATTRIBUTES when accessing a table, and ALL_PROJECTED_ATTRIBUTES when + // accessing an index. You cannot use both Select and AttributesToGet together + // in a single request, unless the value for Select is SPECIFIC_ATTRIBUTES. + // (This usage is equivalent to specifying AttributesToGet without any value + // for Select.) + // + // If you use the ProjectionExpression parameter, then the value for Select + // can only be SPECIFIC_ATTRIBUTES. Any other value for Select will return an + // error. Select *string `type:"string" enum:"Select"` // The name of the table containing the requested items; or, if you provide @@ -6722,11 +7207,11 @@ func (s *ScanInput) SetTotalSegments(v int64) *ScanInput { type ScanOutput struct { _ struct{} `type:"structure"` - // The capacity units consumed by an operation. The data returned includes the - // total provisioned throughput consumed, along with statistics for the table - // and any indexes involved in the operation. ConsumedCapacity is only returned - // if the request asked for it. For more information, see Provisioned Throughput - // (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ProvisionedThroughputIntro.html) + // The capacity units consumed by the Scan operation. The data returned includes + // the total provisioned throughput consumed, along with statistics for the + // table and any indexes involved in the operation. ConsumedCapacity is only + // returned if the ReturnConsumedCapacity parameter was specified. For more + // information, see Provisioned Throughput (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ProvisionedThroughputIntro.html) // in the Amazon DynamoDB Developer Guide. ConsumedCapacity *ConsumedCapacity `type:"structure"` @@ -6814,26 +7299,21 @@ type StreamSpecification struct { // on the table. StreamEnabled *bool `type:"boolean"` - // The DynamoDB Streams settings for the table. These settings consist of: - // - // * StreamEnabled - Indicates whether DynamoDB Streams is enabled (true) - // or disabled (false) on the table. - // - // * StreamViewType - When an item in the table is modified, StreamViewType - // determines what information is written to the stream for this table. Valid - // values for StreamViewType are: - // - // KEYS_ONLY - Only the key attributes of the modified item are written to the - // stream. - // - // NEW_IMAGE - The entire item, as it appears after it was modified, is written - // to the stream. + // When an item in the table is modified, StreamViewType determines what information + // is written to the stream for this table. Valid values for StreamViewType + // are: // - // OLD_IMAGE - The entire item, as it appeared before it was modified, is written + // * KEYS_ONLY - Only the key attributes of the modified item are written // to the stream. // - // NEW_AND_OLD_IMAGES - Both the new and the old item images of the item are + // * NEW_IMAGE - The entire item, as it appears after it was modified, is // written to the stream. + // + // * OLD_IMAGE - The entire item, as it appeared before it was modified, + // is written to the stream. + // + // * NEW_AND_OLD_IMAGES - Both the new and the old item images of the item + // are written to the stream. StreamViewType *string `type:"string" enum:"StreamViewType"` } @@ -7152,54 +7632,54 @@ func (s *TableDescription) SetTableStatus(v string) *TableDescription { return s } -// Represents the new provisioned throughput settings to be applied to a global -// secondary index. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateGlobalSecondaryIndexAction -type UpdateGlobalSecondaryIndexAction struct { +// Describes a tag. A tag is a key-value pair. You can add up to 50 tags to +// a single DynamoDB table. +// +// AWS-assigned tag names and values are automatically assigned the aws: prefix, +// which the user cannot assign. AWS-assigned tag names do not count towards +// the tag limit of 50. User-assigned tag names have the prefix user: in the +// Cost Allocation Report. You cannot backdate the application of a tag. +// +// For an overview on tagging DynamoDB resources, see Tagging for DynamoDB (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tagging.html) +// in the Amazon DynamoDB Developer Guide. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/Tag +type Tag struct { _ struct{} `type:"structure"` - // The name of the global secondary index to be updated. + // The key of the tag.Tag keys are case sensitive. Each DynamoDB table can only + // have up to one tag with the same key. If you try to add an existing tag (same + // key), the existing tag value will be updated to the new value. // - // IndexName is a required field - IndexName *string `min:"3" type:"string" required:"true"` + // Key is a required field + Key *string `min:"1" type:"string" required:"true"` - // Represents the provisioned throughput settings for a specified table or index. - // The settings can be modified using the UpdateTable operation. - // - // For current minimum and maximum provisioned throughput values, see Limits - // (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html) - // in the Amazon DynamoDB Developer Guide. + // The value of the tag. Tag values are case-sensitive and can be null. // - // ProvisionedThroughput is a required field - ProvisionedThroughput *ProvisionedThroughput `type:"structure" required:"true"` + // Value is a required field + Value *string `type:"string" required:"true"` } // String returns the string representation -func (s UpdateGlobalSecondaryIndexAction) String() string { +func (s Tag) String() string { return awsutil.Prettify(s) } // GoString returns the string representation -func (s UpdateGlobalSecondaryIndexAction) GoString() string { +func (s Tag) GoString() string { return s.String() } // Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateGlobalSecondaryIndexAction) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateGlobalSecondaryIndexAction"} - if s.IndexName == nil { - invalidParams.Add(request.NewErrParamRequired("IndexName")) - } - if s.IndexName != nil && len(*s.IndexName) < 3 { - invalidParams.Add(request.NewErrParamMinLen("IndexName", 3)) +func (s *Tag) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Tag"} + if s.Key == nil { + invalidParams.Add(request.NewErrParamRequired("Key")) } - if s.ProvisionedThroughput == nil { - invalidParams.Add(request.NewErrParamRequired("ProvisionedThroughput")) + if s.Key != nil && len(*s.Key) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Key", 1)) } - if s.ProvisionedThroughput != nil { - if err := s.ProvisionedThroughput.Validate(); err != nil { - invalidParams.AddNested("ProvisionedThroughput", err.(request.ErrInvalidParams)) - } + if s.Value == nil { + invalidParams.Add(request.NewErrParamRequired("Value")) } if invalidParams.Len() > 0 { @@ -7208,261 +7688,371 @@ func (s *UpdateGlobalSecondaryIndexAction) Validate() error { return nil } -// SetIndexName sets the IndexName field's value. -func (s *UpdateGlobalSecondaryIndexAction) SetIndexName(v string) *UpdateGlobalSecondaryIndexAction { - s.IndexName = &v +// SetKey sets the Key field's value. +func (s *Tag) SetKey(v string) *Tag { + s.Key = &v return s } -// SetProvisionedThroughput sets the ProvisionedThroughput field's value. -func (s *UpdateGlobalSecondaryIndexAction) SetProvisionedThroughput(v *ProvisionedThroughput) *UpdateGlobalSecondaryIndexAction { - s.ProvisionedThroughput = v +// SetValue sets the Value field's value. +func (s *Tag) SetValue(v string) *Tag { + s.Value = &v return s } -// Represents the input of an UpdateItem operation. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateItemInput -type UpdateItemInput struct { +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/TagResourceInput +type TagResourceInput struct { _ struct{} `type:"structure"` - // This is a legacy parameter, for backward compatibility. New applications - // should use UpdateExpression instead. Do not combine legacy parameters and - // expression parameters in a single API call; otherwise, DynamoDB will return - // a ValidationException exception. - // - // This parameter can be used for modifying top-level attributes; however, it - // does not support individual list or map elements. - // - // The names of attributes to be modified, the action to perform on each, and - // the new value for each. If you are updating an attribute that is an index - // key attribute for any indexes on that table, the attribute type must match - // the index key type defined in the AttributesDefinition of the table description. - // You can use UpdateItem to update any non-key attributes. - // - // Attribute values cannot be null. String and Binary type attributes must have - // lengths greater than zero. Set type attributes must not be empty. Requests - // with empty values will be rejected with a ValidationException exception. - // - // Each AttributeUpdates element consists of an attribute name to modify, along - // with the following: - // - // * Value - The new value, if applicable, for this attribute. - // - // * Action - A value that specifies how to perform the update. This action - // is only valid for an existing attribute whose data type is Number or is - // a set; do not use ADD for other data types. - // - // If an item with the specified primary key is found in the table, the following - // values perform the following actions: - // - // PUT - Adds the specified attribute to the item. If the attribute already - // exists, it is replaced by the new value. - // - // DELETE - Removes the attribute and its value, if no value is specified for - // DELETE. The data type of the specified value must match the existing value's - // data type. - // - // If a set of values is specified, then those values are subtracted from the - // old set. For example, if the attribute value was the set [a,b,c] and the - // DELETE action specifies [a,c], then the final attribute value is [b]. - // Specifying an empty set is an error. - // - // ADD - Adds the specified value to the item, if the attribute does not already - // exist. If the attribute does exist, then the behavior of ADD depends on - // the data type of the attribute: - // - // If the existing attribute is a number, and if Value is also a number, then - // Value is mathematically added to the existing attribute. If Value is a - // negative number, then it is subtracted from the existing attribute. - // - // If you use ADD to increment or decrement a number value for an item that - // doesn't exist before the update, DynamoDB uses 0 as the initial value. - // - // Similarly, if you use ADD for an existing item to increment or decrement - // an attribute value that doesn't exist before the update, DynamoDB uses - // 0 as the initial value. For example, suppose that the item you want to - // update doesn't have an attribute named itemcount, but you decide to ADD - // the number 3 to this attribute anyway. DynamoDB will create the itemcount - // attribute, set its initial value to 0, and finally add 3 to it. The result - // will be a new itemcount attribute, with a value of 3. - // - // If the existing data type is a set, and if Value is also a set, then Value - // is appended to the existing set. For example, if the attribute value is - // the set [1,2], and the ADD action specified [3], then the final attribute - // value is [1,2,3]. An error occurs if an ADD action is specified for a - // set attribute and the attribute type specified does not match the existing - // set type. - // - // Both sets must have the same primitive data type. For example, if the existing - // data type is a set of strings, Value must also be a set of strings. - // - // If no item with the specified key is found in the table, the following values - // perform the following actions: - // - // PUT - Causes DynamoDB to create a new item with the specified primary key, - // and then adds the attribute. - // - // DELETE - Nothing happens, because attributes cannot be deleted from a nonexistent - // item. The operation succeeds, but DynamoDB does not create a new item. - // - // ADD - Causes DynamoDB to create an item with the supplied primary key and - // number (or set of numbers) for the attribute value. The only data types - // allowed are Number and Number Set. + // Identifies the Amazon DynamoDB resource to which tags should be added. This + // value is an Amazon Resource Name (ARN). // - // If you provide any attributes that are part of an index key, then the data - // types for those attributes must match those of the schema in the table's - // attribute definition. - AttributeUpdates map[string]*AttributeValueUpdate `type:"map"` + // ResourceArn is a required field + ResourceArn *string `min:"1" type:"string" required:"true"` - // A condition that must be satisfied in order for a conditional update to succeed. - // - // An expression can contain any of the following: - // - // * Functions: attribute_exists | attribute_not_exists | attribute_type - // | contains | begins_with | size - // - // These function names are case-sensitive. - // - // * Comparison operators: = | <> | < | > | <= - // | >= | BETWEEN | IN - // - // * Logical operators: AND | OR | NOT - // - // For more information on condition expressions, see Specifying Conditions - // (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html) - // in the Amazon DynamoDB Developer Guide. + // The tags to be assigned to the Amazon DynamoDB resource. // - // ConditionExpression replaces the legacy ConditionalOperator and Expected - // parameters. - ConditionExpression *string `type:"string"` + // Tags is a required field + Tags []*Tag `type:"list" required:"true"` +} - // This is a legacy parameter, for backward compatibility. New applications - // should use ConditionExpression instead. Do not combine legacy parameters - // and expression parameters in a single API call; otherwise, DynamoDB will - // return a ValidationException exception. - // - // A logical operator to apply to the conditions in the Expected map: - // - // * AND - If all of the conditions evaluate to true, then the entire map - // evaluates to true. - // - // * OR - If at least one of the conditions evaluate to true, then the entire - // map evaluates to true. - // - // If you omit ConditionalOperator, then AND is the default. - // - // The operation will succeed only if the entire map evaluates to true. - // - // This parameter does not support attributes of type List or Map. - ConditionalOperator *string `type:"string" enum:"ConditionalOperator"` +// String returns the string representation +func (s TagResourceInput) String() string { + return awsutil.Prettify(s) +} - // This is a legacy parameter, for backward compatibility. New applications - // should use ConditionExpression instead. Do not combine legacy parameters - // and expression parameters in a single API call; otherwise, DynamoDB will - // return a ValidationException exception. - // - // A map of attribute/condition pairs. Expected provides a conditional block - // for the UpdateItem operation. - // - // Each element of Expected consists of an attribute name, a comparison operator, - // and one or more values. DynamoDB compares the attribute with the value(s) - // you supplied, using the comparison operator. For each Expected element, the - // result of the evaluation is either true or false. - // - // If you specify more than one element in the Expected map, then by default - // all of the conditions must evaluate to true. In other words, the conditions - // are ANDed together. (You can use the ConditionalOperator parameter to OR - // the conditions instead. If you do this, then at least one of the conditions - // must evaluate to true, rather than all of them.) - // - // If the Expected map evaluates to true, then the conditional operation succeeds; - // otherwise, it fails. - // - // Expected contains the following: - // - // * AttributeValueList - One or more values to evaluate against the supplied - // attribute. The number of values in the list depends on the ComparisonOperator - // being used. - // - // For type Number, value comparisons are numeric. - // - // String value comparisons for greater than, equals, or less than are based - // on ASCII character code values. For example, a is greater than A, and - // a is greater than B. For a list of code values, see http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters - // (http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters). - // - // For type Binary, DynamoDB treats each byte of the binary data as unsigned - // when it compares binary values. - // - // * ComparisonOperator - A comparator for evaluating attributes in the AttributeValueList. - // When performing the comparison, DynamoDB uses strongly consistent reads. - // - // The following comparison operators are available: - // - // EQ | NE | LE | LT | GE | GT | NOT_NULL | NULL | CONTAINS | NOT_CONTAINS | - // BEGINS_WITH | IN | BETWEEN - // - // The following are descriptions of each comparison operator. - // - // EQ : Equal. EQ is supported for all datatypes, including lists and maps. - // - // AttributeValueList can contain only one AttributeValue element of type String, - // Number, Binary, String Set, Number Set, or Binary Set. If an item contains - // an AttributeValue element of a different type than the one provided in - // the request, the value does not match. For example, {"S":"6"} does not - // equal {"N":"6"}. Also, {"N":"6"} does not equal {"NS":["6", "2", "1"]}. - // - // NE : Not equal. NE is supported for all datatypes, including lists and maps. +// GoString returns the string representation +func (s TagResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TagResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TagResourceInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) + } + if s.Tags == nil { + invalidParams.Add(request.NewErrParamRequired("Tags")) + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *TagResourceInput) SetResourceArn(v string) *TagResourceInput { + s.ResourceArn = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *TagResourceInput) SetTags(v []*Tag) *TagResourceInput { + s.Tags = v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/TagResourceOutput +type TagResourceOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s TagResourceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TagResourceOutput) GoString() string { + return s.String() +} + +// The description of the Time to Live (TTL) status on the specified table. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/TimeToLiveDescription +type TimeToLiveDescription struct { + _ struct{} `type:"structure"` + + // The name of the Time to Live attribute for items in the table. + AttributeName *string `min:"1" type:"string"` + + // The Time to Live status for the table. + TimeToLiveStatus *string `type:"string" enum:"TimeToLiveStatus"` +} + +// String returns the string representation +func (s TimeToLiveDescription) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TimeToLiveDescription) GoString() string { + return s.String() +} + +// SetAttributeName sets the AttributeName field's value. +func (s *TimeToLiveDescription) SetAttributeName(v string) *TimeToLiveDescription { + s.AttributeName = &v + return s +} + +// SetTimeToLiveStatus sets the TimeToLiveStatus field's value. +func (s *TimeToLiveDescription) SetTimeToLiveStatus(v string) *TimeToLiveDescription { + s.TimeToLiveStatus = &v + return s +} + +// Represents the settings used to enable or disable Time to Live for the specified +// table. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/TimeToLiveSpecification +type TimeToLiveSpecification struct { + _ struct{} `type:"structure"` + + // The name of the Time to Live attribute used to store the expiration time + // for items in the table. // - // AttributeValueList can contain only one AttributeValue of type String, Number, - // Binary, String Set, Number Set, or Binary Set. If an item contains an - // AttributeValue of a different type than the one provided in the request, - // the value does not match. For example, {"S":"6"} does not equal {"N":"6"}. - // Also, {"N":"6"} does not equal {"NS":["6", "2", "1"]}. + // AttributeName is a required field + AttributeName *string `min:"1" type:"string" required:"true"` + + // Indicates whether Time To Live is to be enabled (true) or disabled (false) + // on the table. // - // * LE : Less than or equal. + // Enabled is a required field + Enabled *bool `type:"boolean" required:"true"` +} + +// String returns the string representation +func (s TimeToLiveSpecification) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TimeToLiveSpecification) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TimeToLiveSpecification) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TimeToLiveSpecification"} + if s.AttributeName == nil { + invalidParams.Add(request.NewErrParamRequired("AttributeName")) + } + if s.AttributeName != nil && len(*s.AttributeName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AttributeName", 1)) + } + if s.Enabled == nil { + invalidParams.Add(request.NewErrParamRequired("Enabled")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAttributeName sets the AttributeName field's value. +func (s *TimeToLiveSpecification) SetAttributeName(v string) *TimeToLiveSpecification { + s.AttributeName = &v + return s +} + +// SetEnabled sets the Enabled field's value. +func (s *TimeToLiveSpecification) SetEnabled(v bool) *TimeToLiveSpecification { + s.Enabled = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UntagResourceInput +type UntagResourceInput struct { + _ struct{} `type:"structure"` + + // The Amazon DyanamoDB resource the tags will be removed from. This value is + // an Amazon Resource Name (ARN). // - // AttributeValueList can contain only one AttributeValue element of type String, - // Number, or Binary (not a set type). If an item contains an AttributeValue - // element of a different type than the one provided in the request, the - // value does not match. For example, {"S":"6"} does not equal {"N":"6"}. - // Also, {"N":"6"} does not compare to {"NS":["6", "2", "1"]}. + // ResourceArn is a required field + ResourceArn *string `min:"1" type:"string" required:"true"` + + // A list of tag keys. Existing tags of the resource whose keys are members + // of this list will be removed from the Amazon DynamoDB resource. // - // * LT : Less than. + // TagKeys is a required field + TagKeys []*string `type:"list" required:"true"` +} + +// String returns the string representation +func (s UntagResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UntagResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UntagResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UntagResourceInput"} + if s.ResourceArn == nil { + invalidParams.Add(request.NewErrParamRequired("ResourceArn")) + } + if s.ResourceArn != nil && len(*s.ResourceArn) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourceArn", 1)) + } + if s.TagKeys == nil { + invalidParams.Add(request.NewErrParamRequired("TagKeys")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourceArn sets the ResourceArn field's value. +func (s *UntagResourceInput) SetResourceArn(v string) *UntagResourceInput { + s.ResourceArn = &v + return s +} + +// SetTagKeys sets the TagKeys field's value. +func (s *UntagResourceInput) SetTagKeys(v []*string) *UntagResourceInput { + s.TagKeys = v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UntagResourceOutput +type UntagResourceOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s UntagResourceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UntagResourceOutput) GoString() string { + return s.String() +} + +// Represents the new provisioned throughput settings to be applied to a global +// secondary index. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateGlobalSecondaryIndexAction +type UpdateGlobalSecondaryIndexAction struct { + _ struct{} `type:"structure"` + + // The name of the global secondary index to be updated. // - // * AttributeValueList can contain only one AttributeValue of type String, - // Number, or Binary (not a set type). If an item contains an AttributeValue - // element of a different type than the one provided in the request, the - // value does not match. For example, {"S":"6"} does not equal {"N":"6"}. - // Also, {"N":"6"} does not compare to {"NS":["6", "2", "1"]}. + // IndexName is a required field + IndexName *string `min:"3" type:"string" required:"true"` + + // Represents the provisioned throughput settings for the specified global secondary + // index. // - // * GE : Greater than or equal. + // For current minimum and maximum provisioned throughput values, see Limits + // (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html) + // in the Amazon DynamoDB Developer Guide. // - // AttributeValueList can contain only one AttributeValue element of type String, - // Number, or Binary (not a set type). If an item contains an AttributeValue - // element of a different type than the one provided in the request, the value - // does not match. For example, {"S":"6"} does not equal {"N":"6"}. Also, {"N":"6"} - // does not compare to {"NS":["6", "2", "1"]}. + // ProvisionedThroughput is a required field + ProvisionedThroughput *ProvisionedThroughput `type:"structure" required:"true"` +} + +// String returns the string representation +func (s UpdateGlobalSecondaryIndexAction) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateGlobalSecondaryIndexAction) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateGlobalSecondaryIndexAction) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateGlobalSecondaryIndexAction"} + if s.IndexName == nil { + invalidParams.Add(request.NewErrParamRequired("IndexName")) + } + if s.IndexName != nil && len(*s.IndexName) < 3 { + invalidParams.Add(request.NewErrParamMinLen("IndexName", 3)) + } + if s.ProvisionedThroughput == nil { + invalidParams.Add(request.NewErrParamRequired("ProvisionedThroughput")) + } + if s.ProvisionedThroughput != nil { + if err := s.ProvisionedThroughput.Validate(); err != nil { + invalidParams.AddNested("ProvisionedThroughput", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetIndexName sets the IndexName field's value. +func (s *UpdateGlobalSecondaryIndexAction) SetIndexName(v string) *UpdateGlobalSecondaryIndexAction { + s.IndexName = &v + return s +} + +// SetProvisionedThroughput sets the ProvisionedThroughput field's value. +func (s *UpdateGlobalSecondaryIndexAction) SetProvisionedThroughput(v *ProvisionedThroughput) *UpdateGlobalSecondaryIndexAction { + s.ProvisionedThroughput = v + return s +} + +// Represents the input of an UpdateItem operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateItemInput +type UpdateItemInput struct { + _ struct{} `type:"structure"` + + // This is a legacy parameter. Use UpdateExpression instead. For more information, + // see AttributeUpdates (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.AttributeUpdates.html) + // in the Amazon DynamoDB Developer Guide. + AttributeUpdates map[string]*AttributeValueUpdate `type:"map"` + + // A condition that must be satisfied in order for a conditional update to succeed. // - // GT: Greater than. + // An expression can contain any of the following: // - // AttributeValueListcan contain only one AttributeValueelement of type String, Number, or Binary (not a set type). If an item contains - // an AttributeValueelement of a different type than the one provided in the request, the value - // does not match. For example, {"S":"6"}does not equal {"N":"6"}. Also, {"N":"6"}does not compare to {"NS":["6", "2", "1"]}. + // * Functions: attribute_exists | attribute_not_exists | attribute_type + // | contains | begins_with | size // - // NOT_NULL - // : The attribute exists. NOT_NULL - // is supported for all datatypes, including lists and maps. + // These function names are case-sensitive. // - // This operator tests for the existence of an attribute, not its data type. - // If the data type of attribute "a" is null, and you evaluate it using NOT_NULL, the result is a Boolean true. This result is because the attribute "a" exists; its data type is not relevant to the NOT_NULLcomparison operator. + // * Comparison operators: = | <> | < | > | <= | >= | BETWEEN | IN // - // NULL - // : The attribute does not exist. NULL - // is supported for all datatypes, including lists and maps. + // * Logical operators: AND | OR | NOT // - // This operator tests for the nonexistence of an attribute, not its data type. - // If the data type of attribute "a" is null, and you evaluate it using NULL, the result is a Boolean false. This is because the attribute "a" exists; its data type is not relevant to the NULL + // For more information on condition expressions, see Specifying Conditions + // (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html) + // in the Amazon DynamoDB Developer Guide. + ConditionExpression *string `type:"string"` + + // This is a legacy parameter. Use ConditionExpression instead. For more information, + // see ConditionalOperator (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.ConditionalOperator.html) + // in the Amazon DynamoDB Developer Guide. + ConditionalOperator *string `type:"string" enum:"ConditionalOperator"` + + // This is a legacy parameter. Use ConditionExpresssion instead. For more information, + // see Expected (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.Expected.html) + // in the Amazon DynamoDB Developer Guide. Expected map[string]*ExpectedAttributeValue `type:"map"` // One or more substitution tokens for attribute names in an expression. The @@ -7565,14 +8155,17 @@ type UpdateItemInput struct { // * NONE - If ReturnValues is not specified, or if its value is NONE, then // nothing is returned. (This setting is the default for ReturnValues.) // - // * ALL_OLD - If UpdateItem overwrote an attribute name-value pair, then - // the content of the old item is returned. + // * ALL_OLD - Returns all of the attributes of the item, as they appeared + // before the UpdateItem operation. // - // * UPDATED_OLD - The old versions of only the updated attributes are returned. + // * UPDATED_OLD - Returns only the updated attributes, as they appeared + // before the UpdateItem operation. // - // * ALL_NEW - All of the attributes of the new version of the item are returned. + // * ALL_NEW - Returns all of the attributes of the item, as they appear + // after the UpdateItem operation. // - // * UPDATED_NEW - The new versions of only the updated attributes are returned. + // * UPDATED_NEW - Returns only the updated attributes, as they appear after + // the UpdateItem operation. // // There is no additional cost associated with requesting a return value aside // from the small network and processing overhead of receiving a larger response. @@ -7659,8 +8252,6 @@ type UpdateItemInput struct { // For more information on update expressions, see Modifying Items and Attributes // (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.Modifying.html) // in the Amazon DynamoDB Developer Guide. - // - // UpdateExpression replaces the legacy AttributeUpdates parameter. UpdateExpression *string `type:"string"` } @@ -7775,18 +8366,33 @@ type UpdateItemOutput struct { // NONE in the request. Each element represents one attribute. Attributes map[string]*AttributeValue `type:"map"` - // The capacity units consumed by an operation. The data returned includes the - // total provisioned throughput consumed, along with statistics for the table - // and any indexes involved in the operation. ConsumedCapacity is only returned - // if the request asked for it. For more information, see Provisioned Throughput - // (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ProvisionedThroughputIntro.html) + // The capacity units consumed by the UpdateItem operation. The data returned + // includes the total provisioned throughput consumed, along with statistics + // for the table and any indexes involved in the operation. ConsumedCapacity + // is only returned if the ReturnConsumedCapacity parameter was specified. For + // more information, see Provisioned Throughput (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ProvisionedThroughputIntro.html) // in the Amazon DynamoDB Developer Guide. ConsumedCapacity *ConsumedCapacity `type:"structure"` - // Information about item collections, if any, that were affected by the operation. - // ItemCollectionMetrics is only returned if the request asked for it. If the - // table does not have any local secondary indexes, this information is not - // returned in the response. + // Information about item collections, if any, that were affected by the UpdateItem + // operation. ItemCollectionMetrics is only returned if the ReturnItemCollectionMetrics + // parameter was specified. If the table does not have any local secondary indexes, + // this information is not returned in the response. + // + // Each ItemCollectionMetrics element consists of: + // + // * ItemCollectionKey - The partition key value of the item collection. + // This is the same as the partition key value of the item itself. + // + // * SizeEstimateRange - An estimate of item collection size, in gigabytes. + // This value is a two-element array containing a lower bound and an upper + // bound for the estimate. The estimate includes the size of all the items + // in the table, plus the size of all attributes projected into all of the + // local secondary indexes on that table. Use this estimate to measure whether + // a local secondary index is approaching its size limit. + // + // The estimate is subject to change over time; therefore, do not rely on the + // precision or accuracy of the estimate. ItemCollectionMetrics *ItemCollectionMetrics `type:"structure"` } @@ -7842,12 +8448,7 @@ type UpdateTableInput struct { // in the Amazon DynamoDB Developer Guide. GlobalSecondaryIndexUpdates []*GlobalSecondaryIndexUpdate `type:"list"` - // Represents the provisioned throughput settings for a specified table or index. - // The settings can be modified using the UpdateTable operation. - // - // For current minimum and maximum provisioned throughput values, see Limits - // (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html) - // in the Amazon DynamoDB Developer Guide. + // The new provisioned throughput settings for the specified table or index. ProvisionedThroughput *ProvisionedThroughput `type:"structure"` // Represents the DynamoDB Streams configuration for the table. @@ -7949,7 +8550,7 @@ func (s *UpdateTableInput) SetTableName(v string) *UpdateTableInput { type UpdateTableOutput struct { _ struct{} `type:"structure"` - // Represents the properties of a table. + // Represents the properties of the table. TableDescription *TableDescription `type:"structure"` } @@ -7969,6 +8570,93 @@ func (s *UpdateTableOutput) SetTableDescription(v *TableDescription) *UpdateTabl return s } +// Represents the input of an UpdateTimeToLive operation. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateTimeToLiveInput +type UpdateTimeToLiveInput struct { + _ struct{} `type:"structure"` + + // The name of the table to be configured. + // + // TableName is a required field + TableName *string `min:"3" type:"string" required:"true"` + + // Represents the settings used to enable or disable Time to Live for the specified + // table. + // + // TimeToLiveSpecification is a required field + TimeToLiveSpecification *TimeToLiveSpecification `type:"structure" required:"true"` +} + +// String returns the string representation +func (s UpdateTimeToLiveInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateTimeToLiveInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UpdateTimeToLiveInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UpdateTimeToLiveInput"} + if s.TableName == nil { + invalidParams.Add(request.NewErrParamRequired("TableName")) + } + if s.TableName != nil && len(*s.TableName) < 3 { + invalidParams.Add(request.NewErrParamMinLen("TableName", 3)) + } + if s.TimeToLiveSpecification == nil { + invalidParams.Add(request.NewErrParamRequired("TimeToLiveSpecification")) + } + if s.TimeToLiveSpecification != nil { + if err := s.TimeToLiveSpecification.Validate(); err != nil { + invalidParams.AddNested("TimeToLiveSpecification", err.(request.ErrInvalidParams)) + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetTableName sets the TableName field's value. +func (s *UpdateTimeToLiveInput) SetTableName(v string) *UpdateTimeToLiveInput { + s.TableName = &v + return s +} + +// SetTimeToLiveSpecification sets the TimeToLiveSpecification field's value. +func (s *UpdateTimeToLiveInput) SetTimeToLiveSpecification(v *TimeToLiveSpecification) *UpdateTimeToLiveInput { + s.TimeToLiveSpecification = v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/UpdateTimeToLiveOutput +type UpdateTimeToLiveOutput struct { + _ struct{} `type:"structure"` + + // Represents the output of an UpdateTimeToLive operation. + TimeToLiveSpecification *TimeToLiveSpecification `type:"structure"` +} + +// String returns the string representation +func (s UpdateTimeToLiveOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UpdateTimeToLiveOutput) GoString() string { + return s.String() +} + +// SetTimeToLiveSpecification sets the TimeToLiveSpecification field's value. +func (s *UpdateTimeToLiveOutput) SetTimeToLiveSpecification(v *TimeToLiveSpecification) *UpdateTimeToLiveOutput { + s.TimeToLiveSpecification = v + return s +} + // Represents an operation to perform - either DeleteItem or PutItem. You can // only request one of these operations, not both, in a single WriteRequest. // If you do need to perform both of these operations, you will need to provide @@ -8202,3 +8890,17 @@ const ( // TableStatusActive is a TableStatus enum value TableStatusActive = "ACTIVE" ) + +const ( + // TimeToLiveStatusEnabling is a TimeToLiveStatus enum value + TimeToLiveStatusEnabling = "ENABLING" + + // TimeToLiveStatusDisabling is a TimeToLiveStatus enum value + TimeToLiveStatusDisabling = "DISABLING" + + // TimeToLiveStatusEnabled is a TimeToLiveStatus enum value + TimeToLiveStatusEnabled = "ENABLED" + + // TimeToLiveStatusDisabled is a TimeToLiveStatus enum value + TimeToLiveStatusDisabled = "DISABLED" +) diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/customizations.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/customizations.go index 51843cd..333e61b 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/customizations.go +++ b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/customizations.go @@ -26,19 +26,30 @@ func (d retryer) RetryRules(r *request.Request) time.Duration { func init() { initClient = func(c *client.Client) { - r := retryer{} - if c.Config.MaxRetries == nil || aws.IntValue(c.Config.MaxRetries) == aws.UseServiceDefaultRetries { - r.NumMaxRetries = 10 - } else { - r.NumMaxRetries = *c.Config.MaxRetries + if c.Config.Retryer == nil { + // Only override the retryer with a custom one if the config + // does not already contain a retryer + setCustomRetryer(c) } - c.Retryer = r c.Handlers.Build.PushBack(disableCompression) c.Handlers.Unmarshal.PushFront(validateCRC32) } } +func setCustomRetryer(c *client.Client) { + maxRetries := aws.IntValue(c.Config.MaxRetries) + if c.Config.MaxRetries == nil || maxRetries == aws.UseServiceDefaultRetries { + maxRetries = 10 + } + + c.Retryer = retryer{ + DefaultRetryer: client.DefaultRetryer{ + NumMaxRetries: maxRetries, + }, + } +} + func drainBody(b io.ReadCloser, length int64) (out *bytes.Buffer, err error) { if length < 0 { length = 0 diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/errors.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/errors.go new file mode 100644 index 0000000..d47a104 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/errors.go @@ -0,0 +1,64 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package dynamodb + +const ( + + // ErrCodeConditionalCheckFailedException for service response error code + // "ConditionalCheckFailedException". + // + // A condition specified in the operation could not be evaluated. + ErrCodeConditionalCheckFailedException = "ConditionalCheckFailedException" + + // ErrCodeInternalServerError for service response error code + // "InternalServerError". + // + // An error occurred on the server side. + ErrCodeInternalServerError = "InternalServerError" + + // ErrCodeItemCollectionSizeLimitExceededException for service response error code + // "ItemCollectionSizeLimitExceededException". + // + // An item collection is too large. This exception is only returned for tables + // that have one or more local secondary indexes. + ErrCodeItemCollectionSizeLimitExceededException = "ItemCollectionSizeLimitExceededException" + + // ErrCodeLimitExceededException for service response error code + // "LimitExceededException". + // + // The number of concurrent table requests (cumulative number of tables in the + // CREATING, DELETING or UPDATING state) exceeds the maximum allowed of 10. + // + // Also, for tables with secondary indexes, only one of those tables can be + // in the CREATING state at any point in time. Do not attempt to create more + // than one such table simultaneously. + // + // The total limit of tables in the ACTIVE state is 250. + ErrCodeLimitExceededException = "LimitExceededException" + + // ErrCodeProvisionedThroughputExceededException for service response error code + // "ProvisionedThroughputExceededException". + // + // Your request rate is too high. The AWS SDKs for DynamoDB automatically retry + // requests that receive this exception. Your request is eventually successful, + // unless your retry queue is too large to finish. Reduce the frequency of requests + // and use exponential backoff. For more information, go to Error Retries and + // Exponential Backoff (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff) + // in the Amazon DynamoDB Developer Guide. + ErrCodeProvisionedThroughputExceededException = "ProvisionedThroughputExceededException" + + // ErrCodeResourceInUseException for service response error code + // "ResourceInUseException". + // + // The operation conflicts with the resource's availability. For example, you + // attempted to recreate an existing table, or tried to delete a table currently + // in the CREATING state. + ErrCodeResourceInUseException = "ResourceInUseException" + + // ErrCodeResourceNotFoundException for service response error code + // "ResourceNotFoundException". + // + // The operation tried to access a nonexistent table or index. The resource + // might not be specified correctly, or its status might not be ACTIVE. + ErrCodeResourceNotFoundException = "ResourceNotFoundException" +) diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/service.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/service.go index 6816764..7782769 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package dynamodb @@ -11,119 +11,24 @@ import ( "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" ) -// This is the Amazon DynamoDB API Reference. This guide provides descriptions -// of the low-level DynamoDB API. -// -// This guide is intended for use with the following DynamoDB documentation: -// -// * Amazon DynamoDB Getting Started Guide (http://docs.aws.amazon.com/amazondynamodb/latest/gettingstartedguide/) -// - provides hands-on exercises that help you learn the basics of working -// with DynamoDB. If you are new to DynamoDB, we recommend that you begin -// with the Getting Started Guide. -// -// * Amazon DynamoDB Developer Guide (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/) -// - contains detailed information about DynamoDB concepts, usage, and best -// practices. -// -// * Amazon DynamoDB Streams API Reference (http://docs.aws.amazon.com/dynamodbstreams/latest/APIReference/) -// - provides descriptions and samples of the DynamoDB Streams API. (For -// more information, see Capturing Table Activity with DynamoDB Streams (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html) -// in the Amazon DynamoDB Developer Guide.) -// -// Instead of making the requests to the low-level DynamoDB API directly from -// your application, we recommend that you use the AWS Software Development -// Kits (SDKs). The easy-to-use libraries in the AWS SDKs make it unnecessary -// to call the low-level DynamoDB API directly from your application. The libraries -// take care of request authentication, serialization, and connection management. -// For more information, see Using the AWS SDKs with DynamoDB (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/UsingAWSSDK.html) -// in the Amazon DynamoDB Developer Guide. -// -// If you decide to code against the low-level DynamoDB API directly, you will -// need to write the necessary code to authenticate your requests. For more -// information on signing your requests, see Using the DynamoDB API (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/API.html) -// in the Amazon DynamoDB Developer Guide. -// -// The following are short descriptions of each low-level API action, organized -// by function. -// -// Managing Tables -// -// * CreateTable - Creates a table with user-specified provisioned throughput -// settings. You must define a primary key for the table - either a simple -// primary key (partition key), or a composite primary key (partition key -// and sort key). Optionally, you can create one or more secondary indexes, -// which provide fast data access using non-key attributes. -// -// * DescribeTable - Returns metadata for a table, such as table size, status, -// and index information. -// -// * UpdateTable - Modifies the provisioned throughput settings for a table. -// Optionally, you can modify the provisioned throughput settings for global -// secondary indexes on the table. -// -// * ListTables - Returns a list of all tables associated with the current -// AWS account and endpoint. -// -// * DeleteTable - Deletes a table and all of its indexes. -// -// For conceptual information about managing tables, see Working with Tables -// (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.html) -// in the Amazon DynamoDB Developer Guide. -// -// Reading Data -// -// * GetItem - Returns a set of attributes for the item that has a given -// primary key. By default, GetItem performs an eventually consistent read; -// however, applications can request a strongly consistent read instead. -// -// * BatchGetItem - Performs multiple GetItem requests for data items using -// their primary keys, from one table or multiple tables. The response from -// BatchGetItem has a size limit of 16 MB and returns a maximum of 100 items. -// Both eventually consistent and strongly consistent reads can be used. -// -// * Query - Returns one or more items from a table or a secondary index. -// You must provide a specific value for the partition key. You can narrow -// the scope of the query using comparison operators against a sort key value, -// or on the index key. Query supports either eventual or strong consistency. -// A single response has a size limit of 1 MB. -// -// * Scan - Reads every item in a table; the result set is eventually consistent. -// You can limit the number of items returned by filtering the data attributes, -// using conditional expressions. Scan can be used to enable ad-hoc querying -// of a table against non-key attributes; however, since this is a full table -// scan without using an index, Scan should not be used for any application -// query use case that requires predictable performance. -// -// For conceptual information about reading data, see Working with Items (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html) -// and Query and Scan Operations (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html) -// in the Amazon DynamoDB Developer Guide. -// -// Modifying Data -// -// * PutItem - Creates a new item, or replaces an existing item with a new -// item (including all the attributes). By default, if an item in the table -// already exists with the same primary key, the new item completely replaces -// the existing item. You can use conditional operators to replace an item -// only if its attribute values match certain conditions, or to insert a -// new item only if that item doesn't already exist. -// -// * UpdateItem - Modifies the attributes of an existing item. You can also -// use conditional operators to perform an update only if the item's attribute -// values match certain conditions. -// -// * DeleteItem - Deletes an item in a table by primary key. You can use -// conditional operators to perform a delete an item only if the item's attribute -// values match certain conditions. -// -// * BatchWriteItem - Performs multiple PutItem and DeleteItem requests across -// multiple tables in a single request. A failure of any request(s) in the -// batch will not cause the entire BatchWriteItem operation to fail. Supports -// batches of up to 25 items to put or delete, with a maximum total request -// size of 16 MB. -// -// For conceptual information about modifying data, see Working with Items (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html) -// and Query and Scan Operations (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html) -// in the Amazon DynamoDB Developer Guide. +// Amazon DynamoDB is a fully managed NoSQL database service that provides fast +// and predictable performance with seamless scalability. DynamoDB lets you +// offload the administrative burdens of operating and scaling a distributed +// database, so that you don't have to worry about hardware provisioning, setup +// and configuration, replication, software patching, or cluster scaling. +// +// With DynamoDB, you can create database tables that can store and retrieve +// any amount of data, and serve any level of request traffic. You can scale +// up or scale down your tables' throughput capacity without downtime or performance +// degradation, and use the AWS Management Console to monitor resource utilization +// and performance metrics. +// +// DynamoDB automatically spreads the data and traffic for your tables over +// a sufficient number of servers to handle your throughput and storage requirements, +// while maintaining consistent and fast performance. All of your data is stored +// on solid state disks (SSDs) and automatically replicated across multiple +// Availability Zones in an AWS region, providing built-in high availability +// and data durability. // The service client's operations are safe to be used concurrently. // It is not safe to mutate any of the client's properties though. // Please also see https://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10 diff --git a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/waiters.go index 57e1264..07c75c4 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/dynamodb/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/dynamodb/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package dynamodb import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilTableExists uses the DynamoDB API operation @@ -11,32 +14,50 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *DynamoDB) WaitUntilTableExists(input *DescribeTableInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeTable", - Delay: 20, + return c.WaitUntilTableExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilTableExistsWithContext is an extended version of WaitUntilTableExists. +// With the support for passing in a context and options to configure the +// Waiter and the underlying request options. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) WaitUntilTableExistsWithContext(ctx aws.Context, input *DescribeTableInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilTableExists", MaxAttempts: 25, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(20 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "path", - Argument: "Table.TableStatus", + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Table.TableStatus", Expected: "ACTIVE", }, { - State: "retry", - Matcher: "error", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "ResourceNotFoundException", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeTableInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeTableRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilTableNotExists uses the DynamoDB API operation @@ -44,24 +65,43 @@ func (c *DynamoDB) WaitUntilTableExists(input *DescribeTableInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *DynamoDB) WaitUntilTableNotExists(input *DescribeTableInput) error { - waiterCfg := waiter.Config{ - Operation: "DescribeTable", - Delay: 20, + return c.WaitUntilTableNotExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilTableNotExistsWithContext is an extended version of WaitUntilTableNotExists. +// With the support for passing in a context and options to configure the +// Waiter and the underlying request options. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *DynamoDB) WaitUntilTableNotExistsWithContext(ctx aws.Context, input *DescribeTableInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilTableNotExists", MaxAttempts: 25, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(20 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "error", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.ErrorWaiterMatch, Expected: "ResourceNotFoundException", }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *DescribeTableInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeTableRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/kms/api.go b/vendor/github.com/aws/aws-sdk-go/service/kms/api.go index 367f917..82ef661 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/kms/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/kms/api.go @@ -1,11 +1,13 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. // Package kms provides a client for AWS Key Management Service. package kms import ( + "fmt" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -50,9 +52,8 @@ func (c *KMS) CancelKeyDeletionRequest(input *CancelKeyDeletionInput) (req *requ input = &CancelKeyDeletionInput{} } - req = c.newRequest(op, input, output) output = &CancelKeyDeletionOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -74,22 +75,22 @@ func (c *KMS) CancelKeyDeletionRequest(input *CancelKeyDeletionInput) (req *requ // API operation CancelKeyDeletion for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -100,8 +101,23 @@ func (c *KMS) CancelKeyDeletionRequest(input *CancelKeyDeletionInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/CancelKeyDeletion func (c *KMS) CancelKeyDeletion(input *CancelKeyDeletionInput) (*CancelKeyDeletionOutput, error) { req, out := c.CancelKeyDeletionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CancelKeyDeletionWithContext is the same as CancelKeyDeletion with the addition of +// the ability to pass a context and additional request options. +// +// See CancelKeyDeletion for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) CancelKeyDeletionWithContext(ctx aws.Context, input *CancelKeyDeletionInput, opts ...request.Option) (*CancelKeyDeletionOutput, error) { + req, out := c.CancelKeyDeletionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateAlias = "CreateAlias" @@ -142,11 +158,10 @@ func (c *KMS) CreateAliasRequest(input *CreateAliasInput) (req *request.Request, input = &CreateAliasInput{} } + output = &CreateAliasOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &CreateAliasOutput{} - req.Data = output return } @@ -173,31 +188,31 @@ func (c *KMS) CreateAliasRequest(input *CreateAliasInput) (req *request.Request, // API operation CreateAlias for usage and error information. // // Returned Error Codes: -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * AlreadyExistsException +// * ErrCodeAlreadyExistsException "AlreadyExistsException" // The request was rejected because it attempted to create a resource that already // exists. // -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * InvalidAliasNameException +// * ErrCodeInvalidAliasNameException "InvalidAliasNameException" // The request was rejected because the specified alias name is not valid. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * LimitExceededException +// * ErrCodeLimitExceededException "LimitExceededException" // The request was rejected because a limit was exceeded. For more information, // see Limits (http://docs.aws.amazon.com/kms/latest/developerguide/limits.html) // in the AWS Key Management Service Developer Guide. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -208,8 +223,23 @@ func (c *KMS) CreateAliasRequest(input *CreateAliasInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/CreateAlias func (c *KMS) CreateAlias(input *CreateAliasInput) (*CreateAliasOutput, error) { req, out := c.CreateAliasRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateAliasWithContext is the same as CreateAlias with the addition of +// the ability to pass a context and additional request options. +// +// See CreateAlias for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) CreateAliasWithContext(ctx aws.Context, input *CreateAliasInput, opts ...request.Option) (*CreateAliasOutput, error) { + req, out := c.CreateAliasRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateGrant = "CreateGrant" @@ -250,9 +280,8 @@ func (c *KMS) CreateGrantRequest(input *CreateGrantInput) (req *request.Request, input = &CreateGrantInput{} } - req = c.newRequest(op, input, output) output = &CreateGrantOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -272,33 +301,33 @@ func (c *KMS) CreateGrantRequest(input *CreateGrantInput) (req *request.Request, // API operation CreateGrant for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * DisabledException +// * ErrCodeDisabledException "DisabledException" // The request was rejected because the specified CMK is not enabled. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidGrantTokenException +// * ErrCodeInvalidGrantTokenException "InvalidGrantTokenException" // The request was rejected because the specified grant token is not valid. // -// * LimitExceededException +// * ErrCodeLimitExceededException "LimitExceededException" // The request was rejected because a limit was exceeded. For more information, // see Limits (http://docs.aws.amazon.com/kms/latest/developerguide/limits.html) // in the AWS Key Management Service Developer Guide. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -309,8 +338,23 @@ func (c *KMS) CreateGrantRequest(input *CreateGrantInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/CreateGrant func (c *KMS) CreateGrant(input *CreateGrantInput) (*CreateGrantOutput, error) { req, out := c.CreateGrantRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateGrantWithContext is the same as CreateGrant with the addition of +// the ability to pass a context and additional request options. +// +// See CreateGrant for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) CreateGrantWithContext(ctx aws.Context, input *CreateGrantInput, opts ...request.Option) (*CreateGrantOutput, error) { + req, out := c.CreateGrantRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateKey = "CreateKey" @@ -351,9 +395,8 @@ func (c *KMS) CreateKeyRequest(input *CreateKeyInput) (req *request.Request, out input = &CreateKeyInput{} } - req = c.newRequest(op, input, output) output = &CreateKeyOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -379,35 +422,53 @@ func (c *KMS) CreateKeyRequest(input *CreateKeyInput) (req *request.Request, out // API operation CreateKey for usage and error information. // // Returned Error Codes: -// * MalformedPolicyDocumentException +// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocumentException" // The request was rejected because the specified policy is not syntactically // or semantically correct. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * UnsupportedOperationException +// * ErrCodeUnsupportedOperationException "UnsupportedOperationException" // The request was rejected because a specified parameter is not supported or // a specified resource is not valid for this operation. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * LimitExceededException +// * ErrCodeLimitExceededException "LimitExceededException" // The request was rejected because a limit was exceeded. For more information, // see Limits (http://docs.aws.amazon.com/kms/latest/developerguide/limits.html) // in the AWS Key Management Service Developer Guide. // +// * ErrCodeTagException "TagException" +// The request was rejected because one or more tags are not valid. +// // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/CreateKey func (c *KMS) CreateKey(input *CreateKeyInput) (*CreateKeyOutput, error) { req, out := c.CreateKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateKeyWithContext is the same as CreateKey with the addition of +// the ability to pass a context and additional request options. +// +// See CreateKey for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) CreateKeyWithContext(ctx aws.Context, input *CreateKeyInput, opts ...request.Option) (*CreateKeyOutput, error) { + req, out := c.CreateKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDecrypt = "Decrypt" @@ -448,9 +509,8 @@ func (c *KMS) DecryptRequest(input *DecryptInput) (req *request.Request, output input = &DecryptInput{} } - req = c.newRequest(op, input, output) output = &DecryptOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -482,33 +542,33 @@ func (c *KMS) DecryptRequest(input *DecryptInput) (req *request.Request, output // API operation Decrypt for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * DisabledException +// * ErrCodeDisabledException "DisabledException" // The request was rejected because the specified CMK is not enabled. // -// * InvalidCiphertextException +// * ErrCodeInvalidCiphertextException "InvalidCiphertextException" // The request was rejected because the specified ciphertext has been corrupted // or is otherwise invalid. // -// * KeyUnavailableException +// * ErrCodeKeyUnavailableException "KeyUnavailableException" // The request was rejected because the specified CMK was not available. The // request can be retried. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InvalidGrantTokenException +// * ErrCodeInvalidGrantTokenException "InvalidGrantTokenException" // The request was rejected because the specified grant token is not valid. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -519,8 +579,23 @@ func (c *KMS) DecryptRequest(input *DecryptInput) (req *request.Request, output // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/Decrypt func (c *KMS) Decrypt(input *DecryptInput) (*DecryptOutput, error) { req, out := c.DecryptRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DecryptWithContext is the same as Decrypt with the addition of +// the ability to pass a context and additional request options. +// +// See Decrypt for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) DecryptWithContext(ctx aws.Context, input *DecryptInput, opts ...request.Option) (*DecryptOutput, error) { + req, out := c.DecryptRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteAlias = "DeleteAlias" @@ -561,11 +636,10 @@ func (c *KMS) DeleteAliasRequest(input *DeleteAliasInput) (req *request.Request, input = &DeleteAliasInput{} } + output = &DeleteAliasOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &DeleteAliasOutput{} - req.Data = output return } @@ -581,19 +655,19 @@ func (c *KMS) DeleteAliasRequest(input *DeleteAliasInput) (req *request.Request, // API operation DeleteAlias for usage and error information. // // Returned Error Codes: -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -604,8 +678,23 @@ func (c *KMS) DeleteAliasRequest(input *DeleteAliasInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/DeleteAlias func (c *KMS) DeleteAlias(input *DeleteAliasInput) (*DeleteAliasOutput, error) { req, out := c.DeleteAliasRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteAliasWithContext is the same as DeleteAlias with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteAlias for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) DeleteAliasWithContext(ctx aws.Context, input *DeleteAliasInput, opts ...request.Option) (*DeleteAliasOutput, error) { + req, out := c.DeleteAliasRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteImportedKeyMaterial = "DeleteImportedKeyMaterial" @@ -646,11 +735,10 @@ func (c *KMS) DeleteImportedKeyMaterialRequest(input *DeleteImportedKeyMaterialI input = &DeleteImportedKeyMaterialInput{} } + output = &DeleteImportedKeyMaterialOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &DeleteImportedKeyMaterialOutput{} - req.Data = output return } @@ -675,26 +763,26 @@ func (c *KMS) DeleteImportedKeyMaterialRequest(input *DeleteImportedKeyMaterialI // API operation DeleteImportedKeyMaterial for usage and error information. // // Returned Error Codes: -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * UnsupportedOperationException +// * ErrCodeUnsupportedOperationException "UnsupportedOperationException" // The request was rejected because a specified parameter is not supported or // a specified resource is not valid for this operation. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -705,8 +793,23 @@ func (c *KMS) DeleteImportedKeyMaterialRequest(input *DeleteImportedKeyMaterialI // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/DeleteImportedKeyMaterial func (c *KMS) DeleteImportedKeyMaterial(input *DeleteImportedKeyMaterialInput) (*DeleteImportedKeyMaterialOutput, error) { req, out := c.DeleteImportedKeyMaterialRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteImportedKeyMaterialWithContext is the same as DeleteImportedKeyMaterial with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteImportedKeyMaterial for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) DeleteImportedKeyMaterialWithContext(ctx aws.Context, input *DeleteImportedKeyMaterialInput, opts ...request.Option) (*DeleteImportedKeyMaterialOutput, error) { + req, out := c.DeleteImportedKeyMaterialRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDescribeKey = "DescribeKey" @@ -747,9 +850,8 @@ func (c *KMS) DescribeKeyRequest(input *DescribeKeyInput) (req *request.Request, input = &DescribeKeyInput{} } - req = c.newRequest(op, input, output) output = &DescribeKeyOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -765,26 +867,41 @@ func (c *KMS) DescribeKeyRequest(input *DescribeKeyInput) (req *request.Request, // API operation DescribeKey for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/DescribeKey func (c *KMS) DescribeKey(input *DescribeKeyInput) (*DescribeKeyOutput, error) { req, out := c.DescribeKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DescribeKeyWithContext is the same as DescribeKey with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeKey for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) DescribeKeyWithContext(ctx aws.Context, input *DescribeKeyInput, opts ...request.Option) (*DescribeKeyOutput, error) { + req, out := c.DescribeKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisableKey = "DisableKey" @@ -825,11 +942,10 @@ func (c *KMS) DisableKeyRequest(input *DisableKeyInput) (req *request.Request, o input = &DisableKeyInput{} } + output = &DisableKeyOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &DisableKeyOutput{} - req.Data = output return } @@ -849,22 +965,22 @@ func (c *KMS) DisableKeyRequest(input *DisableKeyInput) (req *request.Request, o // API operation DisableKey for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -875,8 +991,23 @@ func (c *KMS) DisableKeyRequest(input *DisableKeyInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/DisableKey func (c *KMS) DisableKey(input *DisableKeyInput) (*DisableKeyOutput, error) { req, out := c.DisableKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisableKeyWithContext is the same as DisableKey with the addition of +// the ability to pass a context and additional request options. +// +// See DisableKey for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) DisableKeyWithContext(ctx aws.Context, input *DisableKeyInput, opts ...request.Option) (*DisableKeyOutput, error) { + req, out := c.DisableKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDisableKeyRotation = "DisableKeyRotation" @@ -917,11 +1048,10 @@ func (c *KMS) DisableKeyRotationRequest(input *DisableKeyRotationInput) (req *re input = &DisableKeyRotationInput{} } + output = &DisableKeyRotationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &DisableKeyRotationOutput{} - req.Data = output return } @@ -937,25 +1067,25 @@ func (c *KMS) DisableKeyRotationRequest(input *DisableKeyRotationInput) (req *re // API operation DisableKeyRotation for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * DisabledException +// * ErrCodeDisabledException "DisabledException" // The request was rejected because the specified CMK is not enabled. // -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -963,15 +1093,30 @@ func (c *KMS) DisableKeyRotationRequest(input *DisableKeyRotationInput) (req *re // Key State Affects Use of a Customer Master Key (http://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) // in the AWS Key Management Service Developer Guide. // -// * UnsupportedOperationException +// * ErrCodeUnsupportedOperationException "UnsupportedOperationException" // The request was rejected because a specified parameter is not supported or // a specified resource is not valid for this operation. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/DisableKeyRotation func (c *KMS) DisableKeyRotation(input *DisableKeyRotationInput) (*DisableKeyRotationOutput, error) { req, out := c.DisableKeyRotationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DisableKeyRotationWithContext is the same as DisableKeyRotation with the addition of +// the ability to pass a context and additional request options. +// +// See DisableKeyRotation for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) DisableKeyRotationWithContext(ctx aws.Context, input *DisableKeyRotationInput, opts ...request.Option) (*DisableKeyRotationOutput, error) { + req, out := c.DisableKeyRotationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableKey = "EnableKey" @@ -1012,11 +1157,10 @@ func (c *KMS) EnableKeyRequest(input *EnableKeyInput) (req *request.Request, out input = &EnableKeyInput{} } + output = &EnableKeyOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &EnableKeyOutput{} - req.Data = output return } @@ -1032,27 +1176,27 @@ func (c *KMS) EnableKeyRequest(input *EnableKeyInput) (req *request.Request, out // API operation EnableKey for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * LimitExceededException +// * ErrCodeLimitExceededException "LimitExceededException" // The request was rejected because a limit was exceeded. For more information, // see Limits (http://docs.aws.amazon.com/kms/latest/developerguide/limits.html) // in the AWS Key Management Service Developer Guide. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -1063,8 +1207,23 @@ func (c *KMS) EnableKeyRequest(input *EnableKeyInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/EnableKey func (c *KMS) EnableKey(input *EnableKeyInput) (*EnableKeyOutput, error) { req, out := c.EnableKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableKeyWithContext is the same as EnableKey with the addition of +// the ability to pass a context and additional request options. +// +// See EnableKey for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) EnableKeyWithContext(ctx aws.Context, input *EnableKeyInput, opts ...request.Option) (*EnableKeyOutput, error) { + req, out := c.EnableKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEnableKeyRotation = "EnableKeyRotation" @@ -1105,11 +1264,10 @@ func (c *KMS) EnableKeyRotationRequest(input *EnableKeyRotationInput) (req *requ input = &EnableKeyRotationInput{} } + output = &EnableKeyRotationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &EnableKeyRotationOutput{} - req.Data = output return } @@ -1125,25 +1283,25 @@ func (c *KMS) EnableKeyRotationRequest(input *EnableKeyRotationInput) (req *requ // API operation EnableKeyRotation for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * DisabledException +// * ErrCodeDisabledException "DisabledException" // The request was rejected because the specified CMK is not enabled. // -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -1151,15 +1309,30 @@ func (c *KMS) EnableKeyRotationRequest(input *EnableKeyRotationInput) (req *requ // Key State Affects Use of a Customer Master Key (http://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) // in the AWS Key Management Service Developer Guide. // -// * UnsupportedOperationException +// * ErrCodeUnsupportedOperationException "UnsupportedOperationException" // The request was rejected because a specified parameter is not supported or // a specified resource is not valid for this operation. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/EnableKeyRotation func (c *KMS) EnableKeyRotation(input *EnableKeyRotationInput) (*EnableKeyRotationOutput, error) { req, out := c.EnableKeyRotationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EnableKeyRotationWithContext is the same as EnableKeyRotation with the addition of +// the ability to pass a context and additional request options. +// +// See EnableKeyRotation for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) EnableKeyRotationWithContext(ctx aws.Context, input *EnableKeyRotationInput, opts ...request.Option) (*EnableKeyRotationOutput, error) { + req, out := c.EnableKeyRotationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opEncrypt = "Encrypt" @@ -1200,9 +1373,8 @@ func (c *KMS) EncryptRequest(input *EncryptInput) (req *request.Request, output input = &EncryptInput{} } - req = c.newRequest(op, input, output) output = &EncryptOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1237,32 +1409,32 @@ func (c *KMS) EncryptRequest(input *EncryptInput) (req *request.Request, output // API operation Encrypt for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * DisabledException +// * ErrCodeDisabledException "DisabledException" // The request was rejected because the specified CMK is not enabled. // -// * KeyUnavailableException +// * ErrCodeKeyUnavailableException "KeyUnavailableException" // The request was rejected because the specified CMK was not available. The // request can be retried. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InvalidKeyUsageException +// * ErrCodeInvalidKeyUsageException "InvalidKeyUsageException" // The request was rejected because the specified KeySpec value is not valid. // -// * InvalidGrantTokenException +// * ErrCodeInvalidGrantTokenException "InvalidGrantTokenException" // The request was rejected because the specified grant token is not valid. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -1273,8 +1445,23 @@ func (c *KMS) EncryptRequest(input *EncryptInput) (req *request.Request, output // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/Encrypt func (c *KMS) Encrypt(input *EncryptInput) (*EncryptOutput, error) { req, out := c.EncryptRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// EncryptWithContext is the same as Encrypt with the addition of +// the ability to pass a context and additional request options. +// +// See Encrypt for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) EncryptWithContext(ctx aws.Context, input *EncryptInput, opts ...request.Option) (*EncryptOutput, error) { + req, out := c.EncryptRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGenerateDataKey = "GenerateDataKey" @@ -1315,9 +1502,8 @@ func (c *KMS) GenerateDataKeyRequest(input *GenerateDataKeyInput) (req *request. input = &GenerateDataKeyInput{} } - req = c.newRequest(op, input, output) output = &GenerateDataKeyOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1376,32 +1562,32 @@ func (c *KMS) GenerateDataKeyRequest(input *GenerateDataKeyInput) (req *request. // API operation GenerateDataKey for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * DisabledException +// * ErrCodeDisabledException "DisabledException" // The request was rejected because the specified CMK is not enabled. // -// * KeyUnavailableException +// * ErrCodeKeyUnavailableException "KeyUnavailableException" // The request was rejected because the specified CMK was not available. The // request can be retried. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InvalidKeyUsageException +// * ErrCodeInvalidKeyUsageException "InvalidKeyUsageException" // The request was rejected because the specified KeySpec value is not valid. // -// * InvalidGrantTokenException +// * ErrCodeInvalidGrantTokenException "InvalidGrantTokenException" // The request was rejected because the specified grant token is not valid. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -1412,8 +1598,23 @@ func (c *KMS) GenerateDataKeyRequest(input *GenerateDataKeyInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GenerateDataKey func (c *KMS) GenerateDataKey(input *GenerateDataKeyInput) (*GenerateDataKeyOutput, error) { req, out := c.GenerateDataKeyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GenerateDataKeyWithContext is the same as GenerateDataKey with the addition of +// the ability to pass a context and additional request options. +// +// See GenerateDataKey for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) GenerateDataKeyWithContext(ctx aws.Context, input *GenerateDataKeyInput, opts ...request.Option) (*GenerateDataKeyOutput, error) { + req, out := c.GenerateDataKeyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGenerateDataKeyWithoutPlaintext = "GenerateDataKeyWithoutPlaintext" @@ -1454,9 +1655,8 @@ func (c *KMS) GenerateDataKeyWithoutPlaintextRequest(input *GenerateDataKeyWitho input = &GenerateDataKeyWithoutPlaintextInput{} } - req = c.newRequest(op, input, output) output = &GenerateDataKeyWithoutPlaintextOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1486,32 +1686,32 @@ func (c *KMS) GenerateDataKeyWithoutPlaintextRequest(input *GenerateDataKeyWitho // API operation GenerateDataKeyWithoutPlaintext for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * DisabledException +// * ErrCodeDisabledException "DisabledException" // The request was rejected because the specified CMK is not enabled. // -// * KeyUnavailableException +// * ErrCodeKeyUnavailableException "KeyUnavailableException" // The request was rejected because the specified CMK was not available. The // request can be retried. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InvalidKeyUsageException +// * ErrCodeInvalidKeyUsageException "InvalidKeyUsageException" // The request was rejected because the specified KeySpec value is not valid. // -// * InvalidGrantTokenException +// * ErrCodeInvalidGrantTokenException "InvalidGrantTokenException" // The request was rejected because the specified grant token is not valid. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -1522,8 +1722,23 @@ func (c *KMS) GenerateDataKeyWithoutPlaintextRequest(input *GenerateDataKeyWitho // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GenerateDataKeyWithoutPlaintext func (c *KMS) GenerateDataKeyWithoutPlaintext(input *GenerateDataKeyWithoutPlaintextInput) (*GenerateDataKeyWithoutPlaintextOutput, error) { req, out := c.GenerateDataKeyWithoutPlaintextRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GenerateDataKeyWithoutPlaintextWithContext is the same as GenerateDataKeyWithoutPlaintext with the addition of +// the ability to pass a context and additional request options. +// +// See GenerateDataKeyWithoutPlaintext for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) GenerateDataKeyWithoutPlaintextWithContext(ctx aws.Context, input *GenerateDataKeyWithoutPlaintextInput, opts ...request.Option) (*GenerateDataKeyWithoutPlaintextOutput, error) { + req, out := c.GenerateDataKeyWithoutPlaintextRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGenerateRandom = "GenerateRandom" @@ -1564,9 +1779,8 @@ func (c *KMS) GenerateRandomRequest(input *GenerateRandomInput) (req *request.Re input = &GenerateRandomInput{} } - req = c.newRequest(op, input, output) output = &GenerateRandomOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1582,19 +1796,34 @@ func (c *KMS) GenerateRandomRequest(input *GenerateRandomInput) (req *request.Re // API operation GenerateRandom for usage and error information. // // Returned Error Codes: -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GenerateRandom func (c *KMS) GenerateRandom(input *GenerateRandomInput) (*GenerateRandomOutput, error) { req, out := c.GenerateRandomRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GenerateRandomWithContext is the same as GenerateRandom with the addition of +// the ability to pass a context and additional request options. +// +// See GenerateRandom for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) GenerateRandomWithContext(ctx aws.Context, input *GenerateRandomInput, opts ...request.Option) (*GenerateRandomOutput, error) { + req, out := c.GenerateRandomRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetKeyPolicy = "GetKeyPolicy" @@ -1635,9 +1864,8 @@ func (c *KMS) GetKeyPolicyRequest(input *GetKeyPolicyInput) (req *request.Reques input = &GetKeyPolicyInput{} } - req = c.newRequest(op, input, output) output = &GetKeyPolicyOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1653,22 +1881,22 @@ func (c *KMS) GetKeyPolicyRequest(input *GetKeyPolicyInput) (req *request.Reques // API operation GetKeyPolicy for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -1679,8 +1907,23 @@ func (c *KMS) GetKeyPolicyRequest(input *GetKeyPolicyInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GetKeyPolicy func (c *KMS) GetKeyPolicy(input *GetKeyPolicyInput) (*GetKeyPolicyOutput, error) { req, out := c.GetKeyPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetKeyPolicyWithContext is the same as GetKeyPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetKeyPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) GetKeyPolicyWithContext(ctx aws.Context, input *GetKeyPolicyInput, opts ...request.Option) (*GetKeyPolicyOutput, error) { + req, out := c.GetKeyPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetKeyRotationStatus = "GetKeyRotationStatus" @@ -1721,9 +1964,8 @@ func (c *KMS) GetKeyRotationStatusRequest(input *GetKeyRotationStatusInput) (req input = &GetKeyRotationStatusInput{} } - req = c.newRequest(op, input, output) output = &GetKeyRotationStatusOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1740,22 +1982,22 @@ func (c *KMS) GetKeyRotationStatusRequest(input *GetKeyRotationStatusInput) (req // API operation GetKeyRotationStatus for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -1763,15 +2005,30 @@ func (c *KMS) GetKeyRotationStatusRequest(input *GetKeyRotationStatusInput) (req // Key State Affects Use of a Customer Master Key (http://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) // in the AWS Key Management Service Developer Guide. // -// * UnsupportedOperationException +// * ErrCodeUnsupportedOperationException "UnsupportedOperationException" // The request was rejected because a specified parameter is not supported or // a specified resource is not valid for this operation. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GetKeyRotationStatus func (c *KMS) GetKeyRotationStatus(input *GetKeyRotationStatusInput) (*GetKeyRotationStatusOutput, error) { req, out := c.GetKeyRotationStatusRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetKeyRotationStatusWithContext is the same as GetKeyRotationStatus with the addition of +// the ability to pass a context and additional request options. +// +// See GetKeyRotationStatus for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) GetKeyRotationStatusWithContext(ctx aws.Context, input *GetKeyRotationStatusInput, opts ...request.Option) (*GetKeyRotationStatusOutput, error) { + req, out := c.GetKeyRotationStatusRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetParametersForImport = "GetParametersForImport" @@ -1812,9 +2069,8 @@ func (c *KMS) GetParametersForImportRequest(input *GetParametersForImportInput) input = &GetParametersForImportInput{} } - req = c.newRequest(op, input, output) output = &GetParametersForImportOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1845,26 +2101,26 @@ func (c *KMS) GetParametersForImportRequest(input *GetParametersForImportInput) // API operation GetParametersForImport for usage and error information. // // Returned Error Codes: -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * UnsupportedOperationException +// * ErrCodeUnsupportedOperationException "UnsupportedOperationException" // The request was rejected because a specified parameter is not supported or // a specified resource is not valid for this operation. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -1875,8 +2131,23 @@ func (c *KMS) GetParametersForImportRequest(input *GetParametersForImportInput) // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/GetParametersForImport func (c *KMS) GetParametersForImport(input *GetParametersForImportInput) (*GetParametersForImportOutput, error) { req, out := c.GetParametersForImportRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetParametersForImportWithContext is the same as GetParametersForImport with the addition of +// the ability to pass a context and additional request options. +// +// See GetParametersForImport for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) GetParametersForImportWithContext(ctx aws.Context, input *GetParametersForImportInput, opts ...request.Option) (*GetParametersForImportOutput, error) { + req, out := c.GetParametersForImportRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opImportKeyMaterial = "ImportKeyMaterial" @@ -1917,9 +2188,8 @@ func (c *KMS) ImportKeyMaterialRequest(input *ImportKeyMaterialInput) (req *requ input = &ImportKeyMaterialInput{} } - req = c.newRequest(op, input, output) output = &ImportKeyMaterialOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1955,26 +2225,26 @@ func (c *KMS) ImportKeyMaterialRequest(input *ImportKeyMaterialInput) (req *requ // API operation ImportKeyMaterial for usage and error information. // // Returned Error Codes: -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * UnsupportedOperationException +// * ErrCodeUnsupportedOperationException "UnsupportedOperationException" // The request was rejected because a specified parameter is not supported or // a specified resource is not valid for this operation. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -1982,30 +2252,45 @@ func (c *KMS) ImportKeyMaterialRequest(input *ImportKeyMaterialInput) (req *requ // Key State Affects Use of a Customer Master Key (http://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) // in the AWS Key Management Service Developer Guide. // -// * InvalidCiphertextException +// * ErrCodeInvalidCiphertextException "InvalidCiphertextException" // The request was rejected because the specified ciphertext has been corrupted // or is otherwise invalid. // -// * IncorrectKeyMaterialException +// * ErrCodeIncorrectKeyMaterialException "IncorrectKeyMaterialException" // The request was rejected because the provided key material is invalid or // is not the same key material that was previously imported into this customer // master key (CMK). // -// * ExpiredImportTokenException +// * ErrCodeExpiredImportTokenException "ExpiredImportTokenException" // The request was rejected because the provided import token is expired. Use // GetParametersForImport to retrieve a new import token and public key, use // the new public key to encrypt the key material, and then try the request // again. // -// * InvalidImportTokenException +// * ErrCodeInvalidImportTokenException "InvalidImportTokenException" // The request was rejected because the provided import token is invalid or // is associated with a different customer master key (CMK). // // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ImportKeyMaterial func (c *KMS) ImportKeyMaterial(input *ImportKeyMaterialInput) (*ImportKeyMaterialOutput, error) { req, out := c.ImportKeyMaterialRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ImportKeyMaterialWithContext is the same as ImportKeyMaterial with the addition of +// the ability to pass a context and additional request options. +// +// See ImportKeyMaterial for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ImportKeyMaterialWithContext(ctx aws.Context, input *ImportKeyMaterialInput, opts ...request.Option) (*ImportKeyMaterialOutput, error) { + req, out := c.ImportKeyMaterialRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListAliases = "ListAliases" @@ -2052,9 +2337,8 @@ func (c *KMS) ListAliasesRequest(input *ListAliasesInput) (req *request.Request, input = &ListAliasesInput{} } - req = c.newRequest(op, input, output) output = &ListAliasesOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2070,23 +2354,38 @@ func (c *KMS) ListAliasesRequest(input *ListAliasesInput) (req *request.Request, // API operation ListAliases for usage and error information. // // Returned Error Codes: -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InvalidMarkerException +// * ErrCodeInvalidMarkerException "InvalidMarkerException" // The request was rejected because the marker that specifies where pagination // should next begin is not valid. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ListAliases func (c *KMS) ListAliases(input *ListAliasesInput) (*ListAliasesOutput, error) { req, out := c.ListAliasesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListAliasesWithContext is the same as ListAliases with the addition of +// the ability to pass a context and additional request options. +// +// See ListAliases for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListAliasesWithContext(ctx aws.Context, input *ListAliasesInput, opts ...request.Option) (*ListAliasesOutput, error) { + req, out := c.ListAliasesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListAliasesPages iterates over the pages of a ListAliases operation, @@ -2106,12 +2405,37 @@ func (c *KMS) ListAliases(input *ListAliasesInput) (*ListAliasesOutput, error) { // return pageNum <= 3 // }) // -func (c *KMS) ListAliasesPages(input *ListAliasesInput, fn func(p *ListAliasesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListAliasesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListAliasesOutput), lastPage) - }) +func (c *KMS) ListAliasesPages(input *ListAliasesInput, fn func(*ListAliasesOutput, bool) bool) error { + return c.ListAliasesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAliasesPagesWithContext same as ListAliasesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListAliasesPagesWithContext(ctx aws.Context, input *ListAliasesInput, fn func(*ListAliasesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAliasesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAliasesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListAliasesOutput), !p.HasNextPage()) + } + return p.Err() } const opListGrants = "ListGrants" @@ -2158,9 +2482,8 @@ func (c *KMS) ListGrantsRequest(input *ListGrantsInput) (req *request.Request, o input = &ListGrantsInput{} } - req = c.newRequest(op, input, output) output = &ListGrantsResponse{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2176,26 +2499,26 @@ func (c *KMS) ListGrantsRequest(input *ListGrantsInput) (req *request.Request, o // API operation ListGrants for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InvalidMarkerException +// * ErrCodeInvalidMarkerException "InvalidMarkerException" // The request was rejected because the marker that specifies where pagination // should next begin is not valid. // -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -2206,8 +2529,23 @@ func (c *KMS) ListGrantsRequest(input *ListGrantsInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ListGrants func (c *KMS) ListGrants(input *ListGrantsInput) (*ListGrantsResponse, error) { req, out := c.ListGrantsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListGrantsWithContext is the same as ListGrants with the addition of +// the ability to pass a context and additional request options. +// +// See ListGrants for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListGrantsWithContext(ctx aws.Context, input *ListGrantsInput, opts ...request.Option) (*ListGrantsResponse, error) { + req, out := c.ListGrantsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListGrantsPages iterates over the pages of a ListGrants operation, @@ -2227,12 +2565,37 @@ func (c *KMS) ListGrants(input *ListGrantsInput) (*ListGrantsResponse, error) { // return pageNum <= 3 // }) // -func (c *KMS) ListGrantsPages(input *ListGrantsInput, fn func(p *ListGrantsResponse, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListGrantsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListGrantsResponse), lastPage) - }) +func (c *KMS) ListGrantsPages(input *ListGrantsInput, fn func(*ListGrantsResponse, bool) bool) error { + return c.ListGrantsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListGrantsPagesWithContext same as ListGrantsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListGrantsPagesWithContext(ctx aws.Context, input *ListGrantsInput, fn func(*ListGrantsResponse, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListGrantsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListGrantsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListGrantsResponse), !p.HasNextPage()) + } + return p.Err() } const opListKeyPolicies = "ListKeyPolicies" @@ -2279,9 +2642,8 @@ func (c *KMS) ListKeyPoliciesRequest(input *ListKeyPoliciesInput) (req *request. input = &ListKeyPoliciesInput{} } - req = c.newRequest(op, input, output) output = &ListKeyPoliciesOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2297,22 +2659,22 @@ func (c *KMS) ListKeyPoliciesRequest(input *ListKeyPoliciesInput) (req *request. // API operation ListKeyPolicies for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -2323,8 +2685,23 @@ func (c *KMS) ListKeyPoliciesRequest(input *ListKeyPoliciesInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ListKeyPolicies func (c *KMS) ListKeyPolicies(input *ListKeyPoliciesInput) (*ListKeyPoliciesOutput, error) { req, out := c.ListKeyPoliciesRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListKeyPoliciesWithContext is the same as ListKeyPolicies with the addition of +// the ability to pass a context and additional request options. +// +// See ListKeyPolicies for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListKeyPoliciesWithContext(ctx aws.Context, input *ListKeyPoliciesInput, opts ...request.Option) (*ListKeyPoliciesOutput, error) { + req, out := c.ListKeyPoliciesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListKeyPoliciesPages iterates over the pages of a ListKeyPolicies operation, @@ -2344,12 +2721,37 @@ func (c *KMS) ListKeyPolicies(input *ListKeyPoliciesInput) (*ListKeyPoliciesOutp // return pageNum <= 3 // }) // -func (c *KMS) ListKeyPoliciesPages(input *ListKeyPoliciesInput, fn func(p *ListKeyPoliciesOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListKeyPoliciesRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListKeyPoliciesOutput), lastPage) - }) +func (c *KMS) ListKeyPoliciesPages(input *ListKeyPoliciesInput, fn func(*ListKeyPoliciesOutput, bool) bool) error { + return c.ListKeyPoliciesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListKeyPoliciesPagesWithContext same as ListKeyPoliciesPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListKeyPoliciesPagesWithContext(ctx aws.Context, input *ListKeyPoliciesInput, fn func(*ListKeyPoliciesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListKeyPoliciesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListKeyPoliciesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListKeyPoliciesOutput), !p.HasNextPage()) + } + return p.Err() } const opListKeys = "ListKeys" @@ -2396,9 +2798,8 @@ func (c *KMS) ListKeysRequest(input *ListKeysInput) (req *request.Request, outpu input = &ListKeysInput{} } - req = c.newRequest(op, input, output) output = &ListKeysOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2414,23 +2815,38 @@ func (c *KMS) ListKeysRequest(input *ListKeysInput) (req *request.Request, outpu // API operation ListKeys for usage and error information. // // Returned Error Codes: -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidMarkerException +// * ErrCodeInvalidMarkerException "InvalidMarkerException" // The request was rejected because the marker that specifies where pagination // should next begin is not valid. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ListKeys func (c *KMS) ListKeys(input *ListKeysInput) (*ListKeysOutput, error) { req, out := c.ListKeysRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListKeysWithContext is the same as ListKeys with the addition of +// the ability to pass a context and additional request options. +// +// See ListKeys for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListKeysWithContext(ctx aws.Context, input *ListKeysInput, opts ...request.Option) (*ListKeysOutput, error) { + req, out := c.ListKeysRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListKeysPages iterates over the pages of a ListKeys operation, @@ -2450,12 +2866,129 @@ func (c *KMS) ListKeys(input *ListKeysInput) (*ListKeysOutput, error) { // return pageNum <= 3 // }) // -func (c *KMS) ListKeysPages(input *ListKeysInput, fn func(p *ListKeysOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListKeysRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListKeysOutput), lastPage) - }) +func (c *KMS) ListKeysPages(input *ListKeysInput, fn func(*ListKeysOutput, bool) bool) error { + return c.ListKeysPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListKeysPagesWithContext same as ListKeysPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListKeysPagesWithContext(ctx aws.Context, input *ListKeysInput, fn func(*ListKeysOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListKeysInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListKeysRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListKeysOutput), !p.HasNextPage()) + } + return p.Err() +} + +const opListResourceTags = "ListResourceTags" + +// ListResourceTagsRequest generates a "aws/request.Request" representing the +// client's request for the ListResourceTags operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See ListResourceTags for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the ListResourceTags method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the ListResourceTagsRequest method. +// req, resp := client.ListResourceTagsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ListResourceTags +func (c *KMS) ListResourceTagsRequest(input *ListResourceTagsInput) (req *request.Request, output *ListResourceTagsOutput) { + op := &request.Operation{ + Name: opListResourceTags, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ListResourceTagsInput{} + } + + output = &ListResourceTagsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ListResourceTags API operation for AWS Key Management Service. +// +// Returns a list of all tags for the specified customer master key (CMK). +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Key Management Service's +// API operation ListResourceTags for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInternalException "InternalException" +// The request was rejected because an internal exception occurred. The request +// can be retried. +// +// * ErrCodeNotFoundException "NotFoundException" +// The request was rejected because the specified entity or resource could not +// be found. +// +// * ErrCodeInvalidArnException "InvalidArnException" +// The request was rejected because a specified ARN was not valid. +// +// * ErrCodeInvalidMarkerException "InvalidMarkerException" +// The request was rejected because the marker that specifies where pagination +// should next begin is not valid. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ListResourceTags +func (c *KMS) ListResourceTags(input *ListResourceTagsInput) (*ListResourceTagsOutput, error) { + req, out := c.ListResourceTagsRequest(input) + return out, req.Send() +} + +// ListResourceTagsWithContext is the same as ListResourceTags with the addition of +// the ability to pass a context and additional request options. +// +// See ListResourceTags for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListResourceTagsWithContext(ctx aws.Context, input *ListResourceTagsInput, opts ...request.Option) (*ListResourceTagsOutput, error) { + req, out := c.ListResourceTagsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListRetirableGrants = "ListRetirableGrants" @@ -2496,9 +3029,8 @@ func (c *KMS) ListRetirableGrantsRequest(input *ListRetirableGrantsInput) (req * input = &ListRetirableGrantsInput{} } - req = c.newRequest(op, input, output) output = &ListGrantsResponse{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2518,30 +3050,45 @@ func (c *KMS) ListRetirableGrantsRequest(input *ListRetirableGrantsInput) (req * // API operation ListRetirableGrants for usage and error information. // // Returned Error Codes: -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InvalidMarkerException +// * ErrCodeInvalidMarkerException "InvalidMarkerException" // The request was rejected because the marker that specifies where pagination // should next begin is not valid. // -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ListRetirableGrants func (c *KMS) ListRetirableGrants(input *ListRetirableGrantsInput) (*ListGrantsResponse, error) { req, out := c.ListRetirableGrantsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListRetirableGrantsWithContext is the same as ListRetirableGrants with the addition of +// the ability to pass a context and additional request options. +// +// See ListRetirableGrants for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ListRetirableGrantsWithContext(ctx aws.Context, input *ListRetirableGrantsInput, opts ...request.Option) (*ListGrantsResponse, error) { + req, out := c.ListRetirableGrantsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutKeyPolicy = "PutKeyPolicy" @@ -2582,11 +3129,10 @@ func (c *KMS) PutKeyPolicyRequest(input *PutKeyPolicyInput) (req *request.Reques input = &PutKeyPolicyInput{} } + output = &PutKeyPolicyOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutKeyPolicyOutput{} - req.Data = output return } @@ -2605,35 +3151,35 @@ func (c *KMS) PutKeyPolicyRequest(input *PutKeyPolicyInput) (req *request.Reques // API operation PutKeyPolicy for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * MalformedPolicyDocumentException +// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocumentException" // The request was rejected because the specified policy is not syntactically // or semantically correct. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * UnsupportedOperationException +// * ErrCodeUnsupportedOperationException "UnsupportedOperationException" // The request was rejected because a specified parameter is not supported or // a specified resource is not valid for this operation. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * LimitExceededException +// * ErrCodeLimitExceededException "LimitExceededException" // The request was rejected because a limit was exceeded. For more information, // see Limits (http://docs.aws.amazon.com/kms/latest/developerguide/limits.html) // in the AWS Key Management Service Developer Guide. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -2644,8 +3190,23 @@ func (c *KMS) PutKeyPolicyRequest(input *PutKeyPolicyInput) (req *request.Reques // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/PutKeyPolicy func (c *KMS) PutKeyPolicy(input *PutKeyPolicyInput) (*PutKeyPolicyOutput, error) { req, out := c.PutKeyPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutKeyPolicyWithContext is the same as PutKeyPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See PutKeyPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) PutKeyPolicyWithContext(ctx aws.Context, input *PutKeyPolicyInput, opts ...request.Option) (*PutKeyPolicyOutput, error) { + req, out := c.PutKeyPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opReEncrypt = "ReEncrypt" @@ -2686,9 +3247,8 @@ func (c *KMS) ReEncryptRequest(input *ReEncryptInput) (req *request.Request, out input = &ReEncryptInput{} } - req = c.newRequest(op, input, output) output = &ReEncryptOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2715,36 +3275,36 @@ func (c *KMS) ReEncryptRequest(input *ReEncryptInput) (req *request.Request, out // API operation ReEncrypt for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * DisabledException +// * ErrCodeDisabledException "DisabledException" // The request was rejected because the specified CMK is not enabled. // -// * InvalidCiphertextException +// * ErrCodeInvalidCiphertextException "InvalidCiphertextException" // The request was rejected because the specified ciphertext has been corrupted // or is otherwise invalid. // -// * KeyUnavailableException +// * ErrCodeKeyUnavailableException "KeyUnavailableException" // The request was rejected because the specified CMK was not available. The // request can be retried. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InvalidKeyUsageException +// * ErrCodeInvalidKeyUsageException "InvalidKeyUsageException" // The request was rejected because the specified KeySpec value is not valid. // -// * InvalidGrantTokenException +// * ErrCodeInvalidGrantTokenException "InvalidGrantTokenException" // The request was rejected because the specified grant token is not valid. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -2755,8 +3315,23 @@ func (c *KMS) ReEncryptRequest(input *ReEncryptInput) (req *request.Request, out // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ReEncrypt func (c *KMS) ReEncrypt(input *ReEncryptInput) (*ReEncryptOutput, error) { req, out := c.ReEncryptRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ReEncryptWithContext is the same as ReEncrypt with the addition of +// the ability to pass a context and additional request options. +// +// See ReEncrypt for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ReEncryptWithContext(ctx aws.Context, input *ReEncryptInput, opts ...request.Option) (*ReEncryptOutput, error) { + req, out := c.ReEncryptRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRetireGrant = "RetireGrant" @@ -2797,11 +3372,10 @@ func (c *KMS) RetireGrantRequest(input *RetireGrantInput) (req *request.Request, input = &RetireGrantInput{} } + output = &RetireGrantOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &RetireGrantOutput{} - req.Data = output return } @@ -2832,25 +3406,25 @@ func (c *KMS) RetireGrantRequest(input *RetireGrantInput) (req *request.Request, // API operation RetireGrant for usage and error information. // // Returned Error Codes: -// * InvalidGrantTokenException +// * ErrCodeInvalidGrantTokenException "InvalidGrantTokenException" // The request was rejected because the specified grant token is not valid. // -// * InvalidGrantIdException +// * ErrCodeInvalidGrantIdException "InvalidGrantIdException" // The request was rejected because the specified GrantId is not valid. // -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -2861,8 +3435,23 @@ func (c *KMS) RetireGrantRequest(input *RetireGrantInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/RetireGrant func (c *KMS) RetireGrant(input *RetireGrantInput) (*RetireGrantOutput, error) { req, out := c.RetireGrantRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RetireGrantWithContext is the same as RetireGrant with the addition of +// the ability to pass a context and additional request options. +// +// See RetireGrant for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) RetireGrantWithContext(ctx aws.Context, input *RetireGrantInput, opts ...request.Option) (*RetireGrantOutput, error) { + req, out := c.RetireGrantRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRevokeGrant = "RevokeGrant" @@ -2903,11 +3492,10 @@ func (c *KMS) RevokeGrantRequest(input *RevokeGrantInput) (req *request.Request, input = &RevokeGrantInput{} } + output = &RevokeGrantOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &RevokeGrantOutput{} - req.Data = output return } @@ -2924,25 +3512,25 @@ func (c *KMS) RevokeGrantRequest(input *RevokeGrantInput) (req *request.Request, // API operation RevokeGrant for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * InvalidGrantIdException +// * ErrCodeInvalidGrantIdException "InvalidGrantIdException" // The request was rejected because the specified GrantId is not valid. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -2953,8 +3541,23 @@ func (c *KMS) RevokeGrantRequest(input *RevokeGrantInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/RevokeGrant func (c *KMS) RevokeGrant(input *RevokeGrantInput) (*RevokeGrantOutput, error) { req, out := c.RevokeGrantRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RevokeGrantWithContext is the same as RevokeGrant with the addition of +// the ability to pass a context and additional request options. +// +// See RevokeGrant for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) RevokeGrantWithContext(ctx aws.Context, input *RevokeGrantInput, opts ...request.Option) (*RevokeGrantOutput, error) { + req, out := c.RevokeGrantRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opScheduleKeyDeletion = "ScheduleKeyDeletion" @@ -2995,9 +3598,8 @@ func (c *KMS) ScheduleKeyDeletionRequest(input *ScheduleKeyDeletionInput) (req * input = &ScheduleKeyDeletionInput{} } - req = c.newRequest(op, input, output) output = &ScheduleKeyDeletionOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -3028,22 +3630,22 @@ func (c *KMS) ScheduleKeyDeletionRequest(input *ScheduleKeyDeletionInput) (req * // API operation ScheduleKeyDeletion for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -3054,8 +3656,245 @@ func (c *KMS) ScheduleKeyDeletionRequest(input *ScheduleKeyDeletionInput) (req * // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ScheduleKeyDeletion func (c *KMS) ScheduleKeyDeletion(input *ScheduleKeyDeletionInput) (*ScheduleKeyDeletionOutput, error) { req, out := c.ScheduleKeyDeletionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ScheduleKeyDeletionWithContext is the same as ScheduleKeyDeletion with the addition of +// the ability to pass a context and additional request options. +// +// See ScheduleKeyDeletion for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) ScheduleKeyDeletionWithContext(ctx aws.Context, input *ScheduleKeyDeletionInput, opts ...request.Option) (*ScheduleKeyDeletionOutput, error) { + req, out := c.ScheduleKeyDeletionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opTagResource = "TagResource" + +// TagResourceRequest generates a "aws/request.Request" representing the +// client's request for the TagResource operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See TagResource for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the TagResource method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the TagResourceRequest method. +// req, resp := client.TagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/TagResource +func (c *KMS) TagResourceRequest(input *TagResourceInput) (req *request.Request, output *TagResourceOutput) { + op := &request.Operation{ + Name: opTagResource, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &TagResourceInput{} + } + + output = &TagResourceOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + return +} + +// TagResource API operation for AWS Key Management Service. +// +// Adds or overwrites one or more tags for the specified customer master key +// (CMK). +// +// Each tag consists of a tag key and a tag value. Tag keys and tag values are +// both required, but tag values can be empty (null) strings. +// +// You cannot use the same tag key more than once per CMK. For example, consider +// a CMK with one tag whose tag key is Purpose and tag value is Test. If you +// send a TagResource request for this CMK with a tag key of Purpose and a tag +// value of Prod, it does not create a second tag. Instead, the original tag +// is overwritten with the new tag value. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Key Management Service's +// API operation TagResource for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInternalException "InternalException" +// The request was rejected because an internal exception occurred. The request +// can be retried. +// +// * ErrCodeNotFoundException "NotFoundException" +// The request was rejected because the specified entity or resource could not +// be found. +// +// * ErrCodeInvalidArnException "InvalidArnException" +// The request was rejected because a specified ARN was not valid. +// +// * ErrCodeInvalidStateException "InvalidStateException" +// The request was rejected because the state of the specified resource is not +// valid for this request. +// +// For more information about how key state affects the use of a CMK, see How +// Key State Affects Use of a Customer Master Key (http://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) +// in the AWS Key Management Service Developer Guide. +// +// * ErrCodeLimitExceededException "LimitExceededException" +// The request was rejected because a limit was exceeded. For more information, +// see Limits (http://docs.aws.amazon.com/kms/latest/developerguide/limits.html) +// in the AWS Key Management Service Developer Guide. +// +// * ErrCodeTagException "TagException" +// The request was rejected because one or more tags are not valid. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/TagResource +func (c *KMS) TagResource(input *TagResourceInput) (*TagResourceOutput, error) { + req, out := c.TagResourceRequest(input) + return out, req.Send() +} + +// TagResourceWithContext is the same as TagResource with the addition of +// the ability to pass a context and additional request options. +// +// See TagResource for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) TagResourceWithContext(ctx aws.Context, input *TagResourceInput, opts ...request.Option) (*TagResourceOutput, error) { + req, out := c.TagResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opUntagResource = "UntagResource" + +// UntagResourceRequest generates a "aws/request.Request" representing the +// client's request for the UntagResource operation. The "output" return +// value can be used to capture response data after the request's "Send" method +// is called. +// +// See UntagResource for usage and error information. +// +// Creating a request object using this method should be used when you want to inject +// custom logic into the request's lifecycle using a custom handler, or if you want to +// access properties on the request object before or after sending the request. If +// you just want the service response, call the UntagResource method directly +// instead. +// +// Note: You must call the "Send" method on the returned request object in order +// to execute the request. +// +// // Example sending a request using the UntagResourceRequest method. +// req, resp := client.UntagResourceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/UntagResource +func (c *KMS) UntagResourceRequest(input *UntagResourceInput) (req *request.Request, output *UntagResourceOutput) { + op := &request.Operation{ + Name: opUntagResource, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &UntagResourceInput{} + } + + output = &UntagResourceOutput{} + req = c.newRequest(op, input, output) + req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) + req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) + return +} + +// UntagResource API operation for AWS Key Management Service. +// +// Removes the specified tag or tags from the specified customer master key +// (CMK). +// +// To remove a tag, you specify the tag key for each tag to remove. You do not +// specify the tag value. To overwrite the tag value for an existing tag, use +// TagResource. +// +// Returns awserr.Error for service API and SDK errors. Use runtime type assertions +// with awserr.Error's Code and Message methods to get detailed information about +// the error. +// +// See the AWS API reference guide for AWS Key Management Service's +// API operation UntagResource for usage and error information. +// +// Returned Error Codes: +// * ErrCodeInternalException "InternalException" +// The request was rejected because an internal exception occurred. The request +// can be retried. +// +// * ErrCodeNotFoundException "NotFoundException" +// The request was rejected because the specified entity or resource could not +// be found. +// +// * ErrCodeInvalidArnException "InvalidArnException" +// The request was rejected because a specified ARN was not valid. +// +// * ErrCodeInvalidStateException "InvalidStateException" +// The request was rejected because the state of the specified resource is not +// valid for this request. +// +// For more information about how key state affects the use of a CMK, see How +// Key State Affects Use of a Customer Master Key (http://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) +// in the AWS Key Management Service Developer Guide. +// +// * ErrCodeTagException "TagException" +// The request was rejected because one or more tags are not valid. +// +// Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/UntagResource +func (c *KMS) UntagResource(input *UntagResourceInput) (*UntagResourceOutput, error) { + req, out := c.UntagResourceRequest(input) + return out, req.Send() +} + +// UntagResourceWithContext is the same as UntagResource with the addition of +// the ability to pass a context and additional request options. +// +// See UntagResource for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) UntagResourceWithContext(ctx aws.Context, input *UntagResourceInput, opts ...request.Option) (*UntagResourceOutput, error) { + req, out := c.UntagResourceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateAlias = "UpdateAlias" @@ -3096,11 +3935,10 @@ func (c *KMS) UpdateAliasRequest(input *UpdateAliasInput) (req *request.Request, input = &UpdateAliasInput{} } + output = &UpdateAliasOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &UpdateAliasOutput{} - req.Data = output return } @@ -3128,19 +3966,19 @@ func (c *KMS) UpdateAliasRequest(input *UpdateAliasInput) (req *request.Request, // API operation UpdateAlias for usage and error information. // // Returned Error Codes: -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -3151,8 +3989,23 @@ func (c *KMS) UpdateAliasRequest(input *UpdateAliasInput) (req *request.Request, // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/UpdateAlias func (c *KMS) UpdateAlias(input *UpdateAliasInput) (*UpdateAliasOutput, error) { req, out := c.UpdateAliasRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateAliasWithContext is the same as UpdateAlias with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateAlias for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) UpdateAliasWithContext(ctx aws.Context, input *UpdateAliasInput, opts ...request.Option) (*UpdateAliasOutput, error) { + req, out := c.UpdateAliasRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUpdateKeyDescription = "UpdateKeyDescription" @@ -3193,11 +4046,10 @@ func (c *KMS) UpdateKeyDescriptionRequest(input *UpdateKeyDescriptionInput) (req input = &UpdateKeyDescriptionInput{} } + output = &UpdateKeyDescriptionOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(jsonrpc.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &UpdateKeyDescriptionOutput{} - req.Data = output return } @@ -3213,22 +4065,22 @@ func (c *KMS) UpdateKeyDescriptionRequest(input *UpdateKeyDescriptionInput) (req // API operation UpdateKeyDescription for usage and error information. // // Returned Error Codes: -// * NotFoundException +// * ErrCodeNotFoundException "NotFoundException" // The request was rejected because the specified entity or resource could not // be found. // -// * InvalidArnException +// * ErrCodeInvalidArnException "InvalidArnException" // The request was rejected because a specified ARN was not valid. // -// * DependencyTimeoutException +// * ErrCodeDependencyTimeoutException "DependencyTimeoutException" // The system timed out while trying to fulfill the request. The request can // be retried. // -// * InternalException +// * ErrCodeInternalException "InternalException" // The request was rejected because an internal exception occurred. The request // can be retried. // -// * InvalidStateException +// * ErrCodeInvalidStateException "InvalidStateException" // The request was rejected because the state of the specified resource is not // valid for this request. // @@ -3239,8 +4091,23 @@ func (c *KMS) UpdateKeyDescriptionRequest(input *UpdateKeyDescriptionInput) (req // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/UpdateKeyDescription func (c *KMS) UpdateKeyDescription(input *UpdateKeyDescriptionInput) (*UpdateKeyDescriptionOutput, error) { req, out := c.UpdateKeyDescriptionRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UpdateKeyDescriptionWithContext is the same as UpdateKeyDescription with the addition of +// the ability to pass a context and additional request options. +// +// See UpdateKeyDescription for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *KMS) UpdateKeyDescriptionWithContext(ctx aws.Context, input *UpdateKeyDescriptionInput, opts ...request.Option) (*UpdateKeyDescriptionOutput, error) { + req, out := c.UpdateKeyDescriptionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Contains information about an alias. @@ -3649,8 +4516,8 @@ type CreateKeyInput struct { // section in the AWS Key Management Service Developer Guide. // // Use this parameter only when you include a policy in the request and you - // intend to prevent the principal making the request from making a subsequent - // PutKeyPolicy request on the CMK. + // intend to prevent the principal that is making the request from making a + // subsequent PutKeyPolicy request on the CMK. // // The default value is false. BypassPolicyLockoutSafetyCheck *bool `type:"boolean"` @@ -3683,18 +4550,18 @@ type CreateKeyInput struct { // If you specify a policy and do not set BypassPolicyLockoutSafetyCheck to // true, the policy must meet the following criteria: // - // * It must allow the principal making the CreateKey request to make a subsequent - // PutKeyPolicy request on the CMK. This reduces the likelihood that the - // CMK becomes unmanageable. For more information, refer to the scenario - // in the Default Key Policy (http://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html#key-policy-default-allow-root-enable-iam) + // * It must allow the principal that is making the CreateKey request to + // make a subsequent PutKeyPolicy request on the CMK. This reduces the likelihood + // that the CMK becomes unmanageable. For more information, refer to the + // scenario in the Default Key Policy (http://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html#key-policy-default-allow-root-enable-iam) // section in the AWS Key Management Service Developer Guide. // - // * The principal(s) specified in the key policy must exist and be visible - // to AWS KMS. When you create a new AWS principal (for example, an IAM user - // or role), you might need to enforce a delay before specifying the new - // principal in a key policy because the new principal might not immediately - // be visible to AWS KMS. For more information, see Changes that I make are - // not always immediately visible (http://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_general.html#troubleshoot_general_eventual-consistency) + // * The principals that are specified in the key policy must exist and be + // visible to AWS KMS. When you create a new AWS principal (for example, + // an IAM user or role), you might need to enforce a delay before specifying + // the new principal in a key policy because the new principal might not + // immediately be visible to AWS KMS. For more information, see Changes that + // I make are not always immediately visible (http://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_general.html#troubleshoot_general_eventual-consistency) // in the IAM User Guide. // // If you do not specify a policy, AWS KMS attaches a default key policy to @@ -3703,6 +4570,13 @@ type CreateKeyInput struct { // // The policy size limit is 32 KiB (32768 bytes). Policy *string `min:"1" type:"string"` + + // One or more tags. Each tag consists of a tag key and a tag value. Tag keys + // and tag values are both required, but tag values can be empty (null) strings. + // + // Use this parameter to tag the CMK when it is created. Alternately, you can + // omit this parameter and instead tag the CMK after it is created using TagResource. + Tags []*Tag `type:"list"` } // String returns the string representation @@ -3721,6 +4595,16 @@ func (s *CreateKeyInput) Validate() error { if s.Policy != nil && len(*s.Policy) < 1 { invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -3758,6 +4642,12 @@ func (s *CreateKeyInput) SetPolicy(v string) *CreateKeyInput { return s } +// SetTags sets the Tags field's value. +func (s *CreateKeyInput) SetTags(v []*Tag) *CreateKeyInput { + s.Tags = v + return s +} + // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/CreateKeyResponse type CreateKeyOutput struct { _ struct{} `type:"structure"` @@ -5594,17 +6484,17 @@ func (s *KeyMetadata) SetValidTo(v time.Time) *KeyMetadata { type ListAliasesInput struct { _ struct{} `type:"structure"` - // When paginating results, specify the maximum number of items to return in - // the response. If additional items exist beyond the number you specify, the - // Truncated element in the response is set to true. + // Use this parameter to specify the maximum number of items to return. When + // this value is present, AWS KMS does not return more than the specified number + // of items, but it might return fewer. // // This value is optional. If you include a value, it must be between 1 and // 100, inclusive. If you do not include a value, it defaults to 50. Limit *int64 `min:"1" type:"integer"` - // Use this parameter only when paginating results and only in a subsequent - // request after you receive a response with truncated results. Set it to the - // value of NextMarker from the response you just received. + // Use this parameter in a subsequent request after you receive a response with + // truncated results. Set it to the value of NextMarker from the truncated response + // you just received. Marker *string `min:"1" type:"string"` } @@ -5653,13 +6543,14 @@ type ListAliasesOutput struct { // A list of key aliases in the user's account. Aliases []*AliasListEntry `type:"list"` - // When Truncated is true, this value is present and contains the value to use - // for the Marker parameter in a subsequent pagination request. + // When Truncated is true, this element is present and contains the value to + // use for the Marker parameter in a subsequent request. NextMarker *string `min:"1" type:"string"` - // A flag that indicates whether there are more items in the list. If your results - // were truncated, you can use the Marker parameter to make a subsequent pagination - // request to retrieve more items in the list. + // A flag that indicates whether there are more items in the list. When this + // value is true, the list in this response is truncated. To retrieve more items, + // pass the value of the NextMarker element in this response to the Marker parameter + // in a subsequent request. Truncated *bool `type:"boolean"` } @@ -5705,17 +6596,17 @@ type ListGrantsInput struct { // KeyId is a required field KeyId *string `min:"1" type:"string" required:"true"` - // When paginating results, specify the maximum number of items to return in - // the response. If additional items exist beyond the number you specify, the - // Truncated element in the response is set to true. + // Use this parameter to specify the maximum number of items to return. When + // this value is present, AWS KMS does not return more than the specified number + // of items, but it might return fewer. // // This value is optional. If you include a value, it must be between 1 and // 100, inclusive. If you do not include a value, it defaults to 50. Limit *int64 `min:"1" type:"integer"` - // Use this parameter only when paginating results and only in a subsequent - // request after you receive a response with truncated results. Set it to the - // value of NextMarker from the response you just received. + // Use this parameter in a subsequent request after you receive a response with + // truncated results. Set it to the value of NextMarker from the truncated response + // you just received. Marker *string `min:"1" type:"string"` } @@ -5776,13 +6667,14 @@ type ListGrantsResponse struct { // A list of grants. Grants []*GrantListEntry `type:"list"` - // When Truncated is true, this value is present and contains the value to use - // for the Marker parameter in a subsequent pagination request. + // When Truncated is true, this element is present and contains the value to + // use for the Marker parameter in a subsequent request. NextMarker *string `min:"1" type:"string"` - // A flag that indicates whether there are more items in the list. If your results - // were truncated, you can use the Marker parameter to make a subsequent pagination - // request to retrieve more items in the list. + // A flag that indicates whether there are more items in the list. When this + // value is true, the list in this response is truncated. To retrieve more items, + // pass the value of the NextMarker element in this response to the Marker parameter + // in a subsequent request. Truncated *bool `type:"boolean"` } @@ -5828,9 +6720,9 @@ type ListKeyPoliciesInput struct { // KeyId is a required field KeyId *string `min:"1" type:"string" required:"true"` - // When paginating results, specify the maximum number of items to return in - // the response. If additional items exist beyond the number you specify, the - // Truncated element in the response is set to true. + // Use this parameter to specify the maximum number of items to return. When + // this value is present, AWS KMS does not return more than the specified number + // of items, but it might return fewer. // // This value is optional. If you include a value, it must be between 1 and // 1000, inclusive. If you do not include a value, it defaults to 100. @@ -5838,9 +6730,9 @@ type ListKeyPoliciesInput struct { // Currently only 1 policy can be attached to a key. Limit *int64 `min:"1" type:"integer"` - // Use this parameter only when paginating results and only in a subsequent - // request after you receive a response with truncated results. Set it to the - // value of NextMarker from the response you just received. + // Use this parameter in a subsequent request after you receive a response with + // truncated results. Set it to the value of NextMarker from the truncated response + // you just received. Marker *string `min:"1" type:"string"` } @@ -5898,17 +6790,18 @@ func (s *ListKeyPoliciesInput) SetMarker(v string) *ListKeyPoliciesInput { type ListKeyPoliciesOutput struct { _ struct{} `type:"structure"` - // When Truncated is true, this value is present and contains the value to use - // for the Marker parameter in a subsequent pagination request. + // When Truncated is true, this element is present and contains the value to + // use for the Marker parameter in a subsequent request. NextMarker *string `min:"1" type:"string"` // A list of policy names. Currently, there is only one policy and it is named // "Default". PolicyNames []*string `type:"list"` - // A flag that indicates whether there are more items in the list. If your results - // were truncated, you can use the Marker parameter to make a subsequent pagination - // request to retrieve more items in the list. + // A flag that indicates whether there are more items in the list. When this + // value is true, the list in this response is truncated. To retrieve more items, + // pass the value of the NextMarker element in this response to the Marker parameter + // in a subsequent request. Truncated *bool `type:"boolean"` } @@ -5944,17 +6837,17 @@ func (s *ListKeyPoliciesOutput) SetTruncated(v bool) *ListKeyPoliciesOutput { type ListKeysInput struct { _ struct{} `type:"structure"` - // When paginating results, specify the maximum number of items to return in - // the response. If additional items exist beyond the number you specify, the - // Truncated element in the response is set to true. + // Use this parameter to specify the maximum number of items to return. When + // this value is present, AWS KMS does not return more than the specified number + // of items, but it might return fewer. // // This value is optional. If you include a value, it must be between 1 and // 1000, inclusive. If you do not include a value, it defaults to 100. Limit *int64 `min:"1" type:"integer"` - // Use this parameter only when paginating results and only in a subsequent - // request after you receive a response with truncated results. Set it to the - // value of NextMarker from the response you just received. + // Use this parameter in a subsequent request after you receive a response with + // truncated results. Set it to the value of NextMarker from the truncated response + // you just received. Marker *string `min:"1" type:"string"` } @@ -6003,13 +6896,14 @@ type ListKeysOutput struct { // A list of keys. Keys []*KeyListEntry `type:"list"` - // When Truncated is true, this value is present and contains the value to use - // for the Marker parameter in a subsequent pagination request. + // When Truncated is true, this element is present and contains the value to + // use for the Marker parameter in a subsequent request. NextMarker *string `min:"1" type:"string"` - // A flag that indicates whether there are more items in the list. If your results - // were truncated, you can use the Marker parameter to make a subsequent pagination - // request to retrieve more items in the list. + // A flag that indicates whether there are more items in the list. When this + // value is true, the list in this response is truncated. To retrieve more items, + // pass the value of the NextMarker element in this response to the Marker parameter + // in a subsequent request. Truncated *bool `type:"boolean"` } @@ -6041,21 +6935,150 @@ func (s *ListKeysOutput) SetTruncated(v bool) *ListKeysOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ListResourceTagsRequest +type ListResourceTagsInput struct { + _ struct{} `type:"structure"` + + // A unique identifier for the CMK whose tags you are listing. You can use the + // unique key ID or the Amazon Resource Name (ARN) of the CMK. Examples: + // + // * Unique key ID: 1234abcd-12ab-34cd-56ef-1234567890ab + // + // * Key ARN: arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab + // + // KeyId is a required field + KeyId *string `min:"1" type:"string" required:"true"` + + // Use this parameter to specify the maximum number of items to return. When + // this value is present, AWS KMS does not return more than the specified number + // of items, but it might return fewer. + // + // This value is optional. If you include a value, it must be between 1 and + // 50, inclusive. If you do not include a value, it defaults to 50. + Limit *int64 `min:"1" type:"integer"` + + // Use this parameter in a subsequent request after you receive a response with + // truncated results. Set it to the value of NextMarker from the truncated response + // you just received. + // + // Do not attempt to construct this value. Use only the value of NextMarker + // from the truncated response you just received. + Marker *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ListResourceTagsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListResourceTagsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ListResourceTagsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ListResourceTagsInput"} + if s.KeyId == nil { + invalidParams.Add(request.NewErrParamRequired("KeyId")) + } + if s.KeyId != nil && len(*s.KeyId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("KeyId", 1)) + } + if s.Limit != nil && *s.Limit < 1 { + invalidParams.Add(request.NewErrParamMinValue("Limit", 1)) + } + if s.Marker != nil && len(*s.Marker) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Marker", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetKeyId sets the KeyId field's value. +func (s *ListResourceTagsInput) SetKeyId(v string) *ListResourceTagsInput { + s.KeyId = &v + return s +} + +// SetLimit sets the Limit field's value. +func (s *ListResourceTagsInput) SetLimit(v int64) *ListResourceTagsInput { + s.Limit = &v + return s +} + +// SetMarker sets the Marker field's value. +func (s *ListResourceTagsInput) SetMarker(v string) *ListResourceTagsInput { + s.Marker = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ListResourceTagsResponse +type ListResourceTagsOutput struct { + _ struct{} `type:"structure"` + + // When Truncated is true, this element is present and contains the value to + // use for the Marker parameter in a subsequent request. + // + // Do not assume or infer any information from this value. + NextMarker *string `min:"1" type:"string"` + + // A list of tags. Each tag consists of a tag key and a tag value. + Tags []*Tag `type:"list"` + + // A flag that indicates whether there are more items in the list. When this + // value is true, the list in this response is truncated. To retrieve more items, + // pass the value of the NextMarker element in this response to the Marker parameter + // in a subsequent request. + Truncated *bool `type:"boolean"` +} + +// String returns the string representation +func (s ListResourceTagsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ListResourceTagsOutput) GoString() string { + return s.String() +} + +// SetNextMarker sets the NextMarker field's value. +func (s *ListResourceTagsOutput) SetNextMarker(v string) *ListResourceTagsOutput { + s.NextMarker = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *ListResourceTagsOutput) SetTags(v []*Tag) *ListResourceTagsOutput { + s.Tags = v + return s +} + +// SetTruncated sets the Truncated field's value. +func (s *ListResourceTagsOutput) SetTruncated(v bool) *ListResourceTagsOutput { + s.Truncated = &v + return s +} + // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/ListRetirableGrantsRequest type ListRetirableGrantsInput struct { _ struct{} `type:"structure"` - // When paginating results, specify the maximum number of items to return in - // the response. If additional items exist beyond the number you specify, the - // Truncated element in the response is set to true. + // Use this parameter to specify the maximum number of items to return. When + // this value is present, AWS KMS does not return more than the specified number + // of items, but it might return fewer. // // This value is optional. If you include a value, it must be between 1 and // 100, inclusive. If you do not include a value, it defaults to 50. Limit *int64 `min:"1" type:"integer"` - // Use this parameter only when paginating results and only in a subsequent - // request after you receive a response with truncated results. Set it to the - // value of NextMarker from the response you just received. + // Use this parameter in a subsequent request after you receive a response with + // truncated results. Set it to the value of NextMarker from the truncated response + // you just received. Marker *string `min:"1" type:"string"` // The retiring principal for which to list grants. @@ -6133,8 +7156,8 @@ type PutKeyPolicyInput struct { // For more information, refer to the scenario in the Default Key Policy (http://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html#key-policy-default-allow-root-enable-iam) // section in the AWS Key Management Service Developer Guide. // - // Use this parameter only when you intend to prevent the principal making the - // request from making a subsequent PutKeyPolicy request on the CMK. + // Use this parameter only when you intend to prevent the principal that is + // making the request from making a subsequent PutKeyPolicy request on the CMK. // // The default value is false. BypassPolicyLockoutSafetyCheck *bool `type:"boolean"` @@ -6155,18 +7178,18 @@ type PutKeyPolicyInput struct { // If you do not set BypassPolicyLockoutSafetyCheck to true, the policy must // meet the following criteria: // - // * It must allow the principal making the PutKeyPolicy request to make - // a subsequent PutKeyPolicy request on the CMK. This reduces the likelihood - // that the CMK becomes unmanageable. For more information, refer to the - // scenario in the Default Key Policy (http://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html#key-policy-default-allow-root-enable-iam) + // * It must allow the principal that is making the PutKeyPolicy request + // to make a subsequent PutKeyPolicy request on the CMK. This reduces the + // likelihood that the CMK becomes unmanageable. For more information, refer + // to the scenario in the Default Key Policy (http://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html#key-policy-default-allow-root-enable-iam) // section in the AWS Key Management Service Developer Guide. // - // * The principal(s) specified in the key policy must exist and be visible - // to AWS KMS. When you create a new AWS principal (for example, an IAM user - // or role), you might need to enforce a delay before specifying the new - // principal in a key policy because the new principal might not immediately - // be visible to AWS KMS. For more information, see Changes that I make are - // not always immediately visible (http://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_general.html#troubleshoot_general_eventual-consistency) + // * The principals that are specified in the key policy must exist and be + // visible to AWS KMS. When you create a new AWS principal (for example, + // an IAM user or role), you might need to enforce a delay before specifying + // the new principal in a key policy because the new principal might not + // immediately be visible to AWS KMS. For more information, see Changes that + // I make are not always immediately visible (http://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_general.html#troubleshoot_general_eventual-consistency) // in the IAM User Guide. // // The policy size limit is 32 KiB (32768 bytes). @@ -6668,6 +7691,226 @@ func (s *ScheduleKeyDeletionOutput) SetKeyId(v string) *ScheduleKeyDeletionOutpu return s } +// A key-value pair. A tag consists of a tag key and a tag value. Tag keys and +// tag values are both required, but tag values can be empty (null) strings. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/Tag +type Tag struct { + _ struct{} `type:"structure"` + + // The key of the tag. + // + // TagKey is a required field + TagKey *string `min:"1" type:"string" required:"true"` + + // The value of the tag. + // + // TagValue is a required field + TagValue *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s Tag) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Tag) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Tag) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Tag"} + if s.TagKey == nil { + invalidParams.Add(request.NewErrParamRequired("TagKey")) + } + if s.TagKey != nil && len(*s.TagKey) < 1 { + invalidParams.Add(request.NewErrParamMinLen("TagKey", 1)) + } + if s.TagValue == nil { + invalidParams.Add(request.NewErrParamRequired("TagValue")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetTagKey sets the TagKey field's value. +func (s *Tag) SetTagKey(v string) *Tag { + s.TagKey = &v + return s +} + +// SetTagValue sets the TagValue field's value. +func (s *Tag) SetTagValue(v string) *Tag { + s.TagValue = &v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/TagResourceRequest +type TagResourceInput struct { + _ struct{} `type:"structure"` + + // A unique identifier for the CMK you are tagging. You can use the unique key + // ID or the Amazon Resource Name (ARN) of the CMK. Examples: + // + // * Unique key ID: 1234abcd-12ab-34cd-56ef-1234567890ab + // + // * Key ARN: arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab + // + // KeyId is a required field + KeyId *string `min:"1" type:"string" required:"true"` + + // One or more tags. Each tag consists of a tag key and a tag value. + // + // Tags is a required field + Tags []*Tag `type:"list" required:"true"` +} + +// String returns the string representation +func (s TagResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TagResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *TagResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "TagResourceInput"} + if s.KeyId == nil { + invalidParams.Add(request.NewErrParamRequired("KeyId")) + } + if s.KeyId != nil && len(*s.KeyId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("KeyId", 1)) + } + if s.Tags == nil { + invalidParams.Add(request.NewErrParamRequired("Tags")) + } + if s.Tags != nil { + for i, v := range s.Tags { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetKeyId sets the KeyId field's value. +func (s *TagResourceInput) SetKeyId(v string) *TagResourceInput { + s.KeyId = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *TagResourceInput) SetTags(v []*Tag) *TagResourceInput { + s.Tags = v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/TagResourceOutput +type TagResourceOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s TagResourceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TagResourceOutput) GoString() string { + return s.String() +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/UntagResourceRequest +type UntagResourceInput struct { + _ struct{} `type:"structure"` + + // A unique identifier for the CMK from which you are removing tags. You can + // use the unique key ID or the Amazon Resource Name (ARN) of the CMK. Examples: + // + // * Unique key ID: 1234abcd-12ab-34cd-56ef-1234567890ab + // + // * Key ARN: arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab + // + // KeyId is a required field + KeyId *string `min:"1" type:"string" required:"true"` + + // One or more tag keys. Specify only the tag keys, not the tag values. + // + // TagKeys is a required field + TagKeys []*string `type:"list" required:"true"` +} + +// String returns the string representation +func (s UntagResourceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UntagResourceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *UntagResourceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "UntagResourceInput"} + if s.KeyId == nil { + invalidParams.Add(request.NewErrParamRequired("KeyId")) + } + if s.KeyId != nil && len(*s.KeyId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("KeyId", 1)) + } + if s.TagKeys == nil { + invalidParams.Add(request.NewErrParamRequired("TagKeys")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetKeyId sets the KeyId field's value. +func (s *UntagResourceInput) SetKeyId(v string) *UntagResourceInput { + s.KeyId = &v + return s +} + +// SetTagKeys sets the TagKeys field's value. +func (s *UntagResourceInput) SetTagKeys(v []*string) *UntagResourceInput { + s.TagKeys = v + return s +} + +// Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/UntagResourceOutput +type UntagResourceOutput struct { + _ struct{} `type:"structure"` +} + +// String returns the string representation +func (s UntagResourceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UntagResourceOutput) GoString() string { + return s.String() +} + // Please also see https://docs.aws.amazon.com/goto/WebAPI/kms-2014-11-01/UpdateAliasRequest type UpdateAliasInput struct { _ struct{} `type:"structure"` diff --git a/vendor/github.com/aws/aws-sdk-go/service/kms/errors.go b/vendor/github.com/aws/aws-sdk-go/service/kms/errors.go new file mode 100644 index 0000000..0358c94 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/kms/errors.go @@ -0,0 +1,154 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package kms + +const ( + + // ErrCodeAlreadyExistsException for service response error code + // "AlreadyExistsException". + // + // The request was rejected because it attempted to create a resource that already + // exists. + ErrCodeAlreadyExistsException = "AlreadyExistsException" + + // ErrCodeDependencyTimeoutException for service response error code + // "DependencyTimeoutException". + // + // The system timed out while trying to fulfill the request. The request can + // be retried. + ErrCodeDependencyTimeoutException = "DependencyTimeoutException" + + // ErrCodeDisabledException for service response error code + // "DisabledException". + // + // The request was rejected because the specified CMK is not enabled. + ErrCodeDisabledException = "DisabledException" + + // ErrCodeExpiredImportTokenException for service response error code + // "ExpiredImportTokenException". + // + // The request was rejected because the provided import token is expired. Use + // GetParametersForImport to retrieve a new import token and public key, use + // the new public key to encrypt the key material, and then try the request + // again. + ErrCodeExpiredImportTokenException = "ExpiredImportTokenException" + + // ErrCodeIncorrectKeyMaterialException for service response error code + // "IncorrectKeyMaterialException". + // + // The request was rejected because the provided key material is invalid or + // is not the same key material that was previously imported into this customer + // master key (CMK). + ErrCodeIncorrectKeyMaterialException = "IncorrectKeyMaterialException" + + // ErrCodeInternalException for service response error code + // "InternalException". + // + // The request was rejected because an internal exception occurred. The request + // can be retried. + ErrCodeInternalException = "InternalException" + + // ErrCodeInvalidAliasNameException for service response error code + // "InvalidAliasNameException". + // + // The request was rejected because the specified alias name is not valid. + ErrCodeInvalidAliasNameException = "InvalidAliasNameException" + + // ErrCodeInvalidArnException for service response error code + // "InvalidArnException". + // + // The request was rejected because a specified ARN was not valid. + ErrCodeInvalidArnException = "InvalidArnException" + + // ErrCodeInvalidCiphertextException for service response error code + // "InvalidCiphertextException". + // + // The request was rejected because the specified ciphertext has been corrupted + // or is otherwise invalid. + ErrCodeInvalidCiphertextException = "InvalidCiphertextException" + + // ErrCodeInvalidGrantIdException for service response error code + // "InvalidGrantIdException". + // + // The request was rejected because the specified GrantId is not valid. + ErrCodeInvalidGrantIdException = "InvalidGrantIdException" + + // ErrCodeInvalidGrantTokenException for service response error code + // "InvalidGrantTokenException". + // + // The request was rejected because the specified grant token is not valid. + ErrCodeInvalidGrantTokenException = "InvalidGrantTokenException" + + // ErrCodeInvalidImportTokenException for service response error code + // "InvalidImportTokenException". + // + // The request was rejected because the provided import token is invalid or + // is associated with a different customer master key (CMK). + ErrCodeInvalidImportTokenException = "InvalidImportTokenException" + + // ErrCodeInvalidKeyUsageException for service response error code + // "InvalidKeyUsageException". + // + // The request was rejected because the specified KeySpec value is not valid. + ErrCodeInvalidKeyUsageException = "InvalidKeyUsageException" + + // ErrCodeInvalidMarkerException for service response error code + // "InvalidMarkerException". + // + // The request was rejected because the marker that specifies where pagination + // should next begin is not valid. + ErrCodeInvalidMarkerException = "InvalidMarkerException" + + // ErrCodeInvalidStateException for service response error code + // "InvalidStateException". + // + // The request was rejected because the state of the specified resource is not + // valid for this request. + // + // For more information about how key state affects the use of a CMK, see How + // Key State Affects Use of a Customer Master Key (http://docs.aws.amazon.com/kms/latest/developerguide/key-state.html) + // in the AWS Key Management Service Developer Guide. + ErrCodeInvalidStateException = "InvalidStateException" + + // ErrCodeKeyUnavailableException for service response error code + // "KeyUnavailableException". + // + // The request was rejected because the specified CMK was not available. The + // request can be retried. + ErrCodeKeyUnavailableException = "KeyUnavailableException" + + // ErrCodeLimitExceededException for service response error code + // "LimitExceededException". + // + // The request was rejected because a limit was exceeded. For more information, + // see Limits (http://docs.aws.amazon.com/kms/latest/developerguide/limits.html) + // in the AWS Key Management Service Developer Guide. + ErrCodeLimitExceededException = "LimitExceededException" + + // ErrCodeMalformedPolicyDocumentException for service response error code + // "MalformedPolicyDocumentException". + // + // The request was rejected because the specified policy is not syntactically + // or semantically correct. + ErrCodeMalformedPolicyDocumentException = "MalformedPolicyDocumentException" + + // ErrCodeNotFoundException for service response error code + // "NotFoundException". + // + // The request was rejected because the specified entity or resource could not + // be found. + ErrCodeNotFoundException = "NotFoundException" + + // ErrCodeTagException for service response error code + // "TagException". + // + // The request was rejected because one or more tags are not valid. + ErrCodeTagException = "TagException" + + // ErrCodeUnsupportedOperationException for service response error code + // "UnsupportedOperationException". + // + // The request was rejected because a specified parameter is not supported or + // a specified resource is not valid for this operation. + ErrCodeUnsupportedOperationException = "UnsupportedOperationException" +) diff --git a/vendor/github.com/aws/aws-sdk-go/service/kms/service.go b/vendor/github.com/aws/aws-sdk-go/service/kms/service.go index b4688ca..10aeb24 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/kms/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/kms/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package kms diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/api.go b/vendor/github.com/aws/aws-sdk-go/service/s3/api.go index 7a9d2c8..3f0fc2f 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/api.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. // Package s3 provides a client for Amazon Simple Storage Service. package s3 @@ -8,6 +8,7 @@ import ( "io" "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/private/protocol" @@ -40,6 +41,7 @@ const opAbortMultipartUpload = "AbortMultipartUpload" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortMultipartUpload func (c *S3) AbortMultipartUploadRequest(input *AbortMultipartUploadInput) (req *request.Request, output *AbortMultipartUploadOutput) { op := &request.Operation{ Name: opAbortMultipartUpload, @@ -51,9 +53,8 @@ func (c *S3) AbortMultipartUploadRequest(input *AbortMultipartUploadInput) (req input = &AbortMultipartUploadInput{} } - req = c.newRequest(op, input, output) output = &AbortMultipartUploadOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -73,13 +74,29 @@ func (c *S3) AbortMultipartUploadRequest(input *AbortMultipartUploadInput) (req // API operation AbortMultipartUpload for usage and error information. // // Returned Error Codes: -// * NoSuchUpload +// * ErrCodeNoSuchUpload "NoSuchUpload" // The specified multipart upload does not exist. // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortMultipartUpload func (c *S3) AbortMultipartUpload(input *AbortMultipartUploadInput) (*AbortMultipartUploadOutput, error) { req, out := c.AbortMultipartUploadRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AbortMultipartUploadWithContext is the same as AbortMultipartUpload with the addition of +// the ability to pass a context and additional request options. +// +// See AbortMultipartUpload for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) AbortMultipartUploadWithContext(ctx aws.Context, input *AbortMultipartUploadInput, opts ...request.Option) (*AbortMultipartUploadOutput, error) { + req, out := c.AbortMultipartUploadRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCompleteMultipartUpload = "CompleteMultipartUpload" @@ -108,6 +125,7 @@ const opCompleteMultipartUpload = "CompleteMultipartUpload" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompleteMultipartUpload func (c *S3) CompleteMultipartUploadRequest(input *CompleteMultipartUploadInput) (req *request.Request, output *CompleteMultipartUploadOutput) { op := &request.Operation{ Name: opCompleteMultipartUpload, @@ -119,9 +137,8 @@ func (c *S3) CompleteMultipartUploadRequest(input *CompleteMultipartUploadInput) input = &CompleteMultipartUploadInput{} } - req = c.newRequest(op, input, output) output = &CompleteMultipartUploadOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -135,10 +152,26 @@ func (c *S3) CompleteMultipartUploadRequest(input *CompleteMultipartUploadInput) // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation CompleteMultipartUpload for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompleteMultipartUpload func (c *S3) CompleteMultipartUpload(input *CompleteMultipartUploadInput) (*CompleteMultipartUploadOutput, error) { req, out := c.CompleteMultipartUploadRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CompleteMultipartUploadWithContext is the same as CompleteMultipartUpload with the addition of +// the ability to pass a context and additional request options. +// +// See CompleteMultipartUpload for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) CompleteMultipartUploadWithContext(ctx aws.Context, input *CompleteMultipartUploadInput, opts ...request.Option) (*CompleteMultipartUploadOutput, error) { + req, out := c.CompleteMultipartUploadRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCopyObject = "CopyObject" @@ -167,6 +200,7 @@ const opCopyObject = "CopyObject" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObject func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *request.Request, output *CopyObjectOutput) { op := &request.Operation{ Name: opCopyObject, @@ -178,9 +212,8 @@ func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *request.Request, ou input = &CopyObjectInput{} } - req = c.newRequest(op, input, output) output = &CopyObjectOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -196,14 +229,30 @@ func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *request.Request, ou // API operation CopyObject for usage and error information. // // Returned Error Codes: -// * ObjectNotInActiveTierError +// * ErrCodeObjectNotInActiveTierError "ObjectNotInActiveTierError" // The source object of the COPY operation is not in the active tier and is // only stored in Amazon Glacier. // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObject func (c *S3) CopyObject(input *CopyObjectInput) (*CopyObjectOutput, error) { req, out := c.CopyObjectRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CopyObjectWithContext is the same as CopyObject with the addition of +// the ability to pass a context and additional request options. +// +// See CopyObject for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) CopyObjectWithContext(ctx aws.Context, input *CopyObjectInput, opts ...request.Option) (*CopyObjectOutput, error) { + req, out := c.CopyObjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateBucket = "CreateBucket" @@ -232,6 +281,7 @@ const opCreateBucket = "CreateBucket" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucket func (c *S3) CreateBucketRequest(input *CreateBucketInput) (req *request.Request, output *CreateBucketOutput) { op := &request.Operation{ Name: opCreateBucket, @@ -243,9 +293,8 @@ func (c *S3) CreateBucketRequest(input *CreateBucketInput) (req *request.Request input = &CreateBucketInput{} } - req = c.newRequest(op, input, output) output = &CreateBucketOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -261,17 +310,32 @@ func (c *S3) CreateBucketRequest(input *CreateBucketInput) (req *request.Request // API operation CreateBucket for usage and error information. // // Returned Error Codes: -// * BucketAlreadyExists +// * ErrCodeBucketAlreadyExists "BucketAlreadyExists" // The requested bucket name is not available. The bucket namespace is shared // by all users of the system. Please select a different name and try again. // -// * BucketAlreadyOwnedByYou - +// * ErrCodeBucketAlreadyOwnedByYou "BucketAlreadyOwnedByYou" // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucket func (c *S3) CreateBucket(input *CreateBucketInput) (*CreateBucketOutput, error) { req, out := c.CreateBucketRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateBucketWithContext is the same as CreateBucket with the addition of +// the ability to pass a context and additional request options. +// +// See CreateBucket for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) CreateBucketWithContext(ctx aws.Context, input *CreateBucketInput, opts ...request.Option) (*CreateBucketOutput, error) { + req, out := c.CreateBucketRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opCreateMultipartUpload = "CreateMultipartUpload" @@ -300,6 +364,7 @@ const opCreateMultipartUpload = "CreateMultipartUpload" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateMultipartUpload func (c *S3) CreateMultipartUploadRequest(input *CreateMultipartUploadInput) (req *request.Request, output *CreateMultipartUploadOutput) { op := &request.Operation{ Name: opCreateMultipartUpload, @@ -311,9 +376,8 @@ func (c *S3) CreateMultipartUploadRequest(input *CreateMultipartUploadInput) (re input = &CreateMultipartUploadInput{} } - req = c.newRequest(op, input, output) output = &CreateMultipartUploadOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -333,10 +397,26 @@ func (c *S3) CreateMultipartUploadRequest(input *CreateMultipartUploadInput) (re // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation CreateMultipartUpload for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateMultipartUpload func (c *S3) CreateMultipartUpload(input *CreateMultipartUploadInput) (*CreateMultipartUploadOutput, error) { req, out := c.CreateMultipartUploadRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// CreateMultipartUploadWithContext is the same as CreateMultipartUpload with the addition of +// the ability to pass a context and additional request options. +// +// See CreateMultipartUpload for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) CreateMultipartUploadWithContext(ctx aws.Context, input *CreateMultipartUploadInput, opts ...request.Option) (*CreateMultipartUploadOutput, error) { + req, out := c.CreateMultipartUploadRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucket = "DeleteBucket" @@ -365,6 +445,7 @@ const opDeleteBucket = "DeleteBucket" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucket func (c *S3) DeleteBucketRequest(input *DeleteBucketInput) (req *request.Request, output *DeleteBucketOutput) { op := &request.Operation{ Name: opDeleteBucket, @@ -376,11 +457,10 @@ func (c *S3) DeleteBucketRequest(input *DeleteBucketInput) (req *request.Request input = &DeleteBucketInput{} } + output = &DeleteBucketOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &DeleteBucketOutput{} - req.Data = output return } @@ -395,10 +475,26 @@ func (c *S3) DeleteBucketRequest(input *DeleteBucketInput) (req *request.Request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucket for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucket func (c *S3) DeleteBucket(input *DeleteBucketInput) (*DeleteBucketOutput, error) { req, out := c.DeleteBucketRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketWithContext is the same as DeleteBucket with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucket for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketWithContext(ctx aws.Context, input *DeleteBucketInput, opts ...request.Option) (*DeleteBucketOutput, error) { + req, out := c.DeleteBucketRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketAnalyticsConfiguration = "DeleteBucketAnalyticsConfiguration" @@ -427,6 +523,7 @@ const opDeleteBucketAnalyticsConfiguration = "DeleteBucketAnalyticsConfiguration // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketAnalyticsConfiguration func (c *S3) DeleteBucketAnalyticsConfigurationRequest(input *DeleteBucketAnalyticsConfigurationInput) (req *request.Request, output *DeleteBucketAnalyticsConfigurationOutput) { op := &request.Operation{ Name: opDeleteBucketAnalyticsConfiguration, @@ -438,11 +535,10 @@ func (c *S3) DeleteBucketAnalyticsConfigurationRequest(input *DeleteBucketAnalyt input = &DeleteBucketAnalyticsConfigurationInput{} } + output = &DeleteBucketAnalyticsConfigurationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &DeleteBucketAnalyticsConfigurationOutput{} - req.Data = output return } @@ -457,10 +553,26 @@ func (c *S3) DeleteBucketAnalyticsConfigurationRequest(input *DeleteBucketAnalyt // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketAnalyticsConfiguration for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketAnalyticsConfiguration func (c *S3) DeleteBucketAnalyticsConfiguration(input *DeleteBucketAnalyticsConfigurationInput) (*DeleteBucketAnalyticsConfigurationOutput, error) { req, out := c.DeleteBucketAnalyticsConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketAnalyticsConfigurationWithContext is the same as DeleteBucketAnalyticsConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketAnalyticsConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketAnalyticsConfigurationWithContext(ctx aws.Context, input *DeleteBucketAnalyticsConfigurationInput, opts ...request.Option) (*DeleteBucketAnalyticsConfigurationOutput, error) { + req, out := c.DeleteBucketAnalyticsConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketCors = "DeleteBucketCors" @@ -489,6 +601,7 @@ const opDeleteBucketCors = "DeleteBucketCors" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketCors func (c *S3) DeleteBucketCorsRequest(input *DeleteBucketCorsInput) (req *request.Request, output *DeleteBucketCorsOutput) { op := &request.Operation{ Name: opDeleteBucketCors, @@ -500,11 +613,10 @@ func (c *S3) DeleteBucketCorsRequest(input *DeleteBucketCorsInput) (req *request input = &DeleteBucketCorsInput{} } + output = &DeleteBucketCorsOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &DeleteBucketCorsOutput{} - req.Data = output return } @@ -518,10 +630,26 @@ func (c *S3) DeleteBucketCorsRequest(input *DeleteBucketCorsInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketCors for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketCors func (c *S3) DeleteBucketCors(input *DeleteBucketCorsInput) (*DeleteBucketCorsOutput, error) { req, out := c.DeleteBucketCorsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketCorsWithContext is the same as DeleteBucketCors with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketCors for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketCorsWithContext(ctx aws.Context, input *DeleteBucketCorsInput, opts ...request.Option) (*DeleteBucketCorsOutput, error) { + req, out := c.DeleteBucketCorsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketInventoryConfiguration = "DeleteBucketInventoryConfiguration" @@ -550,6 +678,7 @@ const opDeleteBucketInventoryConfiguration = "DeleteBucketInventoryConfiguration // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketInventoryConfiguration func (c *S3) DeleteBucketInventoryConfigurationRequest(input *DeleteBucketInventoryConfigurationInput) (req *request.Request, output *DeleteBucketInventoryConfigurationOutput) { op := &request.Operation{ Name: opDeleteBucketInventoryConfiguration, @@ -561,11 +690,10 @@ func (c *S3) DeleteBucketInventoryConfigurationRequest(input *DeleteBucketInvent input = &DeleteBucketInventoryConfigurationInput{} } + output = &DeleteBucketInventoryConfigurationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &DeleteBucketInventoryConfigurationOutput{} - req.Data = output return } @@ -580,10 +708,26 @@ func (c *S3) DeleteBucketInventoryConfigurationRequest(input *DeleteBucketInvent // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketInventoryConfiguration for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketInventoryConfiguration func (c *S3) DeleteBucketInventoryConfiguration(input *DeleteBucketInventoryConfigurationInput) (*DeleteBucketInventoryConfigurationOutput, error) { req, out := c.DeleteBucketInventoryConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketInventoryConfigurationWithContext is the same as DeleteBucketInventoryConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketInventoryConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketInventoryConfigurationWithContext(ctx aws.Context, input *DeleteBucketInventoryConfigurationInput, opts ...request.Option) (*DeleteBucketInventoryConfigurationOutput, error) { + req, out := c.DeleteBucketInventoryConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketLifecycle = "DeleteBucketLifecycle" @@ -612,6 +756,7 @@ const opDeleteBucketLifecycle = "DeleteBucketLifecycle" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketLifecycle func (c *S3) DeleteBucketLifecycleRequest(input *DeleteBucketLifecycleInput) (req *request.Request, output *DeleteBucketLifecycleOutput) { op := &request.Operation{ Name: opDeleteBucketLifecycle, @@ -623,11 +768,10 @@ func (c *S3) DeleteBucketLifecycleRequest(input *DeleteBucketLifecycleInput) (re input = &DeleteBucketLifecycleInput{} } + output = &DeleteBucketLifecycleOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &DeleteBucketLifecycleOutput{} - req.Data = output return } @@ -641,10 +785,26 @@ func (c *S3) DeleteBucketLifecycleRequest(input *DeleteBucketLifecycleInput) (re // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketLifecycle for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketLifecycle func (c *S3) DeleteBucketLifecycle(input *DeleteBucketLifecycleInput) (*DeleteBucketLifecycleOutput, error) { req, out := c.DeleteBucketLifecycleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketLifecycleWithContext is the same as DeleteBucketLifecycle with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketLifecycle for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketLifecycleWithContext(ctx aws.Context, input *DeleteBucketLifecycleInput, opts ...request.Option) (*DeleteBucketLifecycleOutput, error) { + req, out := c.DeleteBucketLifecycleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketMetricsConfiguration = "DeleteBucketMetricsConfiguration" @@ -673,6 +833,7 @@ const opDeleteBucketMetricsConfiguration = "DeleteBucketMetricsConfiguration" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketMetricsConfiguration func (c *S3) DeleteBucketMetricsConfigurationRequest(input *DeleteBucketMetricsConfigurationInput) (req *request.Request, output *DeleteBucketMetricsConfigurationOutput) { op := &request.Operation{ Name: opDeleteBucketMetricsConfiguration, @@ -684,11 +845,10 @@ func (c *S3) DeleteBucketMetricsConfigurationRequest(input *DeleteBucketMetricsC input = &DeleteBucketMetricsConfigurationInput{} } + output = &DeleteBucketMetricsConfigurationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &DeleteBucketMetricsConfigurationOutput{} - req.Data = output return } @@ -703,10 +863,26 @@ func (c *S3) DeleteBucketMetricsConfigurationRequest(input *DeleteBucketMetricsC // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketMetricsConfiguration for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketMetricsConfiguration func (c *S3) DeleteBucketMetricsConfiguration(input *DeleteBucketMetricsConfigurationInput) (*DeleteBucketMetricsConfigurationOutput, error) { req, out := c.DeleteBucketMetricsConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketMetricsConfigurationWithContext is the same as DeleteBucketMetricsConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketMetricsConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketMetricsConfigurationWithContext(ctx aws.Context, input *DeleteBucketMetricsConfigurationInput, opts ...request.Option) (*DeleteBucketMetricsConfigurationOutput, error) { + req, out := c.DeleteBucketMetricsConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketPolicy = "DeleteBucketPolicy" @@ -735,6 +911,7 @@ const opDeleteBucketPolicy = "DeleteBucketPolicy" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketPolicy func (c *S3) DeleteBucketPolicyRequest(input *DeleteBucketPolicyInput) (req *request.Request, output *DeleteBucketPolicyOutput) { op := &request.Operation{ Name: opDeleteBucketPolicy, @@ -746,11 +923,10 @@ func (c *S3) DeleteBucketPolicyRequest(input *DeleteBucketPolicyInput) (req *req input = &DeleteBucketPolicyInput{} } + output = &DeleteBucketPolicyOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &DeleteBucketPolicyOutput{} - req.Data = output return } @@ -764,10 +940,26 @@ func (c *S3) DeleteBucketPolicyRequest(input *DeleteBucketPolicyInput) (req *req // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketPolicy for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketPolicy func (c *S3) DeleteBucketPolicy(input *DeleteBucketPolicyInput) (*DeleteBucketPolicyOutput, error) { req, out := c.DeleteBucketPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketPolicyWithContext is the same as DeleteBucketPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketPolicyWithContext(ctx aws.Context, input *DeleteBucketPolicyInput, opts ...request.Option) (*DeleteBucketPolicyOutput, error) { + req, out := c.DeleteBucketPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketReplication = "DeleteBucketReplication" @@ -796,6 +988,7 @@ const opDeleteBucketReplication = "DeleteBucketReplication" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketReplication func (c *S3) DeleteBucketReplicationRequest(input *DeleteBucketReplicationInput) (req *request.Request, output *DeleteBucketReplicationOutput) { op := &request.Operation{ Name: opDeleteBucketReplication, @@ -807,11 +1000,10 @@ func (c *S3) DeleteBucketReplicationRequest(input *DeleteBucketReplicationInput) input = &DeleteBucketReplicationInput{} } + output = &DeleteBucketReplicationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &DeleteBucketReplicationOutput{} - req.Data = output return } @@ -825,10 +1017,26 @@ func (c *S3) DeleteBucketReplicationRequest(input *DeleteBucketReplicationInput) // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketReplication for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketReplication func (c *S3) DeleteBucketReplication(input *DeleteBucketReplicationInput) (*DeleteBucketReplicationOutput, error) { req, out := c.DeleteBucketReplicationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketReplicationWithContext is the same as DeleteBucketReplication with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketReplication for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketReplicationWithContext(ctx aws.Context, input *DeleteBucketReplicationInput, opts ...request.Option) (*DeleteBucketReplicationOutput, error) { + req, out := c.DeleteBucketReplicationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketTagging = "DeleteBucketTagging" @@ -857,6 +1065,7 @@ const opDeleteBucketTagging = "DeleteBucketTagging" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketTagging func (c *S3) DeleteBucketTaggingRequest(input *DeleteBucketTaggingInput) (req *request.Request, output *DeleteBucketTaggingOutput) { op := &request.Operation{ Name: opDeleteBucketTagging, @@ -868,11 +1077,10 @@ func (c *S3) DeleteBucketTaggingRequest(input *DeleteBucketTaggingInput) (req *r input = &DeleteBucketTaggingInput{} } + output = &DeleteBucketTaggingOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &DeleteBucketTaggingOutput{} - req.Data = output return } @@ -886,10 +1094,26 @@ func (c *S3) DeleteBucketTaggingRequest(input *DeleteBucketTaggingInput) (req *r // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketTagging for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketTagging func (c *S3) DeleteBucketTagging(input *DeleteBucketTaggingInput) (*DeleteBucketTaggingOutput, error) { req, out := c.DeleteBucketTaggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketTaggingWithContext is the same as DeleteBucketTagging with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketTagging for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketTaggingWithContext(ctx aws.Context, input *DeleteBucketTaggingInput, opts ...request.Option) (*DeleteBucketTaggingOutput, error) { + req, out := c.DeleteBucketTaggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteBucketWebsite = "DeleteBucketWebsite" @@ -918,6 +1142,7 @@ const opDeleteBucketWebsite = "DeleteBucketWebsite" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketWebsite func (c *S3) DeleteBucketWebsiteRequest(input *DeleteBucketWebsiteInput) (req *request.Request, output *DeleteBucketWebsiteOutput) { op := &request.Operation{ Name: opDeleteBucketWebsite, @@ -929,11 +1154,10 @@ func (c *S3) DeleteBucketWebsiteRequest(input *DeleteBucketWebsiteInput) (req *r input = &DeleteBucketWebsiteInput{} } + output = &DeleteBucketWebsiteOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &DeleteBucketWebsiteOutput{} - req.Data = output return } @@ -947,10 +1171,26 @@ func (c *S3) DeleteBucketWebsiteRequest(input *DeleteBucketWebsiteInput) (req *r // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteBucketWebsite for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketWebsite func (c *S3) DeleteBucketWebsite(input *DeleteBucketWebsiteInput) (*DeleteBucketWebsiteOutput, error) { req, out := c.DeleteBucketWebsiteRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteBucketWebsiteWithContext is the same as DeleteBucketWebsite with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteBucketWebsite for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteBucketWebsiteWithContext(ctx aws.Context, input *DeleteBucketWebsiteInput, opts ...request.Option) (*DeleteBucketWebsiteOutput, error) { + req, out := c.DeleteBucketWebsiteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteObject = "DeleteObject" @@ -979,6 +1219,7 @@ const opDeleteObject = "DeleteObject" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObject func (c *S3) DeleteObjectRequest(input *DeleteObjectInput) (req *request.Request, output *DeleteObjectOutput) { op := &request.Operation{ Name: opDeleteObject, @@ -990,9 +1231,8 @@ func (c *S3) DeleteObjectRequest(input *DeleteObjectInput) (req *request.Request input = &DeleteObjectInput{} } - req = c.newRequest(op, input, output) output = &DeleteObjectOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1008,10 +1248,26 @@ func (c *S3) DeleteObjectRequest(input *DeleteObjectInput) (req *request.Request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteObject for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObject func (c *S3) DeleteObject(input *DeleteObjectInput) (*DeleteObjectOutput, error) { req, out := c.DeleteObjectRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteObjectWithContext is the same as DeleteObject with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteObject for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteObjectWithContext(ctx aws.Context, input *DeleteObjectInput, opts ...request.Option) (*DeleteObjectOutput, error) { + req, out := c.DeleteObjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteObjectTagging = "DeleteObjectTagging" @@ -1040,6 +1296,7 @@ const opDeleteObjectTagging = "DeleteObjectTagging" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectTagging func (c *S3) DeleteObjectTaggingRequest(input *DeleteObjectTaggingInput) (req *request.Request, output *DeleteObjectTaggingOutput) { op := &request.Operation{ Name: opDeleteObjectTagging, @@ -1051,9 +1308,8 @@ func (c *S3) DeleteObjectTaggingRequest(input *DeleteObjectTaggingInput) (req *r input = &DeleteObjectTaggingInput{} } - req = c.newRequest(op, input, output) output = &DeleteObjectTaggingOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1067,10 +1323,26 @@ func (c *S3) DeleteObjectTaggingRequest(input *DeleteObjectTaggingInput) (req *r // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteObjectTagging for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectTagging func (c *S3) DeleteObjectTagging(input *DeleteObjectTaggingInput) (*DeleteObjectTaggingOutput, error) { req, out := c.DeleteObjectTaggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteObjectTaggingWithContext is the same as DeleteObjectTagging with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteObjectTagging for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteObjectTaggingWithContext(ctx aws.Context, input *DeleteObjectTaggingInput, opts ...request.Option) (*DeleteObjectTaggingOutput, error) { + req, out := c.DeleteObjectTaggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDeleteObjects = "DeleteObjects" @@ -1099,6 +1371,7 @@ const opDeleteObjects = "DeleteObjects" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjects func (c *S3) DeleteObjectsRequest(input *DeleteObjectsInput) (req *request.Request, output *DeleteObjectsOutput) { op := &request.Operation{ Name: opDeleteObjects, @@ -1110,9 +1383,8 @@ func (c *S3) DeleteObjectsRequest(input *DeleteObjectsInput) (req *request.Reque input = &DeleteObjectsInput{} } - req = c.newRequest(op, input, output) output = &DeleteObjectsOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1127,10 +1399,26 @@ func (c *S3) DeleteObjectsRequest(input *DeleteObjectsInput) (req *request.Reque // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation DeleteObjects for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjects func (c *S3) DeleteObjects(input *DeleteObjectsInput) (*DeleteObjectsOutput, error) { req, out := c.DeleteObjectsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DeleteObjectsWithContext is the same as DeleteObjects with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteObjects for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) DeleteObjectsWithContext(ctx aws.Context, input *DeleteObjectsInput, opts ...request.Option) (*DeleteObjectsOutput, error) { + req, out := c.DeleteObjectsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketAccelerateConfiguration = "GetBucketAccelerateConfiguration" @@ -1159,6 +1447,7 @@ const opGetBucketAccelerateConfiguration = "GetBucketAccelerateConfiguration" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAccelerateConfiguration func (c *S3) GetBucketAccelerateConfigurationRequest(input *GetBucketAccelerateConfigurationInput) (req *request.Request, output *GetBucketAccelerateConfigurationOutput) { op := &request.Operation{ Name: opGetBucketAccelerateConfiguration, @@ -1170,9 +1459,8 @@ func (c *S3) GetBucketAccelerateConfigurationRequest(input *GetBucketAccelerateC input = &GetBucketAccelerateConfigurationInput{} } - req = c.newRequest(op, input, output) output = &GetBucketAccelerateConfigurationOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1186,10 +1474,26 @@ func (c *S3) GetBucketAccelerateConfigurationRequest(input *GetBucketAccelerateC // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketAccelerateConfiguration for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAccelerateConfiguration func (c *S3) GetBucketAccelerateConfiguration(input *GetBucketAccelerateConfigurationInput) (*GetBucketAccelerateConfigurationOutput, error) { req, out := c.GetBucketAccelerateConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketAccelerateConfigurationWithContext is the same as GetBucketAccelerateConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketAccelerateConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketAccelerateConfigurationWithContext(ctx aws.Context, input *GetBucketAccelerateConfigurationInput, opts ...request.Option) (*GetBucketAccelerateConfigurationOutput, error) { + req, out := c.GetBucketAccelerateConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketAcl = "GetBucketAcl" @@ -1218,6 +1522,7 @@ const opGetBucketAcl = "GetBucketAcl" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAcl func (c *S3) GetBucketAclRequest(input *GetBucketAclInput) (req *request.Request, output *GetBucketAclOutput) { op := &request.Operation{ Name: opGetBucketAcl, @@ -1229,9 +1534,8 @@ func (c *S3) GetBucketAclRequest(input *GetBucketAclInput) (req *request.Request input = &GetBucketAclInput{} } - req = c.newRequest(op, input, output) output = &GetBucketAclOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1245,10 +1549,26 @@ func (c *S3) GetBucketAclRequest(input *GetBucketAclInput) (req *request.Request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketAcl for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAcl func (c *S3) GetBucketAcl(input *GetBucketAclInput) (*GetBucketAclOutput, error) { req, out := c.GetBucketAclRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketAclWithContext is the same as GetBucketAcl with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketAcl for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketAclWithContext(ctx aws.Context, input *GetBucketAclInput, opts ...request.Option) (*GetBucketAclOutput, error) { + req, out := c.GetBucketAclRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketAnalyticsConfiguration = "GetBucketAnalyticsConfiguration" @@ -1277,6 +1597,7 @@ const opGetBucketAnalyticsConfiguration = "GetBucketAnalyticsConfiguration" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAnalyticsConfiguration func (c *S3) GetBucketAnalyticsConfigurationRequest(input *GetBucketAnalyticsConfigurationInput) (req *request.Request, output *GetBucketAnalyticsConfigurationOutput) { op := &request.Operation{ Name: opGetBucketAnalyticsConfiguration, @@ -1288,9 +1609,8 @@ func (c *S3) GetBucketAnalyticsConfigurationRequest(input *GetBucketAnalyticsCon input = &GetBucketAnalyticsConfigurationInput{} } - req = c.newRequest(op, input, output) output = &GetBucketAnalyticsConfigurationOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1305,10 +1625,26 @@ func (c *S3) GetBucketAnalyticsConfigurationRequest(input *GetBucketAnalyticsCon // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketAnalyticsConfiguration for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAnalyticsConfiguration func (c *S3) GetBucketAnalyticsConfiguration(input *GetBucketAnalyticsConfigurationInput) (*GetBucketAnalyticsConfigurationOutput, error) { req, out := c.GetBucketAnalyticsConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketAnalyticsConfigurationWithContext is the same as GetBucketAnalyticsConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketAnalyticsConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketAnalyticsConfigurationWithContext(ctx aws.Context, input *GetBucketAnalyticsConfigurationInput, opts ...request.Option) (*GetBucketAnalyticsConfigurationOutput, error) { + req, out := c.GetBucketAnalyticsConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketCors = "GetBucketCors" @@ -1337,6 +1673,7 @@ const opGetBucketCors = "GetBucketCors" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketCors func (c *S3) GetBucketCorsRequest(input *GetBucketCorsInput) (req *request.Request, output *GetBucketCorsOutput) { op := &request.Operation{ Name: opGetBucketCors, @@ -1348,9 +1685,8 @@ func (c *S3) GetBucketCorsRequest(input *GetBucketCorsInput) (req *request.Reque input = &GetBucketCorsInput{} } - req = c.newRequest(op, input, output) output = &GetBucketCorsOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1364,10 +1700,26 @@ func (c *S3) GetBucketCorsRequest(input *GetBucketCorsInput) (req *request.Reque // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketCors for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketCors func (c *S3) GetBucketCors(input *GetBucketCorsInput) (*GetBucketCorsOutput, error) { req, out := c.GetBucketCorsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketCorsWithContext is the same as GetBucketCors with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketCors for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketCorsWithContext(ctx aws.Context, input *GetBucketCorsInput, opts ...request.Option) (*GetBucketCorsOutput, error) { + req, out := c.GetBucketCorsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketInventoryConfiguration = "GetBucketInventoryConfiguration" @@ -1396,6 +1748,7 @@ const opGetBucketInventoryConfiguration = "GetBucketInventoryConfiguration" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketInventoryConfiguration func (c *S3) GetBucketInventoryConfigurationRequest(input *GetBucketInventoryConfigurationInput) (req *request.Request, output *GetBucketInventoryConfigurationOutput) { op := &request.Operation{ Name: opGetBucketInventoryConfiguration, @@ -1407,9 +1760,8 @@ func (c *S3) GetBucketInventoryConfigurationRequest(input *GetBucketInventoryCon input = &GetBucketInventoryConfigurationInput{} } - req = c.newRequest(op, input, output) output = &GetBucketInventoryConfigurationOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1424,10 +1776,26 @@ func (c *S3) GetBucketInventoryConfigurationRequest(input *GetBucketInventoryCon // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketInventoryConfiguration for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketInventoryConfiguration func (c *S3) GetBucketInventoryConfiguration(input *GetBucketInventoryConfigurationInput) (*GetBucketInventoryConfigurationOutput, error) { req, out := c.GetBucketInventoryConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketInventoryConfigurationWithContext is the same as GetBucketInventoryConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketInventoryConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketInventoryConfigurationWithContext(ctx aws.Context, input *GetBucketInventoryConfigurationInput, opts ...request.Option) (*GetBucketInventoryConfigurationOutput, error) { + req, out := c.GetBucketInventoryConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketLifecycle = "GetBucketLifecycle" @@ -1456,6 +1824,7 @@ const opGetBucketLifecycle = "GetBucketLifecycle" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycle func (c *S3) GetBucketLifecycleRequest(input *GetBucketLifecycleInput) (req *request.Request, output *GetBucketLifecycleOutput) { if c.Client.Config.Logger != nil { c.Client.Config.Logger.Log("This operation, GetBucketLifecycle, has been deprecated") @@ -1470,9 +1839,8 @@ func (c *S3) GetBucketLifecycleRequest(input *GetBucketLifecycleInput) (req *req input = &GetBucketLifecycleInput{} } - req = c.newRequest(op, input, output) output = &GetBucketLifecycleOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1486,10 +1854,26 @@ func (c *S3) GetBucketLifecycleRequest(input *GetBucketLifecycleInput) (req *req // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketLifecycle for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycle func (c *S3) GetBucketLifecycle(input *GetBucketLifecycleInput) (*GetBucketLifecycleOutput, error) { req, out := c.GetBucketLifecycleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketLifecycleWithContext is the same as GetBucketLifecycle with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketLifecycle for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketLifecycleWithContext(ctx aws.Context, input *GetBucketLifecycleInput, opts ...request.Option) (*GetBucketLifecycleOutput, error) { + req, out := c.GetBucketLifecycleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketLifecycleConfiguration = "GetBucketLifecycleConfiguration" @@ -1518,6 +1902,7 @@ const opGetBucketLifecycleConfiguration = "GetBucketLifecycleConfiguration" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleConfiguration func (c *S3) GetBucketLifecycleConfigurationRequest(input *GetBucketLifecycleConfigurationInput) (req *request.Request, output *GetBucketLifecycleConfigurationOutput) { op := &request.Operation{ Name: opGetBucketLifecycleConfiguration, @@ -1529,9 +1914,8 @@ func (c *S3) GetBucketLifecycleConfigurationRequest(input *GetBucketLifecycleCon input = &GetBucketLifecycleConfigurationInput{} } - req = c.newRequest(op, input, output) output = &GetBucketLifecycleConfigurationOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1545,10 +1929,26 @@ func (c *S3) GetBucketLifecycleConfigurationRequest(input *GetBucketLifecycleCon // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketLifecycleConfiguration for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleConfiguration func (c *S3) GetBucketLifecycleConfiguration(input *GetBucketLifecycleConfigurationInput) (*GetBucketLifecycleConfigurationOutput, error) { req, out := c.GetBucketLifecycleConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketLifecycleConfigurationWithContext is the same as GetBucketLifecycleConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketLifecycleConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketLifecycleConfigurationWithContext(ctx aws.Context, input *GetBucketLifecycleConfigurationInput, opts ...request.Option) (*GetBucketLifecycleConfigurationOutput, error) { + req, out := c.GetBucketLifecycleConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketLocation = "GetBucketLocation" @@ -1577,6 +1977,7 @@ const opGetBucketLocation = "GetBucketLocation" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLocation func (c *S3) GetBucketLocationRequest(input *GetBucketLocationInput) (req *request.Request, output *GetBucketLocationOutput) { op := &request.Operation{ Name: opGetBucketLocation, @@ -1588,9 +1989,8 @@ func (c *S3) GetBucketLocationRequest(input *GetBucketLocationInput) (req *reque input = &GetBucketLocationInput{} } - req = c.newRequest(op, input, output) output = &GetBucketLocationOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1604,10 +2004,26 @@ func (c *S3) GetBucketLocationRequest(input *GetBucketLocationInput) (req *reque // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketLocation for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLocation func (c *S3) GetBucketLocation(input *GetBucketLocationInput) (*GetBucketLocationOutput, error) { req, out := c.GetBucketLocationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketLocationWithContext is the same as GetBucketLocation with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketLocation for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketLocationWithContext(ctx aws.Context, input *GetBucketLocationInput, opts ...request.Option) (*GetBucketLocationOutput, error) { + req, out := c.GetBucketLocationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketLogging = "GetBucketLogging" @@ -1636,6 +2052,7 @@ const opGetBucketLogging = "GetBucketLogging" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLogging func (c *S3) GetBucketLoggingRequest(input *GetBucketLoggingInput) (req *request.Request, output *GetBucketLoggingOutput) { op := &request.Operation{ Name: opGetBucketLogging, @@ -1647,9 +2064,8 @@ func (c *S3) GetBucketLoggingRequest(input *GetBucketLoggingInput) (req *request input = &GetBucketLoggingInput{} } - req = c.newRequest(op, input, output) output = &GetBucketLoggingOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1664,10 +2080,26 @@ func (c *S3) GetBucketLoggingRequest(input *GetBucketLoggingInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketLogging for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLogging func (c *S3) GetBucketLogging(input *GetBucketLoggingInput) (*GetBucketLoggingOutput, error) { req, out := c.GetBucketLoggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketLoggingWithContext is the same as GetBucketLogging with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketLogging for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketLoggingWithContext(ctx aws.Context, input *GetBucketLoggingInput, opts ...request.Option) (*GetBucketLoggingOutput, error) { + req, out := c.GetBucketLoggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketMetricsConfiguration = "GetBucketMetricsConfiguration" @@ -1696,6 +2128,7 @@ const opGetBucketMetricsConfiguration = "GetBucketMetricsConfiguration" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketMetricsConfiguration func (c *S3) GetBucketMetricsConfigurationRequest(input *GetBucketMetricsConfigurationInput) (req *request.Request, output *GetBucketMetricsConfigurationOutput) { op := &request.Operation{ Name: opGetBucketMetricsConfiguration, @@ -1707,9 +2140,8 @@ func (c *S3) GetBucketMetricsConfigurationRequest(input *GetBucketMetricsConfigu input = &GetBucketMetricsConfigurationInput{} } - req = c.newRequest(op, input, output) output = &GetBucketMetricsConfigurationOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1724,10 +2156,26 @@ func (c *S3) GetBucketMetricsConfigurationRequest(input *GetBucketMetricsConfigu // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketMetricsConfiguration for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketMetricsConfiguration func (c *S3) GetBucketMetricsConfiguration(input *GetBucketMetricsConfigurationInput) (*GetBucketMetricsConfigurationOutput, error) { req, out := c.GetBucketMetricsConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketMetricsConfigurationWithContext is the same as GetBucketMetricsConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketMetricsConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketMetricsConfigurationWithContext(ctx aws.Context, input *GetBucketMetricsConfigurationInput, opts ...request.Option) (*GetBucketMetricsConfigurationOutput, error) { + req, out := c.GetBucketMetricsConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketNotification = "GetBucketNotification" @@ -1756,6 +2204,7 @@ const opGetBucketNotification = "GetBucketNotification" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotification func (c *S3) GetBucketNotificationRequest(input *GetBucketNotificationConfigurationRequest) (req *request.Request, output *NotificationConfigurationDeprecated) { if c.Client.Config.Logger != nil { c.Client.Config.Logger.Log("This operation, GetBucketNotification, has been deprecated") @@ -1770,9 +2219,8 @@ func (c *S3) GetBucketNotificationRequest(input *GetBucketNotificationConfigurat input = &GetBucketNotificationConfigurationRequest{} } - req = c.newRequest(op, input, output) output = &NotificationConfigurationDeprecated{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1786,10 +2234,26 @@ func (c *S3) GetBucketNotificationRequest(input *GetBucketNotificationConfigurat // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketNotification for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotification func (c *S3) GetBucketNotification(input *GetBucketNotificationConfigurationRequest) (*NotificationConfigurationDeprecated, error) { req, out := c.GetBucketNotificationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketNotificationWithContext is the same as GetBucketNotification with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketNotification for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketNotificationWithContext(ctx aws.Context, input *GetBucketNotificationConfigurationRequest, opts ...request.Option) (*NotificationConfigurationDeprecated, error) { + req, out := c.GetBucketNotificationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketNotificationConfiguration = "GetBucketNotificationConfiguration" @@ -1818,6 +2282,7 @@ const opGetBucketNotificationConfiguration = "GetBucketNotificationConfiguration // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotificationConfiguration func (c *S3) GetBucketNotificationConfigurationRequest(input *GetBucketNotificationConfigurationRequest) (req *request.Request, output *NotificationConfiguration) { op := &request.Operation{ Name: opGetBucketNotificationConfiguration, @@ -1829,9 +2294,8 @@ func (c *S3) GetBucketNotificationConfigurationRequest(input *GetBucketNotificat input = &GetBucketNotificationConfigurationRequest{} } - req = c.newRequest(op, input, output) output = &NotificationConfiguration{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1845,10 +2309,26 @@ func (c *S3) GetBucketNotificationConfigurationRequest(input *GetBucketNotificat // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketNotificationConfiguration for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotificationConfiguration func (c *S3) GetBucketNotificationConfiguration(input *GetBucketNotificationConfigurationRequest) (*NotificationConfiguration, error) { req, out := c.GetBucketNotificationConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketNotificationConfigurationWithContext is the same as GetBucketNotificationConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketNotificationConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketNotificationConfigurationWithContext(ctx aws.Context, input *GetBucketNotificationConfigurationRequest, opts ...request.Option) (*NotificationConfiguration, error) { + req, out := c.GetBucketNotificationConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketPolicy = "GetBucketPolicy" @@ -1877,6 +2357,7 @@ const opGetBucketPolicy = "GetBucketPolicy" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicy func (c *S3) GetBucketPolicyRequest(input *GetBucketPolicyInput) (req *request.Request, output *GetBucketPolicyOutput) { op := &request.Operation{ Name: opGetBucketPolicy, @@ -1888,9 +2369,8 @@ func (c *S3) GetBucketPolicyRequest(input *GetBucketPolicyInput) (req *request.R input = &GetBucketPolicyInput{} } - req = c.newRequest(op, input, output) output = &GetBucketPolicyOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1904,10 +2384,26 @@ func (c *S3) GetBucketPolicyRequest(input *GetBucketPolicyInput) (req *request.R // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketPolicy for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicy func (c *S3) GetBucketPolicy(input *GetBucketPolicyInput) (*GetBucketPolicyOutput, error) { req, out := c.GetBucketPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketPolicyWithContext is the same as GetBucketPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketPolicyWithContext(ctx aws.Context, input *GetBucketPolicyInput, opts ...request.Option) (*GetBucketPolicyOutput, error) { + req, out := c.GetBucketPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketReplication = "GetBucketReplication" @@ -1936,6 +2432,7 @@ const opGetBucketReplication = "GetBucketReplication" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketReplication func (c *S3) GetBucketReplicationRequest(input *GetBucketReplicationInput) (req *request.Request, output *GetBucketReplicationOutput) { op := &request.Operation{ Name: opGetBucketReplication, @@ -1947,9 +2444,8 @@ func (c *S3) GetBucketReplicationRequest(input *GetBucketReplicationInput) (req input = &GetBucketReplicationInput{} } - req = c.newRequest(op, input, output) output = &GetBucketReplicationOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -1963,10 +2459,26 @@ func (c *S3) GetBucketReplicationRequest(input *GetBucketReplicationInput) (req // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketReplication for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketReplication func (c *S3) GetBucketReplication(input *GetBucketReplicationInput) (*GetBucketReplicationOutput, error) { req, out := c.GetBucketReplicationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketReplicationWithContext is the same as GetBucketReplication with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketReplication for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketReplicationWithContext(ctx aws.Context, input *GetBucketReplicationInput, opts ...request.Option) (*GetBucketReplicationOutput, error) { + req, out := c.GetBucketReplicationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketRequestPayment = "GetBucketRequestPayment" @@ -1995,6 +2507,7 @@ const opGetBucketRequestPayment = "GetBucketRequestPayment" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketRequestPayment func (c *S3) GetBucketRequestPaymentRequest(input *GetBucketRequestPaymentInput) (req *request.Request, output *GetBucketRequestPaymentOutput) { op := &request.Operation{ Name: opGetBucketRequestPayment, @@ -2006,9 +2519,8 @@ func (c *S3) GetBucketRequestPaymentRequest(input *GetBucketRequestPaymentInput) input = &GetBucketRequestPaymentInput{} } - req = c.newRequest(op, input, output) output = &GetBucketRequestPaymentOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2022,10 +2534,26 @@ func (c *S3) GetBucketRequestPaymentRequest(input *GetBucketRequestPaymentInput) // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketRequestPayment for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketRequestPayment func (c *S3) GetBucketRequestPayment(input *GetBucketRequestPaymentInput) (*GetBucketRequestPaymentOutput, error) { req, out := c.GetBucketRequestPaymentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketRequestPaymentWithContext is the same as GetBucketRequestPayment with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketRequestPayment for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketRequestPaymentWithContext(ctx aws.Context, input *GetBucketRequestPaymentInput, opts ...request.Option) (*GetBucketRequestPaymentOutput, error) { + req, out := c.GetBucketRequestPaymentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketTagging = "GetBucketTagging" @@ -2054,6 +2582,7 @@ const opGetBucketTagging = "GetBucketTagging" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketTagging func (c *S3) GetBucketTaggingRequest(input *GetBucketTaggingInput) (req *request.Request, output *GetBucketTaggingOutput) { op := &request.Operation{ Name: opGetBucketTagging, @@ -2065,9 +2594,8 @@ func (c *S3) GetBucketTaggingRequest(input *GetBucketTaggingInput) (req *request input = &GetBucketTaggingInput{} } - req = c.newRequest(op, input, output) output = &GetBucketTaggingOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2081,10 +2609,26 @@ func (c *S3) GetBucketTaggingRequest(input *GetBucketTaggingInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketTagging for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketTagging func (c *S3) GetBucketTagging(input *GetBucketTaggingInput) (*GetBucketTaggingOutput, error) { req, out := c.GetBucketTaggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketTaggingWithContext is the same as GetBucketTagging with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketTagging for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketTaggingWithContext(ctx aws.Context, input *GetBucketTaggingInput, opts ...request.Option) (*GetBucketTaggingOutput, error) { + req, out := c.GetBucketTaggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketVersioning = "GetBucketVersioning" @@ -2113,6 +2657,7 @@ const opGetBucketVersioning = "GetBucketVersioning" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketVersioning func (c *S3) GetBucketVersioningRequest(input *GetBucketVersioningInput) (req *request.Request, output *GetBucketVersioningOutput) { op := &request.Operation{ Name: opGetBucketVersioning, @@ -2124,9 +2669,8 @@ func (c *S3) GetBucketVersioningRequest(input *GetBucketVersioningInput) (req *r input = &GetBucketVersioningInput{} } - req = c.newRequest(op, input, output) output = &GetBucketVersioningOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2140,10 +2684,26 @@ func (c *S3) GetBucketVersioningRequest(input *GetBucketVersioningInput) (req *r // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketVersioning for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketVersioning func (c *S3) GetBucketVersioning(input *GetBucketVersioningInput) (*GetBucketVersioningOutput, error) { req, out := c.GetBucketVersioningRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketVersioningWithContext is the same as GetBucketVersioning with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketVersioning for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketVersioningWithContext(ctx aws.Context, input *GetBucketVersioningInput, opts ...request.Option) (*GetBucketVersioningOutput, error) { + req, out := c.GetBucketVersioningRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetBucketWebsite = "GetBucketWebsite" @@ -2172,6 +2732,7 @@ const opGetBucketWebsite = "GetBucketWebsite" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketWebsite func (c *S3) GetBucketWebsiteRequest(input *GetBucketWebsiteInput) (req *request.Request, output *GetBucketWebsiteOutput) { op := &request.Operation{ Name: opGetBucketWebsite, @@ -2183,9 +2744,8 @@ func (c *S3) GetBucketWebsiteRequest(input *GetBucketWebsiteInput) (req *request input = &GetBucketWebsiteInput{} } - req = c.newRequest(op, input, output) output = &GetBucketWebsiteOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2199,10 +2759,26 @@ func (c *S3) GetBucketWebsiteRequest(input *GetBucketWebsiteInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetBucketWebsite for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketWebsite func (c *S3) GetBucketWebsite(input *GetBucketWebsiteInput) (*GetBucketWebsiteOutput, error) { req, out := c.GetBucketWebsiteRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetBucketWebsiteWithContext is the same as GetBucketWebsite with the addition of +// the ability to pass a context and additional request options. +// +// See GetBucketWebsite for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetBucketWebsiteWithContext(ctx aws.Context, input *GetBucketWebsiteInput, opts ...request.Option) (*GetBucketWebsiteOutput, error) { + req, out := c.GetBucketWebsiteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetObject = "GetObject" @@ -2231,6 +2807,7 @@ const opGetObject = "GetObject" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObject func (c *S3) GetObjectRequest(input *GetObjectInput) (req *request.Request, output *GetObjectOutput) { op := &request.Operation{ Name: opGetObject, @@ -2242,9 +2819,8 @@ func (c *S3) GetObjectRequest(input *GetObjectInput) (req *request.Request, outp input = &GetObjectInput{} } - req = c.newRequest(op, input, output) output = &GetObjectOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2260,16 +2836,32 @@ func (c *S3) GetObjectRequest(input *GetObjectInput) (req *request.Request, outp // API operation GetObject for usage and error information. // // Returned Error Codes: -// * NoSuchKey +// * ErrCodeNoSuchKey "NoSuchKey" // The specified key does not exist. // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObject func (c *S3) GetObject(input *GetObjectInput) (*GetObjectOutput, error) { req, out := c.GetObjectRequest(input) - err := req.Send() - return out, err + return out, req.Send() } -const opGetObjectAcl = "GetObjectAcl" +// GetObjectWithContext is the same as GetObject with the addition of +// the ability to pass a context and additional request options. +// +// See GetObject for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetObjectWithContext(ctx aws.Context, input *GetObjectInput, opts ...request.Option) (*GetObjectOutput, error) { + req, out := c.GetObjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opGetObjectAcl = "GetObjectAcl" // GetObjectAclRequest generates a "aws/request.Request" representing the // client's request for the GetObjectAcl operation. The "output" return @@ -2295,6 +2887,7 @@ const opGetObjectAcl = "GetObjectAcl" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectAcl func (c *S3) GetObjectAclRequest(input *GetObjectAclInput) (req *request.Request, output *GetObjectAclOutput) { op := &request.Operation{ Name: opGetObjectAcl, @@ -2306,9 +2899,8 @@ func (c *S3) GetObjectAclRequest(input *GetObjectAclInput) (req *request.Request input = &GetObjectAclInput{} } - req = c.newRequest(op, input, output) output = &GetObjectAclOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2324,13 +2916,29 @@ func (c *S3) GetObjectAclRequest(input *GetObjectAclInput) (req *request.Request // API operation GetObjectAcl for usage and error information. // // Returned Error Codes: -// * NoSuchKey +// * ErrCodeNoSuchKey "NoSuchKey" // The specified key does not exist. // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectAcl func (c *S3) GetObjectAcl(input *GetObjectAclInput) (*GetObjectAclOutput, error) { req, out := c.GetObjectAclRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetObjectAclWithContext is the same as GetObjectAcl with the addition of +// the ability to pass a context and additional request options. +// +// See GetObjectAcl for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetObjectAclWithContext(ctx aws.Context, input *GetObjectAclInput, opts ...request.Option) (*GetObjectAclOutput, error) { + req, out := c.GetObjectAclRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetObjectTagging = "GetObjectTagging" @@ -2359,6 +2967,7 @@ const opGetObjectTagging = "GetObjectTagging" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTagging func (c *S3) GetObjectTaggingRequest(input *GetObjectTaggingInput) (req *request.Request, output *GetObjectTaggingOutput) { op := &request.Operation{ Name: opGetObjectTagging, @@ -2370,9 +2979,8 @@ func (c *S3) GetObjectTaggingRequest(input *GetObjectTaggingInput) (req *request input = &GetObjectTaggingInput{} } - req = c.newRequest(op, input, output) output = &GetObjectTaggingOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2386,10 +2994,26 @@ func (c *S3) GetObjectTaggingRequest(input *GetObjectTaggingInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetObjectTagging for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTagging func (c *S3) GetObjectTagging(input *GetObjectTaggingInput) (*GetObjectTaggingOutput, error) { req, out := c.GetObjectTaggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetObjectTaggingWithContext is the same as GetObjectTagging with the addition of +// the ability to pass a context and additional request options. +// +// See GetObjectTagging for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetObjectTaggingWithContext(ctx aws.Context, input *GetObjectTaggingInput, opts ...request.Option) (*GetObjectTaggingOutput, error) { + req, out := c.GetObjectTaggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetObjectTorrent = "GetObjectTorrent" @@ -2418,6 +3042,7 @@ const opGetObjectTorrent = "GetObjectTorrent" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTorrent func (c *S3) GetObjectTorrentRequest(input *GetObjectTorrentInput) (req *request.Request, output *GetObjectTorrentOutput) { op := &request.Operation{ Name: opGetObjectTorrent, @@ -2429,9 +3054,8 @@ func (c *S3) GetObjectTorrentRequest(input *GetObjectTorrentInput) (req *request input = &GetObjectTorrentInput{} } - req = c.newRequest(op, input, output) output = &GetObjectTorrentOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2445,10 +3069,26 @@ func (c *S3) GetObjectTorrentRequest(input *GetObjectTorrentInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation GetObjectTorrent for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTorrent func (c *S3) GetObjectTorrent(input *GetObjectTorrentInput) (*GetObjectTorrentOutput, error) { req, out := c.GetObjectTorrentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetObjectTorrentWithContext is the same as GetObjectTorrent with the addition of +// the ability to pass a context and additional request options. +// +// See GetObjectTorrent for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) GetObjectTorrentWithContext(ctx aws.Context, input *GetObjectTorrentInput, opts ...request.Option) (*GetObjectTorrentOutput, error) { + req, out := c.GetObjectTorrentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opHeadBucket = "HeadBucket" @@ -2477,6 +3117,7 @@ const opHeadBucket = "HeadBucket" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadBucket func (c *S3) HeadBucketRequest(input *HeadBucketInput) (req *request.Request, output *HeadBucketOutput) { op := &request.Operation{ Name: opHeadBucket, @@ -2488,11 +3129,10 @@ func (c *S3) HeadBucketRequest(input *HeadBucketInput) (req *request.Request, ou input = &HeadBucketInput{} } + output = &HeadBucketOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &HeadBucketOutput{} - req.Data = output return } @@ -2509,13 +3149,29 @@ func (c *S3) HeadBucketRequest(input *HeadBucketInput) (req *request.Request, ou // API operation HeadBucket for usage and error information. // // Returned Error Codes: -// * NoSuchBucket +// * ErrCodeNoSuchBucket "NoSuchBucket" // The specified bucket does not exist. // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadBucket func (c *S3) HeadBucket(input *HeadBucketInput) (*HeadBucketOutput, error) { req, out := c.HeadBucketRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// HeadBucketWithContext is the same as HeadBucket with the addition of +// the ability to pass a context and additional request options. +// +// See HeadBucket for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) HeadBucketWithContext(ctx aws.Context, input *HeadBucketInput, opts ...request.Option) (*HeadBucketOutput, error) { + req, out := c.HeadBucketRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opHeadObject = "HeadObject" @@ -2544,6 +3200,7 @@ const opHeadObject = "HeadObject" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadObject func (c *S3) HeadObjectRequest(input *HeadObjectInput) (req *request.Request, output *HeadObjectOutput) { op := &request.Operation{ Name: opHeadObject, @@ -2555,9 +3212,8 @@ func (c *S3) HeadObjectRequest(input *HeadObjectInput) (req *request.Request, ou input = &HeadObjectInput{} } - req = c.newRequest(op, input, output) output = &HeadObjectOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2575,13 +3231,29 @@ func (c *S3) HeadObjectRequest(input *HeadObjectInput) (req *request.Request, ou // API operation HeadObject for usage and error information. // // Returned Error Codes: -// * NoSuchKey +// * ErrCodeNoSuchKey "NoSuchKey" // The specified key does not exist. // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadObject func (c *S3) HeadObject(input *HeadObjectInput) (*HeadObjectOutput, error) { req, out := c.HeadObjectRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// HeadObjectWithContext is the same as HeadObject with the addition of +// the ability to pass a context and additional request options. +// +// See HeadObject for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) HeadObjectWithContext(ctx aws.Context, input *HeadObjectInput, opts ...request.Option) (*HeadObjectOutput, error) { + req, out := c.HeadObjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListBucketAnalyticsConfigurations = "ListBucketAnalyticsConfigurations" @@ -2610,6 +3282,7 @@ const opListBucketAnalyticsConfigurations = "ListBucketAnalyticsConfigurations" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketAnalyticsConfigurations func (c *S3) ListBucketAnalyticsConfigurationsRequest(input *ListBucketAnalyticsConfigurationsInput) (req *request.Request, output *ListBucketAnalyticsConfigurationsOutput) { op := &request.Operation{ Name: opListBucketAnalyticsConfigurations, @@ -2621,9 +3294,8 @@ func (c *S3) ListBucketAnalyticsConfigurationsRequest(input *ListBucketAnalytics input = &ListBucketAnalyticsConfigurationsInput{} } - req = c.newRequest(op, input, output) output = &ListBucketAnalyticsConfigurationsOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2637,10 +3309,26 @@ func (c *S3) ListBucketAnalyticsConfigurationsRequest(input *ListBucketAnalytics // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation ListBucketAnalyticsConfigurations for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketAnalyticsConfigurations func (c *S3) ListBucketAnalyticsConfigurations(input *ListBucketAnalyticsConfigurationsInput) (*ListBucketAnalyticsConfigurationsOutput, error) { req, out := c.ListBucketAnalyticsConfigurationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListBucketAnalyticsConfigurationsWithContext is the same as ListBucketAnalyticsConfigurations with the addition of +// the ability to pass a context and additional request options. +// +// See ListBucketAnalyticsConfigurations for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListBucketAnalyticsConfigurationsWithContext(ctx aws.Context, input *ListBucketAnalyticsConfigurationsInput, opts ...request.Option) (*ListBucketAnalyticsConfigurationsOutput, error) { + req, out := c.ListBucketAnalyticsConfigurationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListBucketInventoryConfigurations = "ListBucketInventoryConfigurations" @@ -2669,6 +3357,7 @@ const opListBucketInventoryConfigurations = "ListBucketInventoryConfigurations" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketInventoryConfigurations func (c *S3) ListBucketInventoryConfigurationsRequest(input *ListBucketInventoryConfigurationsInput) (req *request.Request, output *ListBucketInventoryConfigurationsOutput) { op := &request.Operation{ Name: opListBucketInventoryConfigurations, @@ -2680,9 +3369,8 @@ func (c *S3) ListBucketInventoryConfigurationsRequest(input *ListBucketInventory input = &ListBucketInventoryConfigurationsInput{} } - req = c.newRequest(op, input, output) output = &ListBucketInventoryConfigurationsOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2696,10 +3384,26 @@ func (c *S3) ListBucketInventoryConfigurationsRequest(input *ListBucketInventory // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation ListBucketInventoryConfigurations for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketInventoryConfigurations func (c *S3) ListBucketInventoryConfigurations(input *ListBucketInventoryConfigurationsInput) (*ListBucketInventoryConfigurationsOutput, error) { req, out := c.ListBucketInventoryConfigurationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListBucketInventoryConfigurationsWithContext is the same as ListBucketInventoryConfigurations with the addition of +// the ability to pass a context and additional request options. +// +// See ListBucketInventoryConfigurations for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListBucketInventoryConfigurationsWithContext(ctx aws.Context, input *ListBucketInventoryConfigurationsInput, opts ...request.Option) (*ListBucketInventoryConfigurationsOutput, error) { + req, out := c.ListBucketInventoryConfigurationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListBucketMetricsConfigurations = "ListBucketMetricsConfigurations" @@ -2728,6 +3432,7 @@ const opListBucketMetricsConfigurations = "ListBucketMetricsConfigurations" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketMetricsConfigurations func (c *S3) ListBucketMetricsConfigurationsRequest(input *ListBucketMetricsConfigurationsInput) (req *request.Request, output *ListBucketMetricsConfigurationsOutput) { op := &request.Operation{ Name: opListBucketMetricsConfigurations, @@ -2739,9 +3444,8 @@ func (c *S3) ListBucketMetricsConfigurationsRequest(input *ListBucketMetricsConf input = &ListBucketMetricsConfigurationsInput{} } - req = c.newRequest(op, input, output) output = &ListBucketMetricsConfigurationsOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2755,10 +3459,26 @@ func (c *S3) ListBucketMetricsConfigurationsRequest(input *ListBucketMetricsConf // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation ListBucketMetricsConfigurations for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketMetricsConfigurations func (c *S3) ListBucketMetricsConfigurations(input *ListBucketMetricsConfigurationsInput) (*ListBucketMetricsConfigurationsOutput, error) { req, out := c.ListBucketMetricsConfigurationsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListBucketMetricsConfigurationsWithContext is the same as ListBucketMetricsConfigurations with the addition of +// the ability to pass a context and additional request options. +// +// See ListBucketMetricsConfigurations for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListBucketMetricsConfigurationsWithContext(ctx aws.Context, input *ListBucketMetricsConfigurationsInput, opts ...request.Option) (*ListBucketMetricsConfigurationsOutput, error) { + req, out := c.ListBucketMetricsConfigurationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListBuckets = "ListBuckets" @@ -2787,6 +3507,7 @@ const opListBuckets = "ListBuckets" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBuckets func (c *S3) ListBucketsRequest(input *ListBucketsInput) (req *request.Request, output *ListBucketsOutput) { op := &request.Operation{ Name: opListBuckets, @@ -2798,9 +3519,8 @@ func (c *S3) ListBucketsRequest(input *ListBucketsInput) (req *request.Request, input = &ListBucketsInput{} } - req = c.newRequest(op, input, output) output = &ListBucketsOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2814,10 +3534,26 @@ func (c *S3) ListBucketsRequest(input *ListBucketsInput) (req *request.Request, // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation ListBuckets for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBuckets func (c *S3) ListBuckets(input *ListBucketsInput) (*ListBucketsOutput, error) { req, out := c.ListBucketsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListBucketsWithContext is the same as ListBuckets with the addition of +// the ability to pass a context and additional request options. +// +// See ListBuckets for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListBucketsWithContext(ctx aws.Context, input *ListBucketsInput, opts ...request.Option) (*ListBucketsOutput, error) { + req, out := c.ListBucketsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opListMultipartUploads = "ListMultipartUploads" @@ -2846,6 +3582,7 @@ const opListMultipartUploads = "ListMultipartUploads" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListMultipartUploads func (c *S3) ListMultipartUploadsRequest(input *ListMultipartUploadsInput) (req *request.Request, output *ListMultipartUploadsOutput) { op := &request.Operation{ Name: opListMultipartUploads, @@ -2863,9 +3600,8 @@ func (c *S3) ListMultipartUploadsRequest(input *ListMultipartUploadsInput) (req input = &ListMultipartUploadsInput{} } - req = c.newRequest(op, input, output) output = &ListMultipartUploadsOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2879,10 +3615,26 @@ func (c *S3) ListMultipartUploadsRequest(input *ListMultipartUploadsInput) (req // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation ListMultipartUploads for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListMultipartUploads func (c *S3) ListMultipartUploads(input *ListMultipartUploadsInput) (*ListMultipartUploadsOutput, error) { req, out := c.ListMultipartUploadsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListMultipartUploadsWithContext is the same as ListMultipartUploads with the addition of +// the ability to pass a context and additional request options. +// +// See ListMultipartUploads for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListMultipartUploadsWithContext(ctx aws.Context, input *ListMultipartUploadsInput, opts ...request.Option) (*ListMultipartUploadsOutput, error) { + req, out := c.ListMultipartUploadsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListMultipartUploadsPages iterates over the pages of a ListMultipartUploads operation, @@ -2902,12 +3654,37 @@ func (c *S3) ListMultipartUploads(input *ListMultipartUploadsInput) (*ListMultip // return pageNum <= 3 // }) // -func (c *S3) ListMultipartUploadsPages(input *ListMultipartUploadsInput, fn func(p *ListMultipartUploadsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListMultipartUploadsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListMultipartUploadsOutput), lastPage) - }) +func (c *S3) ListMultipartUploadsPages(input *ListMultipartUploadsInput, fn func(*ListMultipartUploadsOutput, bool) bool) error { + return c.ListMultipartUploadsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListMultipartUploadsPagesWithContext same as ListMultipartUploadsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListMultipartUploadsPagesWithContext(ctx aws.Context, input *ListMultipartUploadsInput, fn func(*ListMultipartUploadsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListMultipartUploadsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListMultipartUploadsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListMultipartUploadsOutput), !p.HasNextPage()) + } + return p.Err() } const opListObjectVersions = "ListObjectVersions" @@ -2936,6 +3713,7 @@ const opListObjectVersions = "ListObjectVersions" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectVersions func (c *S3) ListObjectVersionsRequest(input *ListObjectVersionsInput) (req *request.Request, output *ListObjectVersionsOutput) { op := &request.Operation{ Name: opListObjectVersions, @@ -2953,9 +3731,8 @@ func (c *S3) ListObjectVersionsRequest(input *ListObjectVersionsInput) (req *req input = &ListObjectVersionsInput{} } - req = c.newRequest(op, input, output) output = &ListObjectVersionsOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -2969,10 +3746,26 @@ func (c *S3) ListObjectVersionsRequest(input *ListObjectVersionsInput) (req *req // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation ListObjectVersions for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectVersions func (c *S3) ListObjectVersions(input *ListObjectVersionsInput) (*ListObjectVersionsOutput, error) { req, out := c.ListObjectVersionsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListObjectVersionsWithContext is the same as ListObjectVersions with the addition of +// the ability to pass a context and additional request options. +// +// See ListObjectVersions for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListObjectVersionsWithContext(ctx aws.Context, input *ListObjectVersionsInput, opts ...request.Option) (*ListObjectVersionsOutput, error) { + req, out := c.ListObjectVersionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListObjectVersionsPages iterates over the pages of a ListObjectVersions operation, @@ -2992,12 +3785,37 @@ func (c *S3) ListObjectVersions(input *ListObjectVersionsInput) (*ListObjectVers // return pageNum <= 3 // }) // -func (c *S3) ListObjectVersionsPages(input *ListObjectVersionsInput, fn func(p *ListObjectVersionsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListObjectVersionsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListObjectVersionsOutput), lastPage) - }) +func (c *S3) ListObjectVersionsPages(input *ListObjectVersionsInput, fn func(*ListObjectVersionsOutput, bool) bool) error { + return c.ListObjectVersionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListObjectVersionsPagesWithContext same as ListObjectVersionsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListObjectVersionsPagesWithContext(ctx aws.Context, input *ListObjectVersionsInput, fn func(*ListObjectVersionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListObjectVersionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListObjectVersionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListObjectVersionsOutput), !p.HasNextPage()) + } + return p.Err() } const opListObjects = "ListObjects" @@ -3026,6 +3844,7 @@ const opListObjects = "ListObjects" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjects func (c *S3) ListObjectsRequest(input *ListObjectsInput) (req *request.Request, output *ListObjectsOutput) { op := &request.Operation{ Name: opListObjects, @@ -3043,9 +3862,8 @@ func (c *S3) ListObjectsRequest(input *ListObjectsInput) (req *request.Request, input = &ListObjectsInput{} } - req = c.newRequest(op, input, output) output = &ListObjectsOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -3063,13 +3881,29 @@ func (c *S3) ListObjectsRequest(input *ListObjectsInput) (req *request.Request, // API operation ListObjects for usage and error information. // // Returned Error Codes: -// * NoSuchBucket +// * ErrCodeNoSuchBucket "NoSuchBucket" // The specified bucket does not exist. // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjects func (c *S3) ListObjects(input *ListObjectsInput) (*ListObjectsOutput, error) { req, out := c.ListObjectsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListObjectsWithContext is the same as ListObjects with the addition of +// the ability to pass a context and additional request options. +// +// See ListObjects for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListObjectsWithContext(ctx aws.Context, input *ListObjectsInput, opts ...request.Option) (*ListObjectsOutput, error) { + req, out := c.ListObjectsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListObjectsPages iterates over the pages of a ListObjects operation, @@ -3089,12 +3923,37 @@ func (c *S3) ListObjects(input *ListObjectsInput) (*ListObjectsOutput, error) { // return pageNum <= 3 // }) // -func (c *S3) ListObjectsPages(input *ListObjectsInput, fn func(p *ListObjectsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListObjectsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListObjectsOutput), lastPage) - }) +func (c *S3) ListObjectsPages(input *ListObjectsInput, fn func(*ListObjectsOutput, bool) bool) error { + return c.ListObjectsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListObjectsPagesWithContext same as ListObjectsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListObjectsPagesWithContext(ctx aws.Context, input *ListObjectsInput, fn func(*ListObjectsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListObjectsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListObjectsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListObjectsOutput), !p.HasNextPage()) + } + return p.Err() } const opListObjectsV2 = "ListObjectsV2" @@ -3123,6 +3982,7 @@ const opListObjectsV2 = "ListObjectsV2" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsV2 func (c *S3) ListObjectsV2Request(input *ListObjectsV2Input) (req *request.Request, output *ListObjectsV2Output) { op := &request.Operation{ Name: opListObjectsV2, @@ -3140,9 +4000,8 @@ func (c *S3) ListObjectsV2Request(input *ListObjectsV2Input) (req *request.Reque input = &ListObjectsV2Input{} } - req = c.newRequest(op, input, output) output = &ListObjectsV2Output{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -3161,13 +4020,29 @@ func (c *S3) ListObjectsV2Request(input *ListObjectsV2Input) (req *request.Reque // API operation ListObjectsV2 for usage and error information. // // Returned Error Codes: -// * NoSuchBucket +// * ErrCodeNoSuchBucket "NoSuchBucket" // The specified bucket does not exist. // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsV2 func (c *S3) ListObjectsV2(input *ListObjectsV2Input) (*ListObjectsV2Output, error) { req, out := c.ListObjectsV2Request(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListObjectsV2WithContext is the same as ListObjectsV2 with the addition of +// the ability to pass a context and additional request options. +// +// See ListObjectsV2 for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListObjectsV2WithContext(ctx aws.Context, input *ListObjectsV2Input, opts ...request.Option) (*ListObjectsV2Output, error) { + req, out := c.ListObjectsV2Request(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListObjectsV2Pages iterates over the pages of a ListObjectsV2 operation, @@ -3187,12 +4062,37 @@ func (c *S3) ListObjectsV2(input *ListObjectsV2Input) (*ListObjectsV2Output, err // return pageNum <= 3 // }) // -func (c *S3) ListObjectsV2Pages(input *ListObjectsV2Input, fn func(p *ListObjectsV2Output, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListObjectsV2Request(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListObjectsV2Output), lastPage) - }) +func (c *S3) ListObjectsV2Pages(input *ListObjectsV2Input, fn func(*ListObjectsV2Output, bool) bool) error { + return c.ListObjectsV2PagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListObjectsV2PagesWithContext same as ListObjectsV2Pages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListObjectsV2PagesWithContext(ctx aws.Context, input *ListObjectsV2Input, fn func(*ListObjectsV2Output, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListObjectsV2Input + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListObjectsV2Request(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListObjectsV2Output), !p.HasNextPage()) + } + return p.Err() } const opListParts = "ListParts" @@ -3221,6 +4121,7 @@ const opListParts = "ListParts" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListParts func (c *S3) ListPartsRequest(input *ListPartsInput) (req *request.Request, output *ListPartsOutput) { op := &request.Operation{ Name: opListParts, @@ -3238,9 +4139,8 @@ func (c *S3) ListPartsRequest(input *ListPartsInput) (req *request.Request, outp input = &ListPartsInput{} } - req = c.newRequest(op, input, output) output = &ListPartsOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -3254,10 +4154,26 @@ func (c *S3) ListPartsRequest(input *ListPartsInput) (req *request.Request, outp // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation ListParts for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListParts func (c *S3) ListParts(input *ListPartsInput) (*ListPartsOutput, error) { req, out := c.ListPartsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// ListPartsWithContext is the same as ListParts with the addition of +// the ability to pass a context and additional request options. +// +// See ListParts for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListPartsWithContext(ctx aws.Context, input *ListPartsInput, opts ...request.Option) (*ListPartsOutput, error) { + req, out := c.ListPartsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // ListPartsPages iterates over the pages of a ListParts operation, @@ -3277,12 +4193,37 @@ func (c *S3) ListParts(input *ListPartsInput) (*ListPartsOutput, error) { // return pageNum <= 3 // }) // -func (c *S3) ListPartsPages(input *ListPartsInput, fn func(p *ListPartsOutput, lastPage bool) (shouldContinue bool)) error { - page, _ := c.ListPartsRequest(input) - page.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler("Paginator")) - return page.EachPage(func(p interface{}, lastPage bool) bool { - return fn(p.(*ListPartsOutput), lastPage) - }) +func (c *S3) ListPartsPages(input *ListPartsInput, fn func(*ListPartsOutput, bool) bool) error { + return c.ListPartsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListPartsPagesWithContext same as ListPartsPages except +// it takes a Context and allows setting request options on the pages. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) ListPartsPagesWithContext(ctx aws.Context, input *ListPartsInput, fn func(*ListPartsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListPartsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListPartsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + cont := true + for p.Next() && cont { + cont = fn(p.Page().(*ListPartsOutput), !p.HasNextPage()) + } + return p.Err() } const opPutBucketAccelerateConfiguration = "PutBucketAccelerateConfiguration" @@ -3311,6 +4252,7 @@ const opPutBucketAccelerateConfiguration = "PutBucketAccelerateConfiguration" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAccelerateConfiguration func (c *S3) PutBucketAccelerateConfigurationRequest(input *PutBucketAccelerateConfigurationInput) (req *request.Request, output *PutBucketAccelerateConfigurationOutput) { op := &request.Operation{ Name: opPutBucketAccelerateConfiguration, @@ -3322,11 +4264,10 @@ func (c *S3) PutBucketAccelerateConfigurationRequest(input *PutBucketAccelerateC input = &PutBucketAccelerateConfigurationInput{} } + output = &PutBucketAccelerateConfigurationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutBucketAccelerateConfigurationOutput{} - req.Data = output return } @@ -3340,10 +4281,26 @@ func (c *S3) PutBucketAccelerateConfigurationRequest(input *PutBucketAccelerateC // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketAccelerateConfiguration for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAccelerateConfiguration func (c *S3) PutBucketAccelerateConfiguration(input *PutBucketAccelerateConfigurationInput) (*PutBucketAccelerateConfigurationOutput, error) { req, out := c.PutBucketAccelerateConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketAccelerateConfigurationWithContext is the same as PutBucketAccelerateConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketAccelerateConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketAccelerateConfigurationWithContext(ctx aws.Context, input *PutBucketAccelerateConfigurationInput, opts ...request.Option) (*PutBucketAccelerateConfigurationOutput, error) { + req, out := c.PutBucketAccelerateConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketAcl = "PutBucketAcl" @@ -3372,6 +4329,7 @@ const opPutBucketAcl = "PutBucketAcl" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAcl func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *request.Request, output *PutBucketAclOutput) { op := &request.Operation{ Name: opPutBucketAcl, @@ -3383,11 +4341,10 @@ func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *request.Request input = &PutBucketAclInput{} } + output = &PutBucketAclOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutBucketAclOutput{} - req.Data = output return } @@ -3401,10 +4358,26 @@ func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *request.Request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketAcl for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAcl func (c *S3) PutBucketAcl(input *PutBucketAclInput) (*PutBucketAclOutput, error) { req, out := c.PutBucketAclRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketAclWithContext is the same as PutBucketAcl with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketAcl for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketAclWithContext(ctx aws.Context, input *PutBucketAclInput, opts ...request.Option) (*PutBucketAclOutput, error) { + req, out := c.PutBucketAclRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketAnalyticsConfiguration = "PutBucketAnalyticsConfiguration" @@ -3433,6 +4406,7 @@ const opPutBucketAnalyticsConfiguration = "PutBucketAnalyticsConfiguration" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAnalyticsConfiguration func (c *S3) PutBucketAnalyticsConfigurationRequest(input *PutBucketAnalyticsConfigurationInput) (req *request.Request, output *PutBucketAnalyticsConfigurationOutput) { op := &request.Operation{ Name: opPutBucketAnalyticsConfiguration, @@ -3444,11 +4418,10 @@ func (c *S3) PutBucketAnalyticsConfigurationRequest(input *PutBucketAnalyticsCon input = &PutBucketAnalyticsConfigurationInput{} } + output = &PutBucketAnalyticsConfigurationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutBucketAnalyticsConfigurationOutput{} - req.Data = output return } @@ -3463,10 +4436,26 @@ func (c *S3) PutBucketAnalyticsConfigurationRequest(input *PutBucketAnalyticsCon // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketAnalyticsConfiguration for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAnalyticsConfiguration func (c *S3) PutBucketAnalyticsConfiguration(input *PutBucketAnalyticsConfigurationInput) (*PutBucketAnalyticsConfigurationOutput, error) { req, out := c.PutBucketAnalyticsConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketAnalyticsConfigurationWithContext is the same as PutBucketAnalyticsConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketAnalyticsConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketAnalyticsConfigurationWithContext(ctx aws.Context, input *PutBucketAnalyticsConfigurationInput, opts ...request.Option) (*PutBucketAnalyticsConfigurationOutput, error) { + req, out := c.PutBucketAnalyticsConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketCors = "PutBucketCors" @@ -3495,6 +4484,7 @@ const opPutBucketCors = "PutBucketCors" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketCors func (c *S3) PutBucketCorsRequest(input *PutBucketCorsInput) (req *request.Request, output *PutBucketCorsOutput) { op := &request.Operation{ Name: opPutBucketCors, @@ -3506,11 +4496,10 @@ func (c *S3) PutBucketCorsRequest(input *PutBucketCorsInput) (req *request.Reque input = &PutBucketCorsInput{} } + output = &PutBucketCorsOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutBucketCorsOutput{} - req.Data = output return } @@ -3524,10 +4513,26 @@ func (c *S3) PutBucketCorsRequest(input *PutBucketCorsInput) (req *request.Reque // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketCors for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketCors func (c *S3) PutBucketCors(input *PutBucketCorsInput) (*PutBucketCorsOutput, error) { req, out := c.PutBucketCorsRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketCorsWithContext is the same as PutBucketCors with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketCors for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketCorsWithContext(ctx aws.Context, input *PutBucketCorsInput, opts ...request.Option) (*PutBucketCorsOutput, error) { + req, out := c.PutBucketCorsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketInventoryConfiguration = "PutBucketInventoryConfiguration" @@ -3556,6 +4561,7 @@ const opPutBucketInventoryConfiguration = "PutBucketInventoryConfiguration" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketInventoryConfiguration func (c *S3) PutBucketInventoryConfigurationRequest(input *PutBucketInventoryConfigurationInput) (req *request.Request, output *PutBucketInventoryConfigurationOutput) { op := &request.Operation{ Name: opPutBucketInventoryConfiguration, @@ -3567,11 +4573,10 @@ func (c *S3) PutBucketInventoryConfigurationRequest(input *PutBucketInventoryCon input = &PutBucketInventoryConfigurationInput{} } + output = &PutBucketInventoryConfigurationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutBucketInventoryConfigurationOutput{} - req.Data = output return } @@ -3586,10 +4591,26 @@ func (c *S3) PutBucketInventoryConfigurationRequest(input *PutBucketInventoryCon // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketInventoryConfiguration for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketInventoryConfiguration func (c *S3) PutBucketInventoryConfiguration(input *PutBucketInventoryConfigurationInput) (*PutBucketInventoryConfigurationOutput, error) { req, out := c.PutBucketInventoryConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketInventoryConfigurationWithContext is the same as PutBucketInventoryConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketInventoryConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketInventoryConfigurationWithContext(ctx aws.Context, input *PutBucketInventoryConfigurationInput, opts ...request.Option) (*PutBucketInventoryConfigurationOutput, error) { + req, out := c.PutBucketInventoryConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketLifecycle = "PutBucketLifecycle" @@ -3618,6 +4639,7 @@ const opPutBucketLifecycle = "PutBucketLifecycle" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycle func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *request.Request, output *PutBucketLifecycleOutput) { if c.Client.Config.Logger != nil { c.Client.Config.Logger.Log("This operation, PutBucketLifecycle, has been deprecated") @@ -3632,11 +4654,10 @@ func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *req input = &PutBucketLifecycleInput{} } + output = &PutBucketLifecycleOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutBucketLifecycleOutput{} - req.Data = output return } @@ -3650,10 +4671,26 @@ func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *req // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketLifecycle for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycle func (c *S3) PutBucketLifecycle(input *PutBucketLifecycleInput) (*PutBucketLifecycleOutput, error) { req, out := c.PutBucketLifecycleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketLifecycleWithContext is the same as PutBucketLifecycle with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketLifecycle for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketLifecycleWithContext(ctx aws.Context, input *PutBucketLifecycleInput, opts ...request.Option) (*PutBucketLifecycleOutput, error) { + req, out := c.PutBucketLifecycleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketLifecycleConfiguration = "PutBucketLifecycleConfiguration" @@ -3682,6 +4719,7 @@ const opPutBucketLifecycleConfiguration = "PutBucketLifecycleConfiguration" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleConfiguration func (c *S3) PutBucketLifecycleConfigurationRequest(input *PutBucketLifecycleConfigurationInput) (req *request.Request, output *PutBucketLifecycleConfigurationOutput) { op := &request.Operation{ Name: opPutBucketLifecycleConfiguration, @@ -3693,11 +4731,10 @@ func (c *S3) PutBucketLifecycleConfigurationRequest(input *PutBucketLifecycleCon input = &PutBucketLifecycleConfigurationInput{} } + output = &PutBucketLifecycleConfigurationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutBucketLifecycleConfigurationOutput{} - req.Data = output return } @@ -3712,10 +4749,26 @@ func (c *S3) PutBucketLifecycleConfigurationRequest(input *PutBucketLifecycleCon // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketLifecycleConfiguration for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleConfiguration func (c *S3) PutBucketLifecycleConfiguration(input *PutBucketLifecycleConfigurationInput) (*PutBucketLifecycleConfigurationOutput, error) { req, out := c.PutBucketLifecycleConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketLifecycleConfigurationWithContext is the same as PutBucketLifecycleConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketLifecycleConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketLifecycleConfigurationWithContext(ctx aws.Context, input *PutBucketLifecycleConfigurationInput, opts ...request.Option) (*PutBucketLifecycleConfigurationOutput, error) { + req, out := c.PutBucketLifecycleConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketLogging = "PutBucketLogging" @@ -3744,6 +4797,7 @@ const opPutBucketLogging = "PutBucketLogging" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLogging func (c *S3) PutBucketLoggingRequest(input *PutBucketLoggingInput) (req *request.Request, output *PutBucketLoggingOutput) { op := &request.Operation{ Name: opPutBucketLogging, @@ -3755,11 +4809,10 @@ func (c *S3) PutBucketLoggingRequest(input *PutBucketLoggingInput) (req *request input = &PutBucketLoggingInput{} } + output = &PutBucketLoggingOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutBucketLoggingOutput{} - req.Data = output return } @@ -3775,10 +4828,26 @@ func (c *S3) PutBucketLoggingRequest(input *PutBucketLoggingInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketLogging for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLogging func (c *S3) PutBucketLogging(input *PutBucketLoggingInput) (*PutBucketLoggingOutput, error) { req, out := c.PutBucketLoggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketLoggingWithContext is the same as PutBucketLogging with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketLogging for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketLoggingWithContext(ctx aws.Context, input *PutBucketLoggingInput, opts ...request.Option) (*PutBucketLoggingOutput, error) { + req, out := c.PutBucketLoggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketMetricsConfiguration = "PutBucketMetricsConfiguration" @@ -3807,6 +4876,7 @@ const opPutBucketMetricsConfiguration = "PutBucketMetricsConfiguration" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketMetricsConfiguration func (c *S3) PutBucketMetricsConfigurationRequest(input *PutBucketMetricsConfigurationInput) (req *request.Request, output *PutBucketMetricsConfigurationOutput) { op := &request.Operation{ Name: opPutBucketMetricsConfiguration, @@ -3818,11 +4888,10 @@ func (c *S3) PutBucketMetricsConfigurationRequest(input *PutBucketMetricsConfigu input = &PutBucketMetricsConfigurationInput{} } + output = &PutBucketMetricsConfigurationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutBucketMetricsConfigurationOutput{} - req.Data = output return } @@ -3837,10 +4906,26 @@ func (c *S3) PutBucketMetricsConfigurationRequest(input *PutBucketMetricsConfigu // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketMetricsConfiguration for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketMetricsConfiguration func (c *S3) PutBucketMetricsConfiguration(input *PutBucketMetricsConfigurationInput) (*PutBucketMetricsConfigurationOutput, error) { req, out := c.PutBucketMetricsConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketMetricsConfigurationWithContext is the same as PutBucketMetricsConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketMetricsConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketMetricsConfigurationWithContext(ctx aws.Context, input *PutBucketMetricsConfigurationInput, opts ...request.Option) (*PutBucketMetricsConfigurationOutput, error) { + req, out := c.PutBucketMetricsConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketNotification = "PutBucketNotification" @@ -3869,6 +4954,7 @@ const opPutBucketNotification = "PutBucketNotification" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotification func (c *S3) PutBucketNotificationRequest(input *PutBucketNotificationInput) (req *request.Request, output *PutBucketNotificationOutput) { if c.Client.Config.Logger != nil { c.Client.Config.Logger.Log("This operation, PutBucketNotification, has been deprecated") @@ -3883,11 +4969,10 @@ func (c *S3) PutBucketNotificationRequest(input *PutBucketNotificationInput) (re input = &PutBucketNotificationInput{} } + output = &PutBucketNotificationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutBucketNotificationOutput{} - req.Data = output return } @@ -3901,10 +4986,26 @@ func (c *S3) PutBucketNotificationRequest(input *PutBucketNotificationInput) (re // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketNotification for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotification func (c *S3) PutBucketNotification(input *PutBucketNotificationInput) (*PutBucketNotificationOutput, error) { req, out := c.PutBucketNotificationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketNotificationWithContext is the same as PutBucketNotification with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketNotification for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketNotificationWithContext(ctx aws.Context, input *PutBucketNotificationInput, opts ...request.Option) (*PutBucketNotificationOutput, error) { + req, out := c.PutBucketNotificationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketNotificationConfiguration = "PutBucketNotificationConfiguration" @@ -3933,6 +5034,7 @@ const opPutBucketNotificationConfiguration = "PutBucketNotificationConfiguration // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationConfiguration func (c *S3) PutBucketNotificationConfigurationRequest(input *PutBucketNotificationConfigurationInput) (req *request.Request, output *PutBucketNotificationConfigurationOutput) { op := &request.Operation{ Name: opPutBucketNotificationConfiguration, @@ -3944,11 +5046,10 @@ func (c *S3) PutBucketNotificationConfigurationRequest(input *PutBucketNotificat input = &PutBucketNotificationConfigurationInput{} } + output = &PutBucketNotificationConfigurationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutBucketNotificationConfigurationOutput{} - req.Data = output return } @@ -3962,10 +5063,26 @@ func (c *S3) PutBucketNotificationConfigurationRequest(input *PutBucketNotificat // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketNotificationConfiguration for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationConfiguration func (c *S3) PutBucketNotificationConfiguration(input *PutBucketNotificationConfigurationInput) (*PutBucketNotificationConfigurationOutput, error) { req, out := c.PutBucketNotificationConfigurationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketNotificationConfigurationWithContext is the same as PutBucketNotificationConfiguration with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketNotificationConfiguration for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketNotificationConfigurationWithContext(ctx aws.Context, input *PutBucketNotificationConfigurationInput, opts ...request.Option) (*PutBucketNotificationConfigurationOutput, error) { + req, out := c.PutBucketNotificationConfigurationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketPolicy = "PutBucketPolicy" @@ -3994,6 +5111,7 @@ const opPutBucketPolicy = "PutBucketPolicy" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketPolicy func (c *S3) PutBucketPolicyRequest(input *PutBucketPolicyInput) (req *request.Request, output *PutBucketPolicyOutput) { op := &request.Operation{ Name: opPutBucketPolicy, @@ -4005,11 +5123,10 @@ func (c *S3) PutBucketPolicyRequest(input *PutBucketPolicyInput) (req *request.R input = &PutBucketPolicyInput{} } + output = &PutBucketPolicyOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutBucketPolicyOutput{} - req.Data = output return } @@ -4024,10 +5141,26 @@ func (c *S3) PutBucketPolicyRequest(input *PutBucketPolicyInput) (req *request.R // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketPolicy for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketPolicy func (c *S3) PutBucketPolicy(input *PutBucketPolicyInput) (*PutBucketPolicyOutput, error) { req, out := c.PutBucketPolicyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketPolicyWithContext is the same as PutBucketPolicy with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketPolicy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketPolicyWithContext(ctx aws.Context, input *PutBucketPolicyInput, opts ...request.Option) (*PutBucketPolicyOutput, error) { + req, out := c.PutBucketPolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketReplication = "PutBucketReplication" @@ -4056,6 +5189,7 @@ const opPutBucketReplication = "PutBucketReplication" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketReplication func (c *S3) PutBucketReplicationRequest(input *PutBucketReplicationInput) (req *request.Request, output *PutBucketReplicationOutput) { op := &request.Operation{ Name: opPutBucketReplication, @@ -4067,11 +5201,10 @@ func (c *S3) PutBucketReplicationRequest(input *PutBucketReplicationInput) (req input = &PutBucketReplicationInput{} } + output = &PutBucketReplicationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutBucketReplicationOutput{} - req.Data = output return } @@ -4086,10 +5219,26 @@ func (c *S3) PutBucketReplicationRequest(input *PutBucketReplicationInput) (req // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketReplication for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketReplication func (c *S3) PutBucketReplication(input *PutBucketReplicationInput) (*PutBucketReplicationOutput, error) { req, out := c.PutBucketReplicationRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketReplicationWithContext is the same as PutBucketReplication with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketReplication for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketReplicationWithContext(ctx aws.Context, input *PutBucketReplicationInput, opts ...request.Option) (*PutBucketReplicationOutput, error) { + req, out := c.PutBucketReplicationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketRequestPayment = "PutBucketRequestPayment" @@ -4118,6 +5267,7 @@ const opPutBucketRequestPayment = "PutBucketRequestPayment" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketRequestPayment func (c *S3) PutBucketRequestPaymentRequest(input *PutBucketRequestPaymentInput) (req *request.Request, output *PutBucketRequestPaymentOutput) { op := &request.Operation{ Name: opPutBucketRequestPayment, @@ -4129,11 +5279,10 @@ func (c *S3) PutBucketRequestPaymentRequest(input *PutBucketRequestPaymentInput) input = &PutBucketRequestPaymentInput{} } + output = &PutBucketRequestPaymentOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutBucketRequestPaymentOutput{} - req.Data = output return } @@ -4151,10 +5300,26 @@ func (c *S3) PutBucketRequestPaymentRequest(input *PutBucketRequestPaymentInput) // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketRequestPayment for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketRequestPayment func (c *S3) PutBucketRequestPayment(input *PutBucketRequestPaymentInput) (*PutBucketRequestPaymentOutput, error) { req, out := c.PutBucketRequestPaymentRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketRequestPaymentWithContext is the same as PutBucketRequestPayment with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketRequestPayment for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketRequestPaymentWithContext(ctx aws.Context, input *PutBucketRequestPaymentInput, opts ...request.Option) (*PutBucketRequestPaymentOutput, error) { + req, out := c.PutBucketRequestPaymentRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketTagging = "PutBucketTagging" @@ -4183,6 +5348,7 @@ const opPutBucketTagging = "PutBucketTagging" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketTagging func (c *S3) PutBucketTaggingRequest(input *PutBucketTaggingInput) (req *request.Request, output *PutBucketTaggingOutput) { op := &request.Operation{ Name: opPutBucketTagging, @@ -4194,11 +5360,10 @@ func (c *S3) PutBucketTaggingRequest(input *PutBucketTaggingInput) (req *request input = &PutBucketTaggingInput{} } + output = &PutBucketTaggingOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutBucketTaggingOutput{} - req.Data = output return } @@ -4212,10 +5377,26 @@ func (c *S3) PutBucketTaggingRequest(input *PutBucketTaggingInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketTagging for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketTagging func (c *S3) PutBucketTagging(input *PutBucketTaggingInput) (*PutBucketTaggingOutput, error) { req, out := c.PutBucketTaggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketTaggingWithContext is the same as PutBucketTagging with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketTagging for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketTaggingWithContext(ctx aws.Context, input *PutBucketTaggingInput, opts ...request.Option) (*PutBucketTaggingOutput, error) { + req, out := c.PutBucketTaggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketVersioning = "PutBucketVersioning" @@ -4244,6 +5425,7 @@ const opPutBucketVersioning = "PutBucketVersioning" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketVersioning func (c *S3) PutBucketVersioningRequest(input *PutBucketVersioningInput) (req *request.Request, output *PutBucketVersioningOutput) { op := &request.Operation{ Name: opPutBucketVersioning, @@ -4255,11 +5437,10 @@ func (c *S3) PutBucketVersioningRequest(input *PutBucketVersioningInput) (req *r input = &PutBucketVersioningInput{} } + output = &PutBucketVersioningOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutBucketVersioningOutput{} - req.Data = output return } @@ -4274,10 +5455,26 @@ func (c *S3) PutBucketVersioningRequest(input *PutBucketVersioningInput) (req *r // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketVersioning for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketVersioning func (c *S3) PutBucketVersioning(input *PutBucketVersioningInput) (*PutBucketVersioningOutput, error) { req, out := c.PutBucketVersioningRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketVersioningWithContext is the same as PutBucketVersioning with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketVersioning for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketVersioningWithContext(ctx aws.Context, input *PutBucketVersioningInput, opts ...request.Option) (*PutBucketVersioningOutput, error) { + req, out := c.PutBucketVersioningRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutBucketWebsite = "PutBucketWebsite" @@ -4306,6 +5503,7 @@ const opPutBucketWebsite = "PutBucketWebsite" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketWebsite func (c *S3) PutBucketWebsiteRequest(input *PutBucketWebsiteInput) (req *request.Request, output *PutBucketWebsiteOutput) { op := &request.Operation{ Name: opPutBucketWebsite, @@ -4317,11 +5515,10 @@ func (c *S3) PutBucketWebsiteRequest(input *PutBucketWebsiteInput) (req *request input = &PutBucketWebsiteInput{} } + output = &PutBucketWebsiteOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - output = &PutBucketWebsiteOutput{} - req.Data = output return } @@ -4335,10 +5532,26 @@ func (c *S3) PutBucketWebsiteRequest(input *PutBucketWebsiteInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutBucketWebsite for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketWebsite func (c *S3) PutBucketWebsite(input *PutBucketWebsiteInput) (*PutBucketWebsiteOutput, error) { req, out := c.PutBucketWebsiteRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutBucketWebsiteWithContext is the same as PutBucketWebsite with the addition of +// the ability to pass a context and additional request options. +// +// See PutBucketWebsite for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutBucketWebsiteWithContext(ctx aws.Context, input *PutBucketWebsiteInput, opts ...request.Option) (*PutBucketWebsiteOutput, error) { + req, out := c.PutBucketWebsiteRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutObject = "PutObject" @@ -4367,6 +5580,7 @@ const opPutObject = "PutObject" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObject func (c *S3) PutObjectRequest(input *PutObjectInput) (req *request.Request, output *PutObjectOutput) { op := &request.Operation{ Name: opPutObject, @@ -4378,9 +5592,8 @@ func (c *S3) PutObjectRequest(input *PutObjectInput) (req *request.Request, outp input = &PutObjectInput{} } - req = c.newRequest(op, input, output) output = &PutObjectOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -4394,10 +5607,26 @@ func (c *S3) PutObjectRequest(input *PutObjectInput) (req *request.Request, outp // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutObject for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObject func (c *S3) PutObject(input *PutObjectInput) (*PutObjectOutput, error) { req, out := c.PutObjectRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutObjectWithContext is the same as PutObject with the addition of +// the ability to pass a context and additional request options. +// +// See PutObject for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutObjectWithContext(ctx aws.Context, input *PutObjectInput, opts ...request.Option) (*PutObjectOutput, error) { + req, out := c.PutObjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutObjectAcl = "PutObjectAcl" @@ -4426,6 +5655,7 @@ const opPutObjectAcl = "PutObjectAcl" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectAcl func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request, output *PutObjectAclOutput) { op := &request.Operation{ Name: opPutObjectAcl, @@ -4437,9 +5667,8 @@ func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request input = &PutObjectAclInput{} } - req = c.newRequest(op, input, output) output = &PutObjectAclOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -4456,13 +5685,29 @@ func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request // API operation PutObjectAcl for usage and error information. // // Returned Error Codes: -// * NoSuchKey +// * ErrCodeNoSuchKey "NoSuchKey" // The specified key does not exist. // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectAcl func (c *S3) PutObjectAcl(input *PutObjectAclInput) (*PutObjectAclOutput, error) { req, out := c.PutObjectAclRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutObjectAclWithContext is the same as PutObjectAcl with the addition of +// the ability to pass a context and additional request options. +// +// See PutObjectAcl for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutObjectAclWithContext(ctx aws.Context, input *PutObjectAclInput, opts ...request.Option) (*PutObjectAclOutput, error) { + req, out := c.PutObjectAclRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opPutObjectTagging = "PutObjectTagging" @@ -4491,6 +5736,7 @@ const opPutObjectTagging = "PutObjectTagging" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectTagging func (c *S3) PutObjectTaggingRequest(input *PutObjectTaggingInput) (req *request.Request, output *PutObjectTaggingOutput) { op := &request.Operation{ Name: opPutObjectTagging, @@ -4502,9 +5748,8 @@ func (c *S3) PutObjectTaggingRequest(input *PutObjectTaggingInput) (req *request input = &PutObjectTaggingInput{} } - req = c.newRequest(op, input, output) output = &PutObjectTaggingOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -4518,10 +5763,26 @@ func (c *S3) PutObjectTaggingRequest(input *PutObjectTaggingInput) (req *request // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation PutObjectTagging for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectTagging func (c *S3) PutObjectTagging(input *PutObjectTaggingInput) (*PutObjectTaggingOutput, error) { req, out := c.PutObjectTaggingRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// PutObjectTaggingWithContext is the same as PutObjectTagging with the addition of +// the ability to pass a context and additional request options. +// +// See PutObjectTagging for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) PutObjectTaggingWithContext(ctx aws.Context, input *PutObjectTaggingInput, opts ...request.Option) (*PutObjectTaggingOutput, error) { + req, out := c.PutObjectTaggingRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opRestoreObject = "RestoreObject" @@ -4550,6 +5811,7 @@ const opRestoreObject = "RestoreObject" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreObject func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Request, output *RestoreObjectOutput) { op := &request.Operation{ Name: opRestoreObject, @@ -4561,9 +5823,8 @@ func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Reque input = &RestoreObjectInput{} } - req = c.newRequest(op, input, output) output = &RestoreObjectOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -4579,13 +5840,29 @@ func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Reque // API operation RestoreObject for usage and error information. // // Returned Error Codes: -// * ObjectAlreadyInActiveTierError +// * ErrCodeObjectAlreadyInActiveTierError "ObjectAlreadyInActiveTierError" // This operation is not allowed against this storage tier // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreObject func (c *S3) RestoreObject(input *RestoreObjectInput) (*RestoreObjectOutput, error) { req, out := c.RestoreObjectRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// RestoreObjectWithContext is the same as RestoreObject with the addition of +// the ability to pass a context and additional request options. +// +// See RestoreObject for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) RestoreObjectWithContext(ctx aws.Context, input *RestoreObjectInput, opts ...request.Option) (*RestoreObjectOutput, error) { + req, out := c.RestoreObjectRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUploadPart = "UploadPart" @@ -4614,6 +5891,7 @@ const opUploadPart = "UploadPart" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPart func (c *S3) UploadPartRequest(input *UploadPartInput) (req *request.Request, output *UploadPartOutput) { op := &request.Operation{ Name: opUploadPart, @@ -4625,9 +5903,8 @@ func (c *S3) UploadPartRequest(input *UploadPartInput) (req *request.Request, ou input = &UploadPartInput{} } - req = c.newRequest(op, input, output) output = &UploadPartOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -4647,10 +5924,26 @@ func (c *S3) UploadPartRequest(input *UploadPartInput) (req *request.Request, ou // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation UploadPart for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPart func (c *S3) UploadPart(input *UploadPartInput) (*UploadPartOutput, error) { req, out := c.UploadPartRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UploadPartWithContext is the same as UploadPart with the addition of +// the ability to pass a context and additional request options. +// +// See UploadPart for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) UploadPartWithContext(ctx aws.Context, input *UploadPartInput, opts ...request.Option) (*UploadPartOutput, error) { + req, out := c.UploadPartRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opUploadPartCopy = "UploadPartCopy" @@ -4679,6 +5972,7 @@ const opUploadPartCopy = "UploadPartCopy" // fmt.Println(resp) // } // +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartCopy func (c *S3) UploadPartCopyRequest(input *UploadPartCopyInput) (req *request.Request, output *UploadPartCopyOutput) { op := &request.Operation{ Name: opUploadPartCopy, @@ -4690,9 +5984,8 @@ func (c *S3) UploadPartCopyRequest(input *UploadPartCopyInput) (req *request.Req input = &UploadPartCopyInput{} } - req = c.newRequest(op, input, output) output = &UploadPartCopyOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -4706,14 +5999,31 @@ func (c *S3) UploadPartCopyRequest(input *UploadPartCopyInput) (req *request.Req // // See the AWS API reference guide for Amazon Simple Storage Service's // API operation UploadPartCopy for usage and error information. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartCopy func (c *S3) UploadPartCopy(input *UploadPartCopyInput) (*UploadPartCopyOutput, error) { req, out := c.UploadPartCopyRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// UploadPartCopyWithContext is the same as UploadPartCopy with the addition of +// the ability to pass a context and additional request options. +// +// See UploadPartCopy for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) UploadPartCopyWithContext(ctx aws.Context, input *UploadPartCopyInput, opts ...request.Option) (*UploadPartCopyOutput, error) { + req, out := c.UploadPartCopyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Specifies the days since the initiation of an Incomplete Multipart Upload // that Lifecycle will wait before permanently removing all parts of the upload. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortIncompleteMultipartUpload type AbortIncompleteMultipartUpload struct { _ struct{} `type:"structure"` @@ -4738,6 +6048,7 @@ func (s *AbortIncompleteMultipartUpload) SetDaysAfterInitiation(v int64) *AbortI return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortMultipartUploadRequest type AbortMultipartUploadInput struct { _ struct{} `type:"structure"` @@ -4813,6 +6124,7 @@ func (s *AbortMultipartUploadInput) SetUploadId(v string) *AbortMultipartUploadI return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortMultipartUploadOutput type AbortMultipartUploadOutput struct { _ struct{} `type:"structure"` @@ -4837,6 +6149,7 @@ func (s *AbortMultipartUploadOutput) SetRequestCharged(v string) *AbortMultipart return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AccelerateConfiguration type AccelerateConfiguration struct { _ struct{} `type:"structure"` @@ -4860,6 +6173,7 @@ func (s *AccelerateConfiguration) SetStatus(v string) *AccelerateConfiguration { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AccessControlPolicy type AccessControlPolicy struct { _ struct{} `type:"structure"` @@ -4911,6 +6225,7 @@ func (s *AccessControlPolicy) SetOwner(v *Owner) *AccessControlPolicy { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AnalyticsAndOperator type AnalyticsAndOperator struct { _ struct{} `type:"structure"` @@ -4963,6 +6278,7 @@ func (s *AnalyticsAndOperator) SetTags(v []*Tag) *AnalyticsAndOperator { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AnalyticsConfiguration type AnalyticsConfiguration struct { _ struct{} `type:"structure"` @@ -5037,6 +6353,7 @@ func (s *AnalyticsConfiguration) SetStorageClassAnalysis(v *StorageClassAnalysis return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AnalyticsExportDestination type AnalyticsExportDestination struct { _ struct{} `type:"structure"` @@ -5080,6 +6397,7 @@ func (s *AnalyticsExportDestination) SetS3BucketDestination(v *AnalyticsS3Bucket return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AnalyticsFilter type AnalyticsFilter struct { _ struct{} `type:"structure"` @@ -5142,6 +6460,7 @@ func (s *AnalyticsFilter) SetTag(v *Tag) *AnalyticsFilter { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AnalyticsS3BucketDestination type AnalyticsS3BucketDestination struct { _ struct{} `type:"structure"` @@ -5214,6 +6533,7 @@ func (s *AnalyticsS3BucketDestination) SetPrefix(v string) *AnalyticsS3BucketDes return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Bucket type Bucket struct { _ struct{} `type:"structure"` @@ -5246,6 +6566,7 @@ func (s *Bucket) SetName(v string) *Bucket { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/BucketLifecycleConfiguration type BucketLifecycleConfiguration struct { _ struct{} `type:"structure"` @@ -5292,6 +6613,7 @@ func (s *BucketLifecycleConfiguration) SetRules(v []*LifecycleRule) *BucketLifec return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/BucketLoggingStatus type BucketLoggingStatus struct { _ struct{} `type:"structure"` @@ -5329,6 +6651,7 @@ func (s *BucketLoggingStatus) SetLoggingEnabled(v *LoggingEnabled) *BucketLoggin return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CORSConfiguration type CORSConfiguration struct { _ struct{} `type:"structure"` @@ -5375,6 +6698,7 @@ func (s *CORSConfiguration) SetCORSRules(v []*CORSRule) *CORSConfiguration { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CORSRule type CORSRule struct { _ struct{} `type:"structure"` @@ -5458,6 +6782,7 @@ func (s *CORSRule) SetMaxAgeSeconds(v int64) *CORSRule { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CloudFunctionConfiguration type CloudFunctionConfiguration struct { _ struct{} `type:"structure"` @@ -5515,6 +6840,7 @@ func (s *CloudFunctionConfiguration) SetInvocationRole(v string) *CloudFunctionC return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CommonPrefix type CommonPrefix struct { _ struct{} `type:"structure"` @@ -5537,6 +6863,7 @@ func (s *CommonPrefix) SetPrefix(v string) *CommonPrefix { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompleteMultipartUploadRequest type CompleteMultipartUploadInput struct { _ struct{} `type:"structure" payload:"MultipartUpload"` @@ -5620,6 +6947,7 @@ func (s *CompleteMultipartUploadInput) SetUploadId(v string) *CompleteMultipartU return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompleteMultipartUploadOutput type CompleteMultipartUploadOutput struct { _ struct{} `type:"structure"` @@ -5716,6 +7044,7 @@ func (s *CompleteMultipartUploadOutput) SetVersionId(v string) *CompleteMultipar return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompletedMultipartUpload type CompletedMultipartUpload struct { _ struct{} `type:"structure"` @@ -5738,6 +7067,7 @@ func (s *CompletedMultipartUpload) SetParts(v []*CompletedPart) *CompletedMultip return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompletedPart type CompletedPart struct { _ struct{} `type:"structure"` @@ -5771,6 +7101,7 @@ func (s *CompletedPart) SetPartNumber(v int64) *CompletedPart { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Condition type Condition struct { _ struct{} `type:"structure"` @@ -5813,6 +7144,7 @@ func (s *Condition) SetKeyPrefixEquals(v string) *Condition { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObjectRequest type CopyObjectInput struct { _ struct{} `type:"structure"` @@ -6175,6 +7507,7 @@ func (s *CopyObjectInput) SetWebsiteRedirectLocation(v string) *CopyObjectInput return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObjectOutput type CopyObjectOutput struct { _ struct{} `type:"structure" payload:"CopyObjectResult"` @@ -6275,6 +7608,7 @@ func (s *CopyObjectOutput) SetVersionId(v string) *CopyObjectOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObjectResult type CopyObjectResult struct { _ struct{} `type:"structure"` @@ -6305,6 +7639,7 @@ func (s *CopyObjectResult) SetLastModified(v time.Time) *CopyObjectResult { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyPartResult type CopyPartResult struct { _ struct{} `type:"structure"` @@ -6337,6 +7672,7 @@ func (s *CopyPartResult) SetLastModified(v time.Time) *CopyPartResult { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucketConfiguration type CreateBucketConfiguration struct { _ struct{} `type:"structure"` @@ -6361,6 +7697,7 @@ func (s *CreateBucketConfiguration) SetLocationConstraint(v string) *CreateBucke return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucketRequest type CreateBucketInput struct { _ struct{} `type:"structure" payload:"CreateBucketConfiguration"` @@ -6460,6 +7797,7 @@ func (s *CreateBucketInput) SetGrantWriteACP(v string) *CreateBucketInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucketOutput type CreateBucketOutput struct { _ struct{} `type:"structure"` @@ -6482,6 +7820,7 @@ func (s *CreateBucketOutput) SetLocation(v string) *CreateBucketOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateMultipartUploadRequest type CreateMultipartUploadInput struct { _ struct{} `type:"structure"` @@ -6730,6 +8069,7 @@ func (s *CreateMultipartUploadInput) SetWebsiteRedirectLocation(v string) *Creat return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateMultipartUploadOutput type CreateMultipartUploadOutput struct { _ struct{} `type:"structure"` @@ -6842,6 +8182,7 @@ func (s *CreateMultipartUploadOutput) SetUploadId(v string) *CreateMultipartUplo return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Delete type Delete struct { _ struct{} `type:"structure"` @@ -6898,6 +8239,7 @@ func (s *Delete) SetQuiet(v bool) *Delete { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketAnalyticsConfigurationRequest type DeleteBucketAnalyticsConfigurationInput struct { _ struct{} `type:"structure"` @@ -6950,6 +8292,7 @@ func (s *DeleteBucketAnalyticsConfigurationInput) SetId(v string) *DeleteBucketA return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketAnalyticsConfigurationOutput type DeleteBucketAnalyticsConfigurationOutput struct { _ struct{} `type:"structure"` } @@ -6964,6 +8307,7 @@ func (s DeleteBucketAnalyticsConfigurationOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketCorsRequest type DeleteBucketCorsInput struct { _ struct{} `type:"structure"` @@ -7000,6 +8344,7 @@ func (s *DeleteBucketCorsInput) SetBucket(v string) *DeleteBucketCorsInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketCorsOutput type DeleteBucketCorsOutput struct { _ struct{} `type:"structure"` } @@ -7014,6 +8359,7 @@ func (s DeleteBucketCorsOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketRequest type DeleteBucketInput struct { _ struct{} `type:"structure"` @@ -7050,6 +8396,7 @@ func (s *DeleteBucketInput) SetBucket(v string) *DeleteBucketInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketInventoryConfigurationRequest type DeleteBucketInventoryConfigurationInput struct { _ struct{} `type:"structure"` @@ -7102,6 +8449,7 @@ func (s *DeleteBucketInventoryConfigurationInput) SetId(v string) *DeleteBucketI return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketInventoryConfigurationOutput type DeleteBucketInventoryConfigurationOutput struct { _ struct{} `type:"structure"` } @@ -7116,6 +8464,7 @@ func (s DeleteBucketInventoryConfigurationOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketLifecycleRequest type DeleteBucketLifecycleInput struct { _ struct{} `type:"structure"` @@ -7152,6 +8501,7 @@ func (s *DeleteBucketLifecycleInput) SetBucket(v string) *DeleteBucketLifecycleI return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketLifecycleOutput type DeleteBucketLifecycleOutput struct { _ struct{} `type:"structure"` } @@ -7166,6 +8516,7 @@ func (s DeleteBucketLifecycleOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketMetricsConfigurationRequest type DeleteBucketMetricsConfigurationInput struct { _ struct{} `type:"structure"` @@ -7218,6 +8569,7 @@ func (s *DeleteBucketMetricsConfigurationInput) SetId(v string) *DeleteBucketMet return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketMetricsConfigurationOutput type DeleteBucketMetricsConfigurationOutput struct { _ struct{} `type:"structure"` } @@ -7232,6 +8584,7 @@ func (s DeleteBucketMetricsConfigurationOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketOutput type DeleteBucketOutput struct { _ struct{} `type:"structure"` } @@ -7246,6 +8599,7 @@ func (s DeleteBucketOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketPolicyRequest type DeleteBucketPolicyInput struct { _ struct{} `type:"structure"` @@ -7282,6 +8636,7 @@ func (s *DeleteBucketPolicyInput) SetBucket(v string) *DeleteBucketPolicyInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketPolicyOutput type DeleteBucketPolicyOutput struct { _ struct{} `type:"structure"` } @@ -7296,6 +8651,7 @@ func (s DeleteBucketPolicyOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketReplicationRequest type DeleteBucketReplicationInput struct { _ struct{} `type:"structure"` @@ -7332,6 +8688,7 @@ func (s *DeleteBucketReplicationInput) SetBucket(v string) *DeleteBucketReplicat return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketReplicationOutput type DeleteBucketReplicationOutput struct { _ struct{} `type:"structure"` } @@ -7346,6 +8703,7 @@ func (s DeleteBucketReplicationOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketTaggingRequest type DeleteBucketTaggingInput struct { _ struct{} `type:"structure"` @@ -7382,6 +8740,7 @@ func (s *DeleteBucketTaggingInput) SetBucket(v string) *DeleteBucketTaggingInput return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketTaggingOutput type DeleteBucketTaggingOutput struct { _ struct{} `type:"structure"` } @@ -7396,6 +8755,7 @@ func (s DeleteBucketTaggingOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketWebsiteRequest type DeleteBucketWebsiteInput struct { _ struct{} `type:"structure"` @@ -7432,6 +8792,7 @@ func (s *DeleteBucketWebsiteInput) SetBucket(v string) *DeleteBucketWebsiteInput return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketWebsiteOutput type DeleteBucketWebsiteOutput struct { _ struct{} `type:"structure"` } @@ -7446,6 +8807,7 @@ func (s DeleteBucketWebsiteOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteMarkerEntry type DeleteMarkerEntry struct { _ struct{} `type:"structure"` @@ -7505,6 +8867,7 @@ func (s *DeleteMarkerEntry) SetVersionId(v string) *DeleteMarkerEntry { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectRequest type DeleteObjectInput struct { _ struct{} `type:"structure"` @@ -7587,6 +8950,7 @@ func (s *DeleteObjectInput) SetVersionId(v string) *DeleteObjectInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectOutput type DeleteObjectOutput struct { _ struct{} `type:"structure"` @@ -7631,6 +8995,7 @@ func (s *DeleteObjectOutput) SetVersionId(v string) *DeleteObjectOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectTaggingRequest type DeleteObjectTaggingInput struct { _ struct{} `type:"structure"` @@ -7691,6 +9056,7 @@ func (s *DeleteObjectTaggingInput) SetVersionId(v string) *DeleteObjectTaggingIn return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectTaggingOutput type DeleteObjectTaggingOutput struct { _ struct{} `type:"structure"` @@ -7714,6 +9080,7 @@ func (s *DeleteObjectTaggingOutput) SetVersionId(v string) *DeleteObjectTaggingO return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectsRequest type DeleteObjectsInput struct { _ struct{} `type:"structure" payload:"Delete"` @@ -7789,6 +9156,7 @@ func (s *DeleteObjectsInput) SetRequestPayer(v string) *DeleteObjectsInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectsOutput type DeleteObjectsOutput struct { _ struct{} `type:"structure"` @@ -7829,6 +9197,7 @@ func (s *DeleteObjectsOutput) SetRequestCharged(v string) *DeleteObjectsOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeletedObject type DeletedObject struct { _ struct{} `type:"structure"` @@ -7875,6 +9244,7 @@ func (s *DeletedObject) SetVersionId(v string) *DeletedObject { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Destination type Destination struct { _ struct{} `type:"structure"` @@ -7923,6 +9293,7 @@ func (s *Destination) SetStorageClass(v string) *Destination { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Error type Error struct { _ struct{} `type:"structure"` @@ -7969,6 +9340,7 @@ func (s *Error) SetVersionId(v string) *Error { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ErrorDocument type ErrorDocument struct { _ struct{} `type:"structure"` @@ -8011,6 +9383,7 @@ func (s *ErrorDocument) SetKey(v string) *ErrorDocument { } // Container for key value pair that defines the criteria for the filter rule. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/FilterRule type FilterRule struct { _ struct{} `type:"structure"` @@ -8045,6 +9418,7 @@ func (s *FilterRule) SetValue(v string) *FilterRule { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAccelerateConfigurationRequest type GetBucketAccelerateConfigurationInput struct { _ struct{} `type:"structure"` @@ -8083,6 +9457,7 @@ func (s *GetBucketAccelerateConfigurationInput) SetBucket(v string) *GetBucketAc return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAccelerateConfigurationOutput type GetBucketAccelerateConfigurationOutput struct { _ struct{} `type:"structure"` @@ -8106,6 +9481,7 @@ func (s *GetBucketAccelerateConfigurationOutput) SetStatus(v string) *GetBucketA return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAclRequest type GetBucketAclInput struct { _ struct{} `type:"structure"` @@ -8142,6 +9518,7 @@ func (s *GetBucketAclInput) SetBucket(v string) *GetBucketAclInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAclOutput type GetBucketAclOutput struct { _ struct{} `type:"structure"` @@ -8173,6 +9550,7 @@ func (s *GetBucketAclOutput) SetOwner(v *Owner) *GetBucketAclOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAnalyticsConfigurationRequest type GetBucketAnalyticsConfigurationInput struct { _ struct{} `type:"structure"` @@ -8225,6 +9603,7 @@ func (s *GetBucketAnalyticsConfigurationInput) SetId(v string) *GetBucketAnalyti return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAnalyticsConfigurationOutput type GetBucketAnalyticsConfigurationOutput struct { _ struct{} `type:"structure" payload:"AnalyticsConfiguration"` @@ -8248,6 +9627,7 @@ func (s *GetBucketAnalyticsConfigurationOutput) SetAnalyticsConfiguration(v *Ana return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketCorsRequest type GetBucketCorsInput struct { _ struct{} `type:"structure"` @@ -8284,6 +9664,7 @@ func (s *GetBucketCorsInput) SetBucket(v string) *GetBucketCorsInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketCorsOutput type GetBucketCorsOutput struct { _ struct{} `type:"structure"` @@ -8306,6 +9687,7 @@ func (s *GetBucketCorsOutput) SetCORSRules(v []*CORSRule) *GetBucketCorsOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketInventoryConfigurationRequest type GetBucketInventoryConfigurationInput struct { _ struct{} `type:"structure"` @@ -8358,6 +9740,7 @@ func (s *GetBucketInventoryConfigurationInput) SetId(v string) *GetBucketInvento return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketInventoryConfigurationOutput type GetBucketInventoryConfigurationOutput struct { _ struct{} `type:"structure" payload:"InventoryConfiguration"` @@ -8381,6 +9764,7 @@ func (s *GetBucketInventoryConfigurationOutput) SetInventoryConfiguration(v *Inv return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleConfigurationRequest type GetBucketLifecycleConfigurationInput struct { _ struct{} `type:"structure"` @@ -8417,6 +9801,7 @@ func (s *GetBucketLifecycleConfigurationInput) SetBucket(v string) *GetBucketLif return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleConfigurationOutput type GetBucketLifecycleConfigurationOutput struct { _ struct{} `type:"structure"` @@ -8439,6 +9824,7 @@ func (s *GetBucketLifecycleConfigurationOutput) SetRules(v []*LifecycleRule) *Ge return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleRequest type GetBucketLifecycleInput struct { _ struct{} `type:"structure"` @@ -8475,6 +9861,7 @@ func (s *GetBucketLifecycleInput) SetBucket(v string) *GetBucketLifecycleInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleOutput type GetBucketLifecycleOutput struct { _ struct{} `type:"structure"` @@ -8497,6 +9884,7 @@ func (s *GetBucketLifecycleOutput) SetRules(v []*Rule) *GetBucketLifecycleOutput return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLocationRequest type GetBucketLocationInput struct { _ struct{} `type:"structure"` @@ -8533,6 +9921,7 @@ func (s *GetBucketLocationInput) SetBucket(v string) *GetBucketLocationInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLocationOutput type GetBucketLocationOutput struct { _ struct{} `type:"structure"` @@ -8555,6 +9944,7 @@ func (s *GetBucketLocationOutput) SetLocationConstraint(v string) *GetBucketLoca return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLoggingRequest type GetBucketLoggingInput struct { _ struct{} `type:"structure"` @@ -8591,6 +9981,7 @@ func (s *GetBucketLoggingInput) SetBucket(v string) *GetBucketLoggingInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLoggingOutput type GetBucketLoggingOutput struct { _ struct{} `type:"structure"` @@ -8613,6 +10004,7 @@ func (s *GetBucketLoggingOutput) SetLoggingEnabled(v *LoggingEnabled) *GetBucket return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketMetricsConfigurationRequest type GetBucketMetricsConfigurationInput struct { _ struct{} `type:"structure"` @@ -8665,6 +10057,7 @@ func (s *GetBucketMetricsConfigurationInput) SetId(v string) *GetBucketMetricsCo return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketMetricsConfigurationOutput type GetBucketMetricsConfigurationOutput struct { _ struct{} `type:"structure" payload:"MetricsConfiguration"` @@ -8688,6 +10081,7 @@ func (s *GetBucketMetricsConfigurationOutput) SetMetricsConfiguration(v *Metrics return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotificationConfigurationRequest type GetBucketNotificationConfigurationRequest struct { _ struct{} `type:"structure"` @@ -8726,6 +10120,7 @@ func (s *GetBucketNotificationConfigurationRequest) SetBucket(v string) *GetBuck return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicyRequest type GetBucketPolicyInput struct { _ struct{} `type:"structure"` @@ -8762,6 +10157,7 @@ func (s *GetBucketPolicyInput) SetBucket(v string) *GetBucketPolicyInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicyOutput type GetBucketPolicyOutput struct { _ struct{} `type:"structure" payload:"Policy"` @@ -8785,6 +10181,7 @@ func (s *GetBucketPolicyOutput) SetPolicy(v string) *GetBucketPolicyOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketReplicationRequest type GetBucketReplicationInput struct { _ struct{} `type:"structure"` @@ -8821,6 +10218,7 @@ func (s *GetBucketReplicationInput) SetBucket(v string) *GetBucketReplicationInp return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketReplicationOutput type GetBucketReplicationOutput struct { _ struct{} `type:"structure" payload:"ReplicationConfiguration"` @@ -8845,6 +10243,7 @@ func (s *GetBucketReplicationOutput) SetReplicationConfiguration(v *ReplicationC return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketRequestPaymentRequest type GetBucketRequestPaymentInput struct { _ struct{} `type:"structure"` @@ -8881,6 +10280,7 @@ func (s *GetBucketRequestPaymentInput) SetBucket(v string) *GetBucketRequestPaym return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketRequestPaymentOutput type GetBucketRequestPaymentOutput struct { _ struct{} `type:"structure"` @@ -8904,6 +10304,7 @@ func (s *GetBucketRequestPaymentOutput) SetPayer(v string) *GetBucketRequestPaym return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketTaggingRequest type GetBucketTaggingInput struct { _ struct{} `type:"structure"` @@ -8940,6 +10341,7 @@ func (s *GetBucketTaggingInput) SetBucket(v string) *GetBucketTaggingInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketTaggingOutput type GetBucketTaggingOutput struct { _ struct{} `type:"structure"` @@ -8963,6 +10365,7 @@ func (s *GetBucketTaggingOutput) SetTagSet(v []*Tag) *GetBucketTaggingOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketVersioningRequest type GetBucketVersioningInput struct { _ struct{} `type:"structure"` @@ -8999,6 +10402,7 @@ func (s *GetBucketVersioningInput) SetBucket(v string) *GetBucketVersioningInput return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketVersioningOutput type GetBucketVersioningOutput struct { _ struct{} `type:"structure"` @@ -9033,6 +10437,7 @@ func (s *GetBucketVersioningOutput) SetStatus(v string) *GetBucketVersioningOutp return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketWebsiteRequest type GetBucketWebsiteInput struct { _ struct{} `type:"structure"` @@ -9069,6 +10474,7 @@ func (s *GetBucketWebsiteInput) SetBucket(v string) *GetBucketWebsiteInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketWebsiteOutput type GetBucketWebsiteOutput struct { _ struct{} `type:"structure"` @@ -9115,6 +10521,7 @@ func (s *GetBucketWebsiteOutput) SetRoutingRules(v []*RoutingRule) *GetBucketWeb return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectAclRequest type GetObjectAclInput struct { _ struct{} `type:"structure"` @@ -9187,6 +10594,7 @@ func (s *GetObjectAclInput) SetVersionId(v string) *GetObjectAclInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectAclOutput type GetObjectAclOutput struct { _ struct{} `type:"structure"` @@ -9228,6 +10636,7 @@ func (s *GetObjectAclOutput) SetRequestCharged(v string) *GetObjectAclOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectRequest type GetObjectInput struct { _ struct{} `type:"structure"` @@ -9448,6 +10857,7 @@ func (s *GetObjectInput) SetVersionId(v string) *GetObjectInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectOutput type GetObjectOutput struct { _ struct{} `type:"structure" payload:"Body"` @@ -9731,6 +11141,7 @@ func (s *GetObjectOutput) SetWebsiteRedirectLocation(v string) *GetObjectOutput return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTaggingRequest type GetObjectTaggingInput struct { _ struct{} `type:"structure"` @@ -9790,6 +11201,7 @@ func (s *GetObjectTaggingInput) SetVersionId(v string) *GetObjectTaggingInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTaggingOutput type GetObjectTaggingOutput struct { _ struct{} `type:"structure"` @@ -9821,6 +11233,7 @@ func (s *GetObjectTaggingOutput) SetVersionId(v string) *GetObjectTaggingOutput return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTorrentRequest type GetObjectTorrentInput struct { _ struct{} `type:"structure"` @@ -9884,6 +11297,7 @@ func (s *GetObjectTorrentInput) SetRequestPayer(v string) *GetObjectTorrentInput return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTorrentOutput type GetObjectTorrentOutput struct { _ struct{} `type:"structure" payload:"Body"` @@ -9916,6 +11330,7 @@ func (s *GetObjectTorrentOutput) SetRequestCharged(v string) *GetObjectTorrentOu return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GlacierJobParameters type GlacierJobParameters struct { _ struct{} `type:"structure"` @@ -9954,6 +11369,7 @@ func (s *GlacierJobParameters) SetTier(v string) *GlacierJobParameters { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Grant type Grant struct { _ struct{} `type:"structure"` @@ -10000,6 +11416,7 @@ func (s *Grant) SetPermission(v string) *Grant { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Grantee type Grantee struct { _ struct{} `type:"structure" xmlPrefix:"xsi" xmlURI:"http://www.w3.org/2001/XMLSchema-instance"` @@ -10074,6 +11491,7 @@ func (s *Grantee) SetURI(v string) *Grantee { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadBucketRequest type HeadBucketInput struct { _ struct{} `type:"structure"` @@ -10110,6 +11528,7 @@ func (s *HeadBucketInput) SetBucket(v string) *HeadBucketInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadBucketOutput type HeadBucketOutput struct { _ struct{} `type:"structure"` } @@ -10124,6 +11543,7 @@ func (s HeadBucketOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadObjectRequest type HeadObjectInput struct { _ struct{} `type:"structure"` @@ -10291,6 +11711,7 @@ func (s *HeadObjectInput) SetVersionId(v string) *HeadObjectInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadObjectOutput type HeadObjectOutput struct { _ struct{} `type:"structure"` @@ -10547,6 +11968,7 @@ func (s *HeadObjectOutput) SetWebsiteRedirectLocation(v string) *HeadObjectOutpu return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/IndexDocument type IndexDocument struct { _ struct{} `type:"structure"` @@ -10588,6 +12010,7 @@ func (s *IndexDocument) SetSuffix(v string) *IndexDocument { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Initiator type Initiator struct { _ struct{} `type:"structure"` @@ -10621,6 +12044,7 @@ func (s *Initiator) SetID(v string) *Initiator { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/InventoryConfiguration type InventoryConfiguration struct { _ struct{} `type:"structure"` @@ -10749,6 +12173,7 @@ func (s *InventoryConfiguration) SetSchedule(v *InventorySchedule) *InventoryCon return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/InventoryDestination type InventoryDestination struct { _ struct{} `type:"structure"` @@ -10793,6 +12218,7 @@ func (s *InventoryDestination) SetS3BucketDestination(v *InventoryS3BucketDestin return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/InventoryFilter type InventoryFilter struct { _ struct{} `type:"structure"` @@ -10831,6 +12257,7 @@ func (s *InventoryFilter) SetPrefix(v string) *InventoryFilter { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/InventoryS3BucketDestination type InventoryS3BucketDestination struct { _ struct{} `type:"structure"` @@ -10902,6 +12329,7 @@ func (s *InventoryS3BucketDestination) SetPrefix(v string) *InventoryS3BucketDes return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/InventorySchedule type InventorySchedule struct { _ struct{} `type:"structure"` @@ -10941,6 +12369,7 @@ func (s *InventorySchedule) SetFrequency(v string) *InventorySchedule { } // Container for object key name prefix and suffix filtering rules. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/S3KeyFilter type KeyFilter struct { _ struct{} `type:"structure"` @@ -10966,6 +12395,7 @@ func (s *KeyFilter) SetFilterRules(v []*FilterRule) *KeyFilter { } // Container for specifying the AWS Lambda notification configuration. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LambdaFunctionConfiguration type LambdaFunctionConfiguration struct { _ struct{} `type:"structure"` @@ -11037,6 +12467,7 @@ func (s *LambdaFunctionConfiguration) SetLambdaFunctionArn(v string) *LambdaFunc return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LifecycleConfiguration type LifecycleConfiguration struct { _ struct{} `type:"structure"` @@ -11083,6 +12514,7 @@ func (s *LifecycleConfiguration) SetRules(v []*Rule) *LifecycleConfiguration { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LifecycleExpiration type LifecycleExpiration struct { _ struct{} `type:"structure"` @@ -11129,6 +12561,7 @@ func (s *LifecycleExpiration) SetExpiredObjectDeleteMarker(v bool) *LifecycleExp return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LifecycleRule type LifecycleRule struct { _ struct{} `type:"structure"` @@ -11252,6 +12685,7 @@ func (s *LifecycleRule) SetTransitions(v []*Transition) *LifecycleRule { // This is used in a Lifecycle Rule Filter to apply a logical AND to two or // more predicates. The Lifecycle Rule will apply to any object matching all // of the predicates configured inside the And operator. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LifecycleRuleAndOperator type LifecycleRuleAndOperator struct { _ struct{} `type:"structure"` @@ -11306,6 +12740,7 @@ func (s *LifecycleRuleAndOperator) SetTags(v []*Tag) *LifecycleRuleAndOperator { // The Filter is used to identify objects that a Lifecycle Rule applies to. // A Filter must have exactly one of Prefix, Tag, or And specified. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LifecycleRuleFilter type LifecycleRuleFilter struct { _ struct{} `type:"structure"` @@ -11369,6 +12804,7 @@ func (s *LifecycleRuleFilter) SetTag(v *Tag) *LifecycleRuleFilter { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketAnalyticsConfigurationsRequest type ListBucketAnalyticsConfigurationsInput struct { _ struct{} `type:"structure"` @@ -11417,6 +12853,7 @@ func (s *ListBucketAnalyticsConfigurationsInput) SetContinuationToken(v string) return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketAnalyticsConfigurationsOutput type ListBucketAnalyticsConfigurationsOutput struct { _ struct{} `type:"structure"` @@ -11471,6 +12908,7 @@ func (s *ListBucketAnalyticsConfigurationsOutput) SetNextContinuationToken(v str return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketInventoryConfigurationsRequest type ListBucketInventoryConfigurationsInput struct { _ struct{} `type:"structure"` @@ -11521,6 +12959,7 @@ func (s *ListBucketInventoryConfigurationsInput) SetContinuationToken(v string) return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketInventoryConfigurationsOutput type ListBucketInventoryConfigurationsOutput struct { _ struct{} `type:"structure"` @@ -11575,6 +13014,7 @@ func (s *ListBucketInventoryConfigurationsOutput) SetNextContinuationToken(v str return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketMetricsConfigurationsRequest type ListBucketMetricsConfigurationsInput struct { _ struct{} `type:"structure"` @@ -11625,6 +13065,7 @@ func (s *ListBucketMetricsConfigurationsInput) SetContinuationToken(v string) *L return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketMetricsConfigurationsOutput type ListBucketMetricsConfigurationsOutput struct { _ struct{} `type:"structure"` @@ -11681,6 +13122,7 @@ func (s *ListBucketMetricsConfigurationsOutput) SetNextContinuationToken(v strin return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketsInput type ListBucketsInput struct { _ struct{} `type:"structure"` } @@ -11695,6 +13137,7 @@ func (s ListBucketsInput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketsOutput type ListBucketsOutput struct { _ struct{} `type:"structure"` @@ -11725,6 +13168,7 @@ func (s *ListBucketsOutput) SetOwner(v *Owner) *ListBucketsOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListMultipartUploadsRequest type ListMultipartUploadsInput struct { _ struct{} `type:"structure"` @@ -11826,6 +13270,7 @@ func (s *ListMultipartUploadsInput) SetUploadIdMarker(v string) *ListMultipartUp return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListMultipartUploadsOutput type ListMultipartUploadsOutput struct { _ struct{} `type:"structure"` @@ -11952,6 +13397,7 @@ func (s *ListMultipartUploadsOutput) SetUploads(v []*MultipartUpload) *ListMulti return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectVersionsRequest type ListObjectVersionsInput struct { _ struct{} `type:"structure"` @@ -12048,6 +13494,7 @@ func (s *ListObjectVersionsInput) SetVersionIdMarker(v string) *ListObjectVersio return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectVersionsOutput type ListObjectVersionsOutput struct { _ struct{} `type:"structure"` @@ -12175,6 +13622,7 @@ func (s *ListObjectVersionsOutput) SetVersions(v []*ObjectVersion) *ListObjectVe return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsRequest type ListObjectsInput struct { _ struct{} `type:"structure"` @@ -12273,6 +13721,7 @@ func (s *ListObjectsInput) SetRequestPayer(v string) *ListObjectsInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsOutput type ListObjectsOutput struct { _ struct{} `type:"structure"` @@ -12377,6 +13826,7 @@ func (s *ListObjectsOutput) SetPrefix(v string) *ListObjectsOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsV2Request type ListObjectsV2Input struct { _ struct{} `type:"structure"` @@ -12495,6 +13945,7 @@ func (s *ListObjectsV2Input) SetStartAfter(v string) *ListObjectsV2Input { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsV2Output type ListObjectsV2Output struct { _ struct{} `type:"structure"` @@ -12628,6 +14079,7 @@ func (s *ListObjectsV2Output) SetStartAfter(v string) *ListObjectsV2Output { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListPartsRequest type ListPartsInput struct { _ struct{} `type:"structure"` @@ -12724,6 +14176,7 @@ func (s *ListPartsInput) SetUploadId(v string) *ListPartsInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListPartsOutput type ListPartsOutput struct { _ struct{} `type:"structure"` @@ -12866,6 +14319,7 @@ func (s *ListPartsOutput) SetUploadId(v string) *ListPartsOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LoggingEnabled type LoggingEnabled struct { _ struct{} `type:"structure"` @@ -12932,6 +14386,7 @@ func (s *LoggingEnabled) SetTargetPrefix(v string) *LoggingEnabled { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/MetricsAndOperator type MetricsAndOperator struct { _ struct{} `type:"structure"` @@ -12984,6 +14439,7 @@ func (s *MetricsAndOperator) SetTags(v []*Tag) *MetricsAndOperator { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/MetricsConfiguration type MetricsConfiguration struct { _ struct{} `type:"structure"` @@ -13038,6 +14494,7 @@ func (s *MetricsConfiguration) SetId(v string) *MetricsConfiguration { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/MetricsFilter type MetricsFilter struct { _ struct{} `type:"structure"` @@ -13101,6 +14558,7 @@ func (s *MetricsFilter) SetTag(v *Tag) *MetricsFilter { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/MultipartUpload type MultipartUpload struct { _ struct{} `type:"structure"` @@ -13173,6 +14631,7 @@ func (s *MultipartUpload) SetUploadId(v string) *MultipartUpload { // configuration action on a bucket that has versioning enabled (or suspended) // to request that Amazon S3 delete noncurrent object versions at a specific // period in the object's lifetime. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/NoncurrentVersionExpiration type NoncurrentVersionExpiration struct { _ struct{} `type:"structure"` @@ -13204,6 +14663,7 @@ func (s *NoncurrentVersionExpiration) SetNoncurrentDays(v int64) *NoncurrentVers // versioning-enabled (or versioning is suspended), you can set this action // to request that Amazon S3 transition noncurrent object versions to the STANDARD_IA // or GLACIER storage class at a specific period in the object's lifetime. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/NoncurrentVersionTransition type NoncurrentVersionTransition struct { _ struct{} `type:"structure"` @@ -13241,6 +14701,7 @@ func (s *NoncurrentVersionTransition) SetStorageClass(v string) *NoncurrentVersi // Container for specifying the notification configuration of the bucket. If // this element is empty, notifications are turned off on the bucket. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/NotificationConfiguration type NotificationConfiguration struct { _ struct{} `type:"structure"` @@ -13319,6 +14780,7 @@ func (s *NotificationConfiguration) SetTopicConfigurations(v []*TopicConfigurati return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/NotificationConfigurationDeprecated type NotificationConfigurationDeprecated struct { _ struct{} `type:"structure"` @@ -13359,6 +14821,7 @@ func (s *NotificationConfigurationDeprecated) SetTopicConfiguration(v *TopicConf // Container for object key name filtering rules. For information about key // name filtering, go to Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/NotificationConfigurationFilter type NotificationConfigurationFilter struct { _ struct{} `type:"structure"` @@ -13382,6 +14845,7 @@ func (s *NotificationConfigurationFilter) SetKey(v *KeyFilter) *NotificationConf return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Object type Object struct { _ struct{} `type:"structure"` @@ -13445,6 +14909,7 @@ func (s *Object) SetStorageClass(v string) *Object { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ObjectIdentifier type ObjectIdentifier struct { _ struct{} `type:"structure"` @@ -13495,6 +14960,7 @@ func (s *ObjectIdentifier) SetVersionId(v string) *ObjectIdentifier { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ObjectVersion type ObjectVersion struct { _ struct{} `type:"structure"` @@ -13580,6 +15046,7 @@ func (s *ObjectVersion) SetVersionId(v string) *ObjectVersion { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Owner type Owner struct { _ struct{} `type:"structure"` @@ -13610,6 +15077,7 @@ func (s *Owner) SetID(v string) *Owner { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Part type Part struct { _ struct{} `type:"structure"` @@ -13661,6 +15129,7 @@ func (s *Part) SetSize(v int64) *Part { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAccelerateConfigurationRequest type PutBucketAccelerateConfigurationInput struct { _ struct{} `type:"structure" payload:"AccelerateConfiguration"` @@ -13713,6 +15182,7 @@ func (s *PutBucketAccelerateConfigurationInput) SetBucket(v string) *PutBucketAc return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAccelerateConfigurationOutput type PutBucketAccelerateConfigurationOutput struct { _ struct{} `type:"structure"` } @@ -13727,6 +15197,7 @@ func (s PutBucketAccelerateConfigurationOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAclRequest type PutBucketAclInput struct { _ struct{} `type:"structure" payload:"AccessControlPolicy"` @@ -13831,6 +15302,7 @@ func (s *PutBucketAclInput) SetGrantWriteACP(v string) *PutBucketAclInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAclOutput type PutBucketAclOutput struct { _ struct{} `type:"structure"` } @@ -13845,6 +15317,7 @@ func (s PutBucketAclOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAnalyticsConfigurationRequest type PutBucketAnalyticsConfigurationInput struct { _ struct{} `type:"structure" payload:"AnalyticsConfiguration"` @@ -13916,6 +15389,7 @@ func (s *PutBucketAnalyticsConfigurationInput) SetId(v string) *PutBucketAnalyti return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAnalyticsConfigurationOutput type PutBucketAnalyticsConfigurationOutput struct { _ struct{} `type:"structure"` } @@ -13930,6 +15404,7 @@ func (s PutBucketAnalyticsConfigurationOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketCorsRequest type PutBucketCorsInput struct { _ struct{} `type:"structure" payload:"CORSConfiguration"` @@ -13983,6 +15458,7 @@ func (s *PutBucketCorsInput) SetCORSConfiguration(v *CORSConfiguration) *PutBuck return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketCorsOutput type PutBucketCorsOutput struct { _ struct{} `type:"structure"` } @@ -13997,6 +15473,7 @@ func (s PutBucketCorsOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketInventoryConfigurationRequest type PutBucketInventoryConfigurationInput struct { _ struct{} `type:"structure" payload:"InventoryConfiguration"` @@ -14068,6 +15545,7 @@ func (s *PutBucketInventoryConfigurationInput) SetInventoryConfiguration(v *Inve return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketInventoryConfigurationOutput type PutBucketInventoryConfigurationOutput struct { _ struct{} `type:"structure"` } @@ -14082,6 +15560,7 @@ func (s PutBucketInventoryConfigurationOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleConfigurationRequest type PutBucketLifecycleConfigurationInput struct { _ struct{} `type:"structure" payload:"LifecycleConfiguration"` @@ -14131,6 +15610,7 @@ func (s *PutBucketLifecycleConfigurationInput) SetLifecycleConfiguration(v *Buck return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleConfigurationOutput type PutBucketLifecycleConfigurationOutput struct { _ struct{} `type:"structure"` } @@ -14145,6 +15625,7 @@ func (s PutBucketLifecycleConfigurationOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleRequest type PutBucketLifecycleInput struct { _ struct{} `type:"structure" payload:"LifecycleConfiguration"` @@ -14194,6 +15675,7 @@ func (s *PutBucketLifecycleInput) SetLifecycleConfiguration(v *LifecycleConfigur return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleOutput type PutBucketLifecycleOutput struct { _ struct{} `type:"structure"` } @@ -14208,6 +15690,7 @@ func (s PutBucketLifecycleOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLoggingRequest type PutBucketLoggingInput struct { _ struct{} `type:"structure" payload:"BucketLoggingStatus"` @@ -14261,6 +15744,7 @@ func (s *PutBucketLoggingInput) SetBucketLoggingStatus(v *BucketLoggingStatus) * return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLoggingOutput type PutBucketLoggingOutput struct { _ struct{} `type:"structure"` } @@ -14275,6 +15759,7 @@ func (s PutBucketLoggingOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketMetricsConfigurationRequest type PutBucketMetricsConfigurationInput struct { _ struct{} `type:"structure" payload:"MetricsConfiguration"` @@ -14346,6 +15831,7 @@ func (s *PutBucketMetricsConfigurationInput) SetMetricsConfiguration(v *MetricsC return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketMetricsConfigurationOutput type PutBucketMetricsConfigurationOutput struct { _ struct{} `type:"structure"` } @@ -14360,6 +15846,7 @@ func (s PutBucketMetricsConfigurationOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationConfigurationRequest type PutBucketNotificationConfigurationInput struct { _ struct{} `type:"structure" payload:"NotificationConfiguration"` @@ -14416,6 +15903,7 @@ func (s *PutBucketNotificationConfigurationInput) SetNotificationConfiguration(v return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationConfigurationOutput type PutBucketNotificationConfigurationOutput struct { _ struct{} `type:"structure"` } @@ -14430,6 +15918,7 @@ func (s PutBucketNotificationConfigurationOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationRequest type PutBucketNotificationInput struct { _ struct{} `type:"structure" payload:"NotificationConfiguration"` @@ -14478,6 +15967,7 @@ func (s *PutBucketNotificationInput) SetNotificationConfiguration(v *Notificatio return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationOutput type PutBucketNotificationOutput struct { _ struct{} `type:"structure"` } @@ -14492,6 +15982,7 @@ func (s PutBucketNotificationOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketPolicyRequest type PutBucketPolicyInput struct { _ struct{} `type:"structure" payload:"Policy"` @@ -14542,6 +16033,7 @@ func (s *PutBucketPolicyInput) SetPolicy(v string) *PutBucketPolicyInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketPolicyOutput type PutBucketPolicyOutput struct { _ struct{} `type:"structure"` } @@ -14556,6 +16048,7 @@ func (s PutBucketPolicyOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketReplicationRequest type PutBucketReplicationInput struct { _ struct{} `type:"structure" payload:"ReplicationConfiguration"` @@ -14612,6 +16105,7 @@ func (s *PutBucketReplicationInput) SetReplicationConfiguration(v *ReplicationCo return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketReplicationOutput type PutBucketReplicationOutput struct { _ struct{} `type:"structure"` } @@ -14626,6 +16120,7 @@ func (s PutBucketReplicationOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketRequestPaymentRequest type PutBucketRequestPaymentInput struct { _ struct{} `type:"structure" payload:"RequestPaymentConfiguration"` @@ -14679,6 +16174,7 @@ func (s *PutBucketRequestPaymentInput) SetRequestPaymentConfiguration(v *Request return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketRequestPaymentOutput type PutBucketRequestPaymentOutput struct { _ struct{} `type:"structure"` } @@ -14693,6 +16189,7 @@ func (s PutBucketRequestPaymentOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketTaggingRequest type PutBucketTaggingInput struct { _ struct{} `type:"structure" payload:"Tagging"` @@ -14746,6 +16243,7 @@ func (s *PutBucketTaggingInput) SetTagging(v *Tagging) *PutBucketTaggingInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketTaggingOutput type PutBucketTaggingOutput struct { _ struct{} `type:"structure"` } @@ -14760,6 +16258,7 @@ func (s PutBucketTaggingOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketVersioningRequest type PutBucketVersioningInput struct { _ struct{} `type:"structure" payload:"VersioningConfiguration"` @@ -14818,6 +16317,7 @@ func (s *PutBucketVersioningInput) SetVersioningConfiguration(v *VersioningConfi return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketVersioningOutput type PutBucketVersioningOutput struct { _ struct{} `type:"structure"` } @@ -14832,6 +16332,7 @@ func (s PutBucketVersioningOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketWebsiteRequest type PutBucketWebsiteInput struct { _ struct{} `type:"structure" payload:"WebsiteConfiguration"` @@ -14885,6 +16386,7 @@ func (s *PutBucketWebsiteInput) SetWebsiteConfiguration(v *WebsiteConfiguration) return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketWebsiteOutput type PutBucketWebsiteOutput struct { _ struct{} `type:"structure"` } @@ -14899,6 +16401,7 @@ func (s PutBucketWebsiteOutput) GoString() string { return s.String() } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectAclRequest type PutObjectAclInput struct { _ struct{} `type:"structure" payload:"AccessControlPolicy"` @@ -15039,6 +16542,7 @@ func (s *PutObjectAclInput) SetVersionId(v string) *PutObjectAclInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectAclOutput type PutObjectAclOutput struct { _ struct{} `type:"structure"` @@ -15063,6 +16567,7 @@ func (s *PutObjectAclOutput) SetRequestCharged(v string) *PutObjectAclOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectRequest type PutObjectInput struct { _ struct{} `type:"structure" payload:"Body"` @@ -15343,6 +16848,7 @@ func (s *PutObjectInput) SetWebsiteRedirectLocation(v string) *PutObjectInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectOutput type PutObjectOutput struct { _ struct{} `type:"structure"` @@ -15437,6 +16943,7 @@ func (s *PutObjectOutput) SetVersionId(v string) *PutObjectOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectTaggingRequest type PutObjectTaggingInput struct { _ struct{} `type:"structure" payload:"Tagging"` @@ -15513,6 +17020,7 @@ func (s *PutObjectTaggingInput) SetVersionId(v string) *PutObjectTaggingInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectTaggingOutput type PutObjectTaggingOutput struct { _ struct{} `type:"structure"` @@ -15537,6 +17045,7 @@ func (s *PutObjectTaggingOutput) SetVersionId(v string) *PutObjectTaggingOutput // Container for specifying an configuration when you want Amazon S3 to publish // events to an Amazon Simple Queue Service (Amazon SQS) queue. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/QueueConfiguration type QueueConfiguration struct { _ struct{} `type:"structure"` @@ -15608,6 +17117,7 @@ func (s *QueueConfiguration) SetQueueArn(v string) *QueueConfiguration { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/QueueConfigurationDeprecated type QueueConfigurationDeprecated struct { _ struct{} `type:"structure"` @@ -15657,6 +17167,7 @@ func (s *QueueConfigurationDeprecated) SetQueue(v string) *QueueConfigurationDep return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Redirect type Redirect struct { _ struct{} `type:"structure"` @@ -15725,6 +17236,7 @@ func (s *Redirect) SetReplaceKeyWith(v string) *Redirect { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RedirectAllRequestsTo type RedirectAllRequestsTo struct { _ struct{} `type:"structure"` @@ -15775,6 +17287,7 @@ func (s *RedirectAllRequestsTo) SetProtocol(v string) *RedirectAllRequestsTo { // Container for replication rules. You can add as many as 1,000 rules. Total // replication configuration size can be up to 2 MB. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ReplicationConfiguration type ReplicationConfiguration struct { _ struct{} `type:"structure"` @@ -15839,6 +17352,7 @@ func (s *ReplicationConfiguration) SetRules(v []*ReplicationRule) *ReplicationCo return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ReplicationRule type ReplicationRule struct { _ struct{} `type:"structure"` @@ -15919,6 +17433,7 @@ func (s *ReplicationRule) SetStatus(v string) *ReplicationRule { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RequestPaymentConfiguration type RequestPaymentConfiguration struct { _ struct{} `type:"structure"` @@ -15957,6 +17472,7 @@ func (s *RequestPaymentConfiguration) SetPayer(v string) *RequestPaymentConfigur return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreObjectRequest type RestoreObjectInput struct { _ struct{} `type:"structure" payload:"RestoreRequest"` @@ -16041,6 +17557,7 @@ func (s *RestoreObjectInput) SetVersionId(v string) *RestoreObjectInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreObjectOutput type RestoreObjectOutput struct { _ struct{} `type:"structure"` @@ -16065,6 +17582,7 @@ func (s *RestoreObjectOutput) SetRequestCharged(v string) *RestoreObjectOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreRequest type RestoreRequest struct { _ struct{} `type:"structure"` @@ -16117,6 +17635,7 @@ func (s *RestoreRequest) SetGlacierJobParameters(v *GlacierJobParameters) *Resto return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RoutingRule type RoutingRule struct { _ struct{} `type:"structure"` @@ -16169,6 +17688,7 @@ func (s *RoutingRule) SetRedirect(v *Redirect) *RoutingRule { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Rule type Rule struct { _ struct{} `type:"structure"` @@ -16283,6 +17803,7 @@ func (s *Rule) SetTransition(v *Transition) *Rule { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/StorageClassAnalysis type StorageClassAnalysis struct { _ struct{} `type:"structure"` @@ -16322,6 +17843,7 @@ func (s *StorageClassAnalysis) SetDataExport(v *StorageClassAnalysisDataExport) return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/StorageClassAnalysisDataExport type StorageClassAnalysisDataExport struct { _ struct{} `type:"structure"` @@ -16379,6 +17901,7 @@ func (s *StorageClassAnalysisDataExport) SetOutputSchemaVersion(v string) *Stora return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Tag type Tag struct { _ struct{} `type:"structure"` @@ -16434,6 +17957,7 @@ func (s *Tag) SetValue(v string) *Tag { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Tagging type Tagging struct { _ struct{} `type:"structure"` @@ -16480,6 +18004,7 @@ func (s *Tagging) SetTagSet(v []*Tag) *Tagging { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/TargetGrant type TargetGrant struct { _ struct{} `type:"structure"` @@ -16528,6 +18053,7 @@ func (s *TargetGrant) SetPermission(v string) *TargetGrant { // Container for specifying the configuration when you want Amazon S3 to publish // events to an Amazon Simple Notification Service (Amazon SNS) topic. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/TopicConfiguration type TopicConfiguration struct { _ struct{} `type:"structure"` @@ -16599,6 +18125,7 @@ func (s *TopicConfiguration) SetTopicArn(v string) *TopicConfiguration { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/TopicConfigurationDeprecated type TopicConfigurationDeprecated struct { _ struct{} `type:"structure"` @@ -16650,6 +18177,7 @@ func (s *TopicConfigurationDeprecated) SetTopic(v string) *TopicConfigurationDep return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Transition type Transition struct { _ struct{} `type:"structure"` @@ -16693,6 +18221,7 @@ func (s *Transition) SetStorageClass(v string) *Transition { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartCopyRequest type UploadPartCopyInput struct { _ struct{} `type:"structure"` @@ -16915,6 +18444,7 @@ func (s *UploadPartCopyInput) SetUploadId(v string) *UploadPartCopyInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartCopyOutput type UploadPartCopyOutput struct { _ struct{} `type:"structure" payload:"CopyPartResult"` @@ -16999,6 +18529,7 @@ func (s *UploadPartCopyOutput) SetServerSideEncryption(v string) *UploadPartCopy return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartRequest type UploadPartInput struct { _ struct{} `type:"structure" payload:"Body"` @@ -17148,6 +18679,7 @@ func (s *UploadPartInput) SetUploadId(v string) *UploadPartInput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartOutput type UploadPartOutput struct { _ struct{} `type:"structure"` @@ -17223,6 +18755,7 @@ func (s *UploadPartOutput) SetServerSideEncryption(v string) *UploadPartOutput { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/VersioningConfiguration type VersioningConfiguration struct { _ struct{} `type:"structure"` @@ -17257,6 +18790,7 @@ func (s *VersioningConfiguration) SetStatus(v string) *VersioningConfiguration { return s } +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/WebsiteConfiguration type WebsiteConfiguration struct { _ struct{} `type:"structure"` diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/errors.go b/vendor/github.com/aws/aws-sdk-go/service/s3/errors.go new file mode 100644 index 0000000..931cb17 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/errors.go @@ -0,0 +1,48 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package s3 + +const ( + + // ErrCodeBucketAlreadyExists for service response error code + // "BucketAlreadyExists". + // + // The requested bucket name is not available. The bucket namespace is shared + // by all users of the system. Please select a different name and try again. + ErrCodeBucketAlreadyExists = "BucketAlreadyExists" + + // ErrCodeBucketAlreadyOwnedByYou for service response error code + // "BucketAlreadyOwnedByYou". + ErrCodeBucketAlreadyOwnedByYou = "BucketAlreadyOwnedByYou" + + // ErrCodeNoSuchBucket for service response error code + // "NoSuchBucket". + // + // The specified bucket does not exist. + ErrCodeNoSuchBucket = "NoSuchBucket" + + // ErrCodeNoSuchKey for service response error code + // "NoSuchKey". + // + // The specified key does not exist. + ErrCodeNoSuchKey = "NoSuchKey" + + // ErrCodeNoSuchUpload for service response error code + // "NoSuchUpload". + // + // The specified multipart upload does not exist. + ErrCodeNoSuchUpload = "NoSuchUpload" + + // ErrCodeObjectAlreadyInActiveTierError for service response error code + // "ObjectAlreadyInActiveTierError". + // + // This operation is not allowed against this storage tier + ErrCodeObjectAlreadyInActiveTierError = "ObjectAlreadyInActiveTierError" + + // ErrCodeObjectNotInActiveTierError for service response error code + // "ObjectNotInActiveTierError". + // + // The source object of the COPY operation is not in the active tier and is + // only stored in Amazon Glacier. + ErrCodeObjectNotInActiveTierError = "ObjectNotInActiveTierError" +) diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/service.go b/vendor/github.com/aws/aws-sdk-go/service/s3/service.go index fe9347c..3fb5b3b 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package s3 @@ -12,8 +12,9 @@ import ( ) // S3 is a client for Amazon S3. -//The service client's operations are safe to be used concurrently. +// The service client's operations are safe to be used concurrently. // It is not safe to mutate any of the client's properties though. +// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01 type S3 struct { *client.Client } @@ -24,8 +25,11 @@ var initClient func(*client.Client) // Used for custom request initialization logic var initRequest func(*request.Request) -// A ServiceName is the name of the service the client will make API calls to. -const ServiceName = "s3" +// Service information constants +const ( + ServiceName = "s3" // Service endpoint prefix API calls made to. + EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. +) // New creates a new instance of the S3 client with a session. // If additional configuration is needed for the client instance use the optional @@ -38,7 +42,7 @@ const ServiceName = "s3" // // Create a S3 client with additional configuration // svc := s3.New(mySession, aws.NewConfig().WithRegion("us-west-2")) func New(p client.ConfigProvider, cfgs ...*aws.Config) *S3 { - c := p.ClientConfig(ServiceName, cfgs...) + c := p.ClientConfig(EndpointsID, cfgs...) return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go b/vendor/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go index ed91c58..bcca862 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go @@ -23,17 +23,22 @@ func unmarshalError(r *request.Request) { defer r.HTTPResponse.Body.Close() defer io.Copy(ioutil.Discard, r.HTTPResponse.Body) + hostID := r.HTTPResponse.Header.Get("X-Amz-Id-2") + // Bucket exists in a different region, and request needs // to be made to the correct region. if r.HTTPResponse.StatusCode == http.StatusMovedPermanently { - r.Error = awserr.NewRequestFailure( - awserr.New("BucketRegionError", - fmt.Sprintf("incorrect region, the bucket is not in '%s' region", - aws.StringValue(r.Config.Region)), - nil), - r.HTTPResponse.StatusCode, - r.RequestID, - ) + r.Error = requestFailure{ + RequestFailure: awserr.NewRequestFailure( + awserr.New("BucketRegionError", + fmt.Sprintf("incorrect region, the bucket is not in '%s' region", + aws.StringValue(r.Config.Region)), + nil), + r.HTTPResponse.StatusCode, + r.RequestID, + ), + hostID: hostID, + } return } @@ -48,6 +53,7 @@ func unmarshalError(r *request.Request) { } else { errCode = resp.Code errMsg = resp.Message + err = nil } // Fallback to status code converted to message if still no error code @@ -57,9 +63,41 @@ func unmarshalError(r *request.Request) { errMsg = statusText } - r.Error = awserr.NewRequestFailure( - awserr.New(errCode, errMsg, nil), - r.HTTPResponse.StatusCode, - r.RequestID, - ) + r.Error = requestFailure{ + RequestFailure: awserr.NewRequestFailure( + awserr.New(errCode, errMsg, err), + r.HTTPResponse.StatusCode, + r.RequestID, + ), + hostID: hostID, + } +} + +// A RequestFailure provides access to the S3 Request ID and Host ID values +// returned from API operation errors. Getting the error as a string will +// return the formated error with the same information as awserr.RequestFailure, +// while also adding the HostID value from the response. +type RequestFailure interface { + awserr.RequestFailure + + // Host ID is the S3 Host ID needed for debug, and contacting support + HostID() string +} + +type requestFailure struct { + awserr.RequestFailure + + hostID string +} + +func (r requestFailure) Error() string { + extra := fmt.Sprintf("status code: %d, request id: %s, host id: %s", + r.StatusCode(), r.RequestID(), r.hostID) + return awserr.SprintError(r.Code(), r.Message(), extra, r.OrigErr()) +} +func (r requestFailure) String() string { + return r.Error() +} +func (r requestFailure) HostID() string { + return r.hostID } diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/s3/waiters.go index 5e16be4..cccfa8c 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/waiters.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/waiters.go @@ -1,9 +1,12 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package s3 import ( - "github.com/aws/aws-sdk-go/private/waiter" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" ) // WaitUntilBucketExists uses the Amazon S3 API operation @@ -11,44 +14,60 @@ import ( // If the condition is not meet within the max attempt window an error will // be returned. func (c *S3) WaitUntilBucketExists(input *HeadBucketInput) error { - waiterCfg := waiter.Config{ - Operation: "HeadBucket", - Delay: 5, + return c.WaitUntilBucketExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilBucketExistsWithContext is an extended version of WaitUntilBucketExists. +// With the support for passing in a context and options to configure the +// Waiter and the underlying request options. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) WaitUntilBucketExistsWithContext(ctx aws.Context, input *HeadBucketInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilBucketExists", MaxAttempts: 20, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 200, }, { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 301, }, { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 403, }, { - State: "retry", - Matcher: "status", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 404, }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *HeadBucketInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.HeadBucketRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilBucketNotExists uses the Amazon S3 API operation @@ -56,26 +75,45 @@ func (c *S3) WaitUntilBucketExists(input *HeadBucketInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *S3) WaitUntilBucketNotExists(input *HeadBucketInput) error { - waiterCfg := waiter.Config{ - Operation: "HeadBucket", - Delay: 5, + return c.WaitUntilBucketNotExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilBucketNotExistsWithContext is an extended version of WaitUntilBucketNotExists. +// With the support for passing in a context and options to configure the +// Waiter and the underlying request options. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) WaitUntilBucketNotExistsWithContext(ctx aws.Context, input *HeadBucketInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilBucketNotExists", MaxAttempts: 20, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 404, }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *HeadBucketInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.HeadBucketRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilObjectExists uses the Amazon S3 API operation @@ -83,32 +121,50 @@ func (c *S3) WaitUntilBucketNotExists(input *HeadBucketInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *S3) WaitUntilObjectExists(input *HeadObjectInput) error { - waiterCfg := waiter.Config{ - Operation: "HeadObject", - Delay: 5, + return c.WaitUntilObjectExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilObjectExistsWithContext is an extended version of WaitUntilObjectExists. +// With the support for passing in a context and options to configure the +// Waiter and the underlying request options. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) WaitUntilObjectExistsWithContext(ctx aws.Context, input *HeadObjectInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilObjectExists", MaxAttempts: 20, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 200, }, { - State: "retry", - Matcher: "status", - Argument: "", + State: request.RetryWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 404, }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *HeadObjectInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.HeadObjectRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } // WaitUntilObjectNotExists uses the Amazon S3 API operation @@ -116,24 +172,43 @@ func (c *S3) WaitUntilObjectExists(input *HeadObjectInput) error { // If the condition is not meet within the max attempt window an error will // be returned. func (c *S3) WaitUntilObjectNotExists(input *HeadObjectInput) error { - waiterCfg := waiter.Config{ - Operation: "HeadObject", - Delay: 5, + return c.WaitUntilObjectNotExistsWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilObjectNotExistsWithContext is an extended version of WaitUntilObjectNotExists. +// With the support for passing in a context and options to configure the +// Waiter and the underlying request options. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *S3) WaitUntilObjectNotExistsWithContext(ctx aws.Context, input *HeadObjectInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilObjectNotExists", MaxAttempts: 20, - Acceptors: []waiter.WaitAcceptor{ + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ { - State: "success", - Matcher: "status", - Argument: "", + State: request.SuccessWaiterState, + Matcher: request.StatusWaiterMatch, Expected: 404, }, }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *HeadObjectInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.HeadObjectRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, } + w.ApplyOptions(opts...) - w := waiter.Waiter{ - Client: c, - Input: input, - Config: waiterCfg, - } - return w.Wait() + return w.WaitWithContext(ctx) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/api.go b/vendor/github.com/aws/aws-sdk-go/service/sts/api.go index 4459465..19dd0bf 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sts/api.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. // Package sts provides a client for AWS Security Token Service. package sts @@ -6,6 +6,7 @@ package sts import ( "time" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/request" ) @@ -48,9 +49,8 @@ func (c *STS) AssumeRoleRequest(input *AssumeRoleInput) (req *request.Request, o input = &AssumeRoleInput{} } - req = c.newRequest(op, input, output) output = &AssumeRoleOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -154,16 +154,16 @@ func (c *STS) AssumeRoleRequest(input *AssumeRoleInput) (req *request.Request, o // API operation AssumeRole for usage and error information. // // Returned Error Codes: -// * MalformedPolicyDocument +// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" // The request was rejected because the policy document was malformed. The error // message describes the specific error. // -// * PackedPolicyTooLarge +// * ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" // The request was rejected because the policy document was too large. The error // message describes how big the policy document is, in packed form, as a percentage // of what the API allows. // -// * RegionDisabledException +// * ErrCodeRegionDisabledException "RegionDisabledException" // STS is not activated in the requested region for the account that is being // asked to generate credentials. The account administrator must use the IAM // console to activate STS in that region. For more information, see Activating @@ -173,8 +173,23 @@ func (c *STS) AssumeRoleRequest(input *AssumeRoleInput) (req *request.Request, o // Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRole func (c *STS) AssumeRole(input *AssumeRoleInput) (*AssumeRoleOutput, error) { req, out := c.AssumeRoleRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssumeRoleWithContext is the same as AssumeRole with the addition of +// the ability to pass a context and additional request options. +// +// See AssumeRole for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *STS) AssumeRoleWithContext(ctx aws.Context, input *AssumeRoleInput, opts ...request.Option) (*AssumeRoleOutput, error) { + req, out := c.AssumeRoleRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAssumeRoleWithSAML = "AssumeRoleWithSAML" @@ -215,9 +230,8 @@ func (c *STS) AssumeRoleWithSAMLRequest(input *AssumeRoleWithSAMLInput) (req *re input = &AssumeRoleWithSAMLInput{} } - req = c.newRequest(op, input, output) output = &AssumeRoleWithSAMLOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -299,31 +313,31 @@ func (c *STS) AssumeRoleWithSAMLRequest(input *AssumeRoleWithSAMLInput) (req *re // API operation AssumeRoleWithSAML for usage and error information. // // Returned Error Codes: -// * MalformedPolicyDocument +// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" // The request was rejected because the policy document was malformed. The error // message describes the specific error. // -// * PackedPolicyTooLarge +// * ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" // The request was rejected because the policy document was too large. The error // message describes how big the policy document is, in packed form, as a percentage // of what the API allows. // -// * IDPRejectedClaim +// * ErrCodeIDPRejectedClaimException "IDPRejectedClaim" // The identity provider (IdP) reported that authentication failed. This might // be because the claim is invalid. // // If this error is returned for the AssumeRoleWithWebIdentity operation, it // can also mean that the claim has expired or has been explicitly revoked. // -// * InvalidIdentityToken +// * ErrCodeInvalidIdentityTokenException "InvalidIdentityToken" // The web identity token that was passed could not be validated by AWS. Get // a new identity token from the identity provider and then retry the request. // -// * ExpiredTokenException +// * ErrCodeExpiredTokenException "ExpiredTokenException" // The web identity token that was passed is expired or is not valid. Get a // new identity token from the identity provider and then retry the request. // -// * RegionDisabledException +// * ErrCodeRegionDisabledException "RegionDisabledException" // STS is not activated in the requested region for the account that is being // asked to generate credentials. The account administrator must use the IAM // console to activate STS in that region. For more information, see Activating @@ -333,8 +347,23 @@ func (c *STS) AssumeRoleWithSAMLRequest(input *AssumeRoleWithSAMLInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAML func (c *STS) AssumeRoleWithSAML(input *AssumeRoleWithSAMLInput) (*AssumeRoleWithSAMLOutput, error) { req, out := c.AssumeRoleWithSAMLRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssumeRoleWithSAMLWithContext is the same as AssumeRoleWithSAML with the addition of +// the ability to pass a context and additional request options. +// +// See AssumeRoleWithSAML for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *STS) AssumeRoleWithSAMLWithContext(ctx aws.Context, input *AssumeRoleWithSAMLInput, opts ...request.Option) (*AssumeRoleWithSAMLOutput, error) { + req, out := c.AssumeRoleWithSAMLRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opAssumeRoleWithWebIdentity = "AssumeRoleWithWebIdentity" @@ -375,9 +404,8 @@ func (c *STS) AssumeRoleWithWebIdentityRequest(input *AssumeRoleWithWebIdentityI input = &AssumeRoleWithWebIdentityInput{} } - req = c.newRequest(op, input, output) output = &AssumeRoleWithWebIdentityOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -481,38 +509,38 @@ func (c *STS) AssumeRoleWithWebIdentityRequest(input *AssumeRoleWithWebIdentityI // API operation AssumeRoleWithWebIdentity for usage and error information. // // Returned Error Codes: -// * MalformedPolicyDocument +// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" // The request was rejected because the policy document was malformed. The error // message describes the specific error. // -// * PackedPolicyTooLarge +// * ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" // The request was rejected because the policy document was too large. The error // message describes how big the policy document is, in packed form, as a percentage // of what the API allows. // -// * IDPRejectedClaim +// * ErrCodeIDPRejectedClaimException "IDPRejectedClaim" // The identity provider (IdP) reported that authentication failed. This might // be because the claim is invalid. // // If this error is returned for the AssumeRoleWithWebIdentity operation, it // can also mean that the claim has expired or has been explicitly revoked. // -// * IDPCommunicationError +// * ErrCodeIDPCommunicationErrorException "IDPCommunicationError" // The request could not be fulfilled because the non-AWS identity provider // (IDP) that was asked to verify the incoming identity token could not be reached. // This is often a transient error caused by network conditions. Retry the request // a limited number of times so that you don't exceed the request rate. If the // error persists, the non-AWS identity provider might be down or not responding. // -// * InvalidIdentityToken +// * ErrCodeInvalidIdentityTokenException "InvalidIdentityToken" // The web identity token that was passed could not be validated by AWS. Get // a new identity token from the identity provider and then retry the request. // -// * ExpiredTokenException +// * ErrCodeExpiredTokenException "ExpiredTokenException" // The web identity token that was passed is expired or is not valid. Get a // new identity token from the identity provider and then retry the request. // -// * RegionDisabledException +// * ErrCodeRegionDisabledException "RegionDisabledException" // STS is not activated in the requested region for the account that is being // asked to generate credentials. The account administrator must use the IAM // console to activate STS in that region. For more information, see Activating @@ -522,8 +550,23 @@ func (c *STS) AssumeRoleWithWebIdentityRequest(input *AssumeRoleWithWebIdentityI // Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentity func (c *STS) AssumeRoleWithWebIdentity(input *AssumeRoleWithWebIdentityInput) (*AssumeRoleWithWebIdentityOutput, error) { req, out := c.AssumeRoleWithWebIdentityRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// AssumeRoleWithWebIdentityWithContext is the same as AssumeRoleWithWebIdentity with the addition of +// the ability to pass a context and additional request options. +// +// See AssumeRoleWithWebIdentity for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *STS) AssumeRoleWithWebIdentityWithContext(ctx aws.Context, input *AssumeRoleWithWebIdentityInput, opts ...request.Option) (*AssumeRoleWithWebIdentityOutput, error) { + req, out := c.AssumeRoleWithWebIdentityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opDecodeAuthorizationMessage = "DecodeAuthorizationMessage" @@ -564,9 +607,8 @@ func (c *STS) DecodeAuthorizationMessageRequest(input *DecodeAuthorizationMessag input = &DecodeAuthorizationMessageInput{} } - req = c.newRequest(op, input, output) output = &DecodeAuthorizationMessageOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -613,7 +655,7 @@ func (c *STS) DecodeAuthorizationMessageRequest(input *DecodeAuthorizationMessag // API operation DecodeAuthorizationMessage for usage and error information. // // Returned Error Codes: -// * InvalidAuthorizationMessageException +// * ErrCodeInvalidAuthorizationMessageException "InvalidAuthorizationMessageException" // The error returned if the message passed to DecodeAuthorizationMessage was // invalid. This can happen if the token contains invalid characters, such as // linebreaks. @@ -621,8 +663,23 @@ func (c *STS) DecodeAuthorizationMessageRequest(input *DecodeAuthorizationMessag // Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessage func (c *STS) DecodeAuthorizationMessage(input *DecodeAuthorizationMessageInput) (*DecodeAuthorizationMessageOutput, error) { req, out := c.DecodeAuthorizationMessageRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// DecodeAuthorizationMessageWithContext is the same as DecodeAuthorizationMessage with the addition of +// the ability to pass a context and additional request options. +// +// See DecodeAuthorizationMessage for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *STS) DecodeAuthorizationMessageWithContext(ctx aws.Context, input *DecodeAuthorizationMessageInput, opts ...request.Option) (*DecodeAuthorizationMessageOutput, error) { + req, out := c.DecodeAuthorizationMessageRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetCallerIdentity = "GetCallerIdentity" @@ -663,9 +720,8 @@ func (c *STS) GetCallerIdentityRequest(input *GetCallerIdentityInput) (req *requ input = &GetCallerIdentityInput{} } - req = c.newRequest(op, input, output) output = &GetCallerIdentityOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -683,8 +739,23 @@ func (c *STS) GetCallerIdentityRequest(input *GetCallerIdentityInput) (req *requ // Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentity func (c *STS) GetCallerIdentity(input *GetCallerIdentityInput) (*GetCallerIdentityOutput, error) { req, out := c.GetCallerIdentityRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetCallerIdentityWithContext is the same as GetCallerIdentity with the addition of +// the ability to pass a context and additional request options. +// +// See GetCallerIdentity for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *STS) GetCallerIdentityWithContext(ctx aws.Context, input *GetCallerIdentityInput, opts ...request.Option) (*GetCallerIdentityOutput, error) { + req, out := c.GetCallerIdentityRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetFederationToken = "GetFederationToken" @@ -725,9 +796,8 @@ func (c *STS) GetFederationTokenRequest(input *GetFederationTokenInput) (req *re input = &GetFederationTokenInput{} } - req = c.newRequest(op, input, output) output = &GetFederationTokenOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -820,16 +890,16 @@ func (c *STS) GetFederationTokenRequest(input *GetFederationTokenInput) (req *re // API operation GetFederationToken for usage and error information. // // Returned Error Codes: -// * MalformedPolicyDocument +// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" // The request was rejected because the policy document was malformed. The error // message describes the specific error. // -// * PackedPolicyTooLarge +// * ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" // The request was rejected because the policy document was too large. The error // message describes how big the policy document is, in packed form, as a percentage // of what the API allows. // -// * RegionDisabledException +// * ErrCodeRegionDisabledException "RegionDisabledException" // STS is not activated in the requested region for the account that is being // asked to generate credentials. The account administrator must use the IAM // console to activate STS in that region. For more information, see Activating @@ -839,8 +909,23 @@ func (c *STS) GetFederationTokenRequest(input *GetFederationTokenInput) (req *re // Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationToken func (c *STS) GetFederationToken(input *GetFederationTokenInput) (*GetFederationTokenOutput, error) { req, out := c.GetFederationTokenRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetFederationTokenWithContext is the same as GetFederationToken with the addition of +// the ability to pass a context and additional request options. +// +// See GetFederationToken for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *STS) GetFederationTokenWithContext(ctx aws.Context, input *GetFederationTokenInput, opts ...request.Option) (*GetFederationTokenOutput, error) { + req, out := c.GetFederationTokenRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } const opGetSessionToken = "GetSessionToken" @@ -881,9 +966,8 @@ func (c *STS) GetSessionTokenRequest(input *GetSessionTokenInput) (req *request. input = &GetSessionTokenInput{} } - req = c.newRequest(op, input, output) output = &GetSessionTokenOutput{} - req.Data = output + req = c.newRequest(op, input, output) return } @@ -944,7 +1028,7 @@ func (c *STS) GetSessionTokenRequest(input *GetSessionTokenInput) (req *request. // API operation GetSessionToken for usage and error information. // // Returned Error Codes: -// * RegionDisabledException +// * ErrCodeRegionDisabledException "RegionDisabledException" // STS is not activated in the requested region for the account that is being // asked to generate credentials. The account administrator must use the IAM // console to activate STS in that region. For more information, see Activating @@ -954,8 +1038,23 @@ func (c *STS) GetSessionTokenRequest(input *GetSessionTokenInput) (req *request. // Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionToken func (c *STS) GetSessionToken(input *GetSessionTokenInput) (*GetSessionTokenOutput, error) { req, out := c.GetSessionTokenRequest(input) - err := req.Send() - return out, err + return out, req.Send() +} + +// GetSessionTokenWithContext is the same as GetSessionToken with the addition of +// the ability to pass a context and additional request options. +// +// See GetSessionToken for details on how to use this API operation. +// +// The context must be non-nil and will be used for request cancellation. If +// the context is nil a panic will occur. In the future the SDK may create +// sub-contexts for http.Requests. See https://golang.org/pkg/context/ +// for more information on using Contexts. +func (c *STS) GetSessionTokenWithContext(ctx aws.Context, input *GetSessionTokenInput, opts ...request.Option) (*GetSessionTokenOutput, error) { + req, out := c.GetSessionTokenRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() } // Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleRequest diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go b/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go new file mode 100644 index 0000000..e24884e --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go @@ -0,0 +1,73 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package sts + +const ( + + // ErrCodeExpiredTokenException for service response error code + // "ExpiredTokenException". + // + // The web identity token that was passed is expired or is not valid. Get a + // new identity token from the identity provider and then retry the request. + ErrCodeExpiredTokenException = "ExpiredTokenException" + + // ErrCodeIDPCommunicationErrorException for service response error code + // "IDPCommunicationError". + // + // The request could not be fulfilled because the non-AWS identity provider + // (IDP) that was asked to verify the incoming identity token could not be reached. + // This is often a transient error caused by network conditions. Retry the request + // a limited number of times so that you don't exceed the request rate. If the + // error persists, the non-AWS identity provider might be down or not responding. + ErrCodeIDPCommunicationErrorException = "IDPCommunicationError" + + // ErrCodeIDPRejectedClaimException for service response error code + // "IDPRejectedClaim". + // + // The identity provider (IdP) reported that authentication failed. This might + // be because the claim is invalid. + // + // If this error is returned for the AssumeRoleWithWebIdentity operation, it + // can also mean that the claim has expired or has been explicitly revoked. + ErrCodeIDPRejectedClaimException = "IDPRejectedClaim" + + // ErrCodeInvalidAuthorizationMessageException for service response error code + // "InvalidAuthorizationMessageException". + // + // The error returned if the message passed to DecodeAuthorizationMessage was + // invalid. This can happen if the token contains invalid characters, such as + // linebreaks. + ErrCodeInvalidAuthorizationMessageException = "InvalidAuthorizationMessageException" + + // ErrCodeInvalidIdentityTokenException for service response error code + // "InvalidIdentityToken". + // + // The web identity token that was passed could not be validated by AWS. Get + // a new identity token from the identity provider and then retry the request. + ErrCodeInvalidIdentityTokenException = "InvalidIdentityToken" + + // ErrCodeMalformedPolicyDocumentException for service response error code + // "MalformedPolicyDocument". + // + // The request was rejected because the policy document was malformed. The error + // message describes the specific error. + ErrCodeMalformedPolicyDocumentException = "MalformedPolicyDocument" + + // ErrCodePackedPolicyTooLargeException for service response error code + // "PackedPolicyTooLarge". + // + // The request was rejected because the policy document was too large. The error + // message describes how big the policy document is, in packed form, as a percentage + // of what the API allows. + ErrCodePackedPolicyTooLargeException = "PackedPolicyTooLarge" + + // ErrCodeRegionDisabledException for service response error code + // "RegionDisabledException". + // + // STS is not activated in the requested region for the account that is being + // asked to generate credentials. The account administrator must use the IAM + // console to activate STS in that region. For more information, see Activating + // and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) + // in the IAM User Guide. + ErrCodeRegionDisabledException = "RegionDisabledException" +) diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/service.go b/vendor/github.com/aws/aws-sdk-go/service/sts/service.go index 9c4bfb8..be21838 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/service.go +++ b/vendor/github.com/aws/aws-sdk-go/service/sts/service.go @@ -1,4 +1,4 @@ -// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. package sts diff --git a/vendor/github.com/go-ini/ini/Makefile b/vendor/github.com/go-ini/ini/Makefile new file mode 100644 index 0000000..ac034e5 --- /dev/null +++ b/vendor/github.com/go-ini/ini/Makefile @@ -0,0 +1,12 @@ +.PHONY: build test bench vet + +build: vet bench + +test: + go test -v -cover -race + +bench: + go test -v -cover -race -test.bench=. -test.benchmem + +vet: + go vet diff --git a/vendor/github.com/go-ini/ini/README.md b/vendor/github.com/go-ini/ini/README.md index 1272038..8594742 100644 --- a/vendor/github.com/go-ini/ini/README.md +++ b/vendor/github.com/go-ini/ini/README.md @@ -1,4 +1,4 @@ -ini [![Build Status](https://drone.io/github.com/go-ini/ini/status.png)](https://drone.io/github.com/go-ini/ini/latest) [![](http://gocover.io/_badge/github.com/go-ini/ini)](http://gocover.io/github.com/go-ini/ini) +INI [![Build Status](https://travis-ci.org/go-ini/ini.svg?branch=master)](https://travis-ci.org/go-ini/ini) [![Sourcegraph](https://sourcegraph.com/github.com/go-ini/ini/-/badge.svg)](https://sourcegraph.com/github.com/go-ini/ini?badge) === ![](https://avatars0.githubusercontent.com/u/10216035?v=3&s=200) @@ -9,7 +9,7 @@ Package ini provides INI file read and write functionality in Go. ## Feature -- Load multiple data sources(`[]byte` or file) with overwrites. +- Load multiple data sources(`[]byte`, file and `io.ReadCloser`) with overwrites. - Read with recursion values. - Read with parent-child sections. - Read with auto-increment key names. @@ -22,16 +22,32 @@ Package ini provides INI file read and write functionality in Go. ## Installation +To use a tagged revision: + go get gopkg.in/ini.v1 +To use with latest changes: + + go get github.com/go-ini/ini + +Please add `-u` flag to update in the future. + +### Testing + +If you want to test on your machine, please apply `-t` flag: + + go get -t gopkg.in/ini.v1 + +Please add `-u` flag to update in the future. + ## Getting Started ### Loading from data sources -A **Data Source** is either raw data in type `[]byte` or a file name with type `string` and you can load **as many as** data sources you want. Passing other types will simply return an error. +A **Data Source** is either raw data in type `[]byte`, a file name with type `string` or `io.ReadCloser`. You can load **as many data sources as you want**. Passing other types will simply return an error. ```go -cfg, err := ini.Load([]byte("raw data"), "filename") +cfg, err := ini.Load([]byte("raw data"), "filename", ioutil.NopCloser(bytes.NewReader([]byte("some other data")))) ``` Or start with an empty object: @@ -40,12 +56,72 @@ Or start with an empty object: cfg := ini.Empty() ``` -When you cannot decide how many data sources to load at the beginning, you still able to **Append()** them later. +When you cannot decide how many data sources to load at the beginning, you will still be able to **Append()** them later. ```go err := cfg.Append("other file", []byte("other raw data")) ``` +If you have a list of files with possibilities that some of them may not available at the time, and you don't know exactly which ones, you can use `LooseLoad` to ignore nonexistent files without returning error. + +```go +cfg, err := ini.LooseLoad("filename", "filename_404") +``` + +The cool thing is, whenever the file is available to load while you're calling `Reload` method, it will be counted as usual. + +#### Ignore cases of key name + +When you do not care about cases of section and key names, you can use `InsensitiveLoad` to force all names to be lowercased while parsing. + +```go +cfg, err := ini.InsensitiveLoad("filename") +//... + +// sec1 and sec2 are the exactly same section object +sec1, err := cfg.GetSection("Section") +sec2, err := cfg.GetSection("SecTIOn") + +// key1 and key2 are the exactly same key object +key1, err := cfg.GetKey("Key") +key2, err := cfg.GetKey("KeY") +``` + +#### MySQL-like boolean key + +MySQL's configuration allows a key without value as follows: + +```ini +[mysqld] +... +skip-host-cache +skip-name-resolve +``` + +By default, this is considered as missing value. But if you know you're going to deal with those cases, you can assign advanced load options: + +```go +cfg, err := LoadSources(LoadOptions{AllowBooleanKeys: true}, "my.cnf")) +``` + +The value of those keys are always `true`, and when you save to a file, it will keep in the same foramt as you read. + +To generate such keys in your program, you could use `NewBooleanKey`: + +```go +key, err := sec.NewBooleanKey("skip-host-cache") +``` + +#### Comment + +Take care that following format will be treated as comment: + +1. Line begins with `#` or `;` +2. Words after `#` or `;` +3. Words after section name (i.e words after `[some section name]`) + +If you want to save a value with `#` or `;`, please quote them with ``` ` ``` or ``` """ ```. + ### Working with sections To get a section, you would need to: @@ -63,7 +139,7 @@ section, err := cfg.GetSection("") When you're pretty sure the section exists, following code could make your life easier: ```go -section := cfg.Section("") +section := cfg.Section("section name") ``` What happens when the section somehow does not exist? Don't panic, it automatically creates and returns a new section to you. @@ -95,6 +171,12 @@ Same rule applies to key operations: key := cfg.Section("").Key("key name") ``` +To check if a key exists: + +```go +yes := cfg.Section("").HasKey("key name") +``` + To create a new key: ```go @@ -111,7 +193,7 @@ names := cfg.Section("").KeyStrings() To get a clone hash of keys and corresponding values: ```go -hash := cfg.GetSection("").KeysHash() +hash := cfg.Section("").KeysHash() ``` ### Working with values @@ -133,12 +215,24 @@ val := cfg.Section("").Key("key name").Validate(func(in string) string { }) ``` +If you do not want any auto-transformation (such as recursive read) for the values, you can get raw value directly (this way you get much better performance): + +```go +val := cfg.Section("").Key("key name").Value() +``` + +To check if raw value exists: + +```go +yes := cfg.Section("").HasValue("test value") +``` + To get value with types: ```go // For boolean values: -// true when value is: 1, t, T, TRUE, true, True, YES, yes, Yes, ON, on, On -// false when value is: 0, f, F, FALSE, false, False, NO, no, No, OFF, off, Off +// true when value is: 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On +// false when value is: 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off v, err = cfg.Section("").Key("BOOL").Bool() v, err = cfg.Section("").Key("FLOAT64").Float64() v, err = cfg.Section("").Key("INT").Int() @@ -212,6 +306,16 @@ cfg.Section("advance").Key("two_lines").String() // how about continuation lines cfg.Section("advance").Key("lots_of_lines").String() // 1 2 3 4 ``` +Well, I hate continuation lines, how do I disable that? + +```go +cfg, err := ini.LoadSources(ini.LoadOptions{ + IgnoreContinuation: true, +}, "filename") +``` + +Holy crap! + Note that single quotes around values will be stripped: ```ini @@ -250,9 +354,13 @@ vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), min vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339 ``` -To auto-split value into slice: +##### Auto-split values into a slice + +To use zero value of type for invalid inputs: ```go +// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] +// Input: how, 2.2, are, you -> [0.0 2.2 0.0 0.0] vals = cfg.Section("").Key("STRINGS").Strings(",") vals = cfg.Section("").Key("FLOAT64S").Float64s(",") vals = cfg.Section("").Key("INTS").Ints(",") @@ -262,6 +370,32 @@ vals = cfg.Section("").Key("UINT64S").Uint64s(",") vals = cfg.Section("").Key("TIMES").Times(",") ``` +To exclude invalid values out of result slice: + +```go +// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] +// Input: how, 2.2, are, you -> [2.2] +vals = cfg.Section("").Key("FLOAT64S").ValidFloat64s(",") +vals = cfg.Section("").Key("INTS").ValidInts(",") +vals = cfg.Section("").Key("INT64S").ValidInt64s(",") +vals = cfg.Section("").Key("UINTS").ValidUints(",") +vals = cfg.Section("").Key("UINT64S").ValidUint64s(",") +vals = cfg.Section("").Key("TIMES").ValidTimes(",") +``` + +Or to return nothing but error when have invalid inputs: + +```go +// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] +// Input: how, 2.2, are, you -> error +vals = cfg.Section("").Key("FLOAT64S").StrictFloat64s(",") +vals = cfg.Section("").Key("INTS").StrictInts(",") +vals = cfg.Section("").Key("INT64S").StrictInt64s(",") +vals = cfg.Section("").Key("UINTS").StrictUints(",") +vals = cfg.Section("").Key("UINT64S").StrictUint64s(",") +vals = cfg.Section("").Key("TIMES").StrictTimes(",") +``` + ### Save your configuration Finally, it's time to save your configuration to somewhere. @@ -282,6 +416,12 @@ cfg.WriteTo(writer) cfg.WriteToIndent(writer, "\t") ``` +By default, spaces are used to align "=" sign between key and values, to disable that: + +```go +ini.PrettyFormat = false +``` + ## Advanced Usage ### Recursive Values @@ -323,6 +463,27 @@ CLONE_URL = https://%(IMPORT_PATH)s cfg.Section("package.sub").Key("CLONE_URL").String() // https://gopkg.in/ini.v1 ``` +#### Retrieve parent keys available to a child section + +```go +cfg.Section("package.sub").ParentKeys() // ["CLONE_URL"] +``` + +### Unparseable Sections + +Sometimes, you have sections that do not contain key-value pairs but raw content, to handle such case, you can use `LoadOptions.UnparsableSections`: + +```go +cfg, err := LoadSources(LoadOptions{UnparseableSections: []string{"COMMENTS"}}, `[COMMENTS] +<1> This slide has the fuel listed in the wrong units `)) + +body := cfg.Section("COMMENTS").Body() + +/* --- start --- +<1> This slide has the fuel listed in the wrong units +------ end --- */ +``` + ### Auto-increment Key Names If key name is `-` in data source, then it would be seen as special syntax for auto-increment key name start from 1, and every section is independent on counter. @@ -407,8 +568,8 @@ Why not? ```go type Embeded struct { Dates []time.Time `delim:"|"` - Places []string - None []int + Places []string `ini:"places,omitempty"` + None []int `ini:",omitempty"` } type Author struct { @@ -443,8 +604,7 @@ GPA = 2.8 [Embeded] Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00 -Places = HangZhou,Boston -None = +places = HangZhou,Boston ``` #### Name Mapper @@ -464,7 +624,7 @@ type Info struct { } func main() { - err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("packag_name=ini")) + err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("package_name=ini")) // ... cfg, err := ini.Load([]byte("PACKAGE_NAME=ini")) @@ -478,6 +638,26 @@ func main() { Same rules of name mapper apply to `ini.ReflectFromWithMapper` function. +#### Value Mapper + +To expand values (e.g. from environment variables), you can use the `ValueMapper` to transform values: + +```go +type Env struct { + Foo string `ini:"foo"` +} + +func main() { + cfg, err := ini.Load([]byte("[env]\nfoo = ${MY_VAR}\n") + cfg.ValueMapper = os.ExpandEnv + // ... + env := &Env{} + err = cfg.Section("env").MapTo(env) +} +``` + +This would set the value of `env.Foo` to the value of the environment variable `MY_VAR`. + #### Other Notes On Map/Reflect Any embedded struct is treated as a section by default, and there is no automatic parent-child relations in map/reflect feature: diff --git a/vendor/github.com/go-ini/ini/README_ZH.md b/vendor/github.com/go-ini/ini/README_ZH.md index 45e19ed..163432d 100644 --- a/vendor/github.com/go-ini/ini/README_ZH.md +++ b/vendor/github.com/go-ini/ini/README_ZH.md @@ -2,7 +2,7 @@ ## 功能特性 -- 支持覆盖加载多个数据源(`[]byte` 或文件) +- 支持覆盖加载多个数据源(`[]byte`、文件和 `io.ReadCloser`) - 支持递归读取键值 - 支持读取父子分区 - 支持读取自增键名 @@ -15,16 +15,32 @@ ## 下载安装 +使用一个特定版本: + go get gopkg.in/ini.v1 +使用最新版: + + go get github.com/go-ini/ini + +如需更新请添加 `-u` 选项。 + +### 测试安装 + +如果您想要在自己的机器上运行测试,请使用 `-t` 标记: + + go get -t gopkg.in/ini.v1 + +如需更新请添加 `-u` 选项。 + ## 开始使用 ### 从数据源加载 -一个 **数据源** 可以是 `[]byte` 类型的原始数据,或 `string` 类型的文件路径。您可以加载 **任意多个** 数据源。如果您传递其它类型的数据源,则会直接返回错误。 +一个 **数据源** 可以是 `[]byte` 类型的原始数据,`string` 类型的文件路径或 `io.ReadCloser`。您可以加载 **任意多个** 数据源。如果您传递其它类型的数据源,则会直接返回错误。 ```go -cfg, err := ini.Load([]byte("raw data"), "filename") +cfg, err := ini.Load([]byte("raw data"), "filename", ioutil.NopCloser(bytes.NewReader([]byte("some other data")))) ``` 或者从一个空白的文件开始: @@ -39,6 +55,66 @@ cfg := ini.Empty() err := cfg.Append("other file", []byte("other raw data")) ``` +当您想要加载一系列文件,但是不能够确定其中哪些文件是不存在的,可以通过调用函数 `LooseLoad` 来忽略它们(`Load` 会因为文件不存在而返回错误): + +```go +cfg, err := ini.LooseLoad("filename", "filename_404") +``` + +更牛逼的是,当那些之前不存在的文件在重新调用 `Reload` 方法的时候突然出现了,那么它们会被正常加载。 + +#### 忽略键名的大小写 + +有时候分区和键的名称大小写混合非常烦人,这个时候就可以通过 `InsensitiveLoad` 将所有分区和键名在读取里强制转换为小写: + +```go +cfg, err := ini.InsensitiveLoad("filename") +//... + +// sec1 和 sec2 指向同一个分区对象 +sec1, err := cfg.GetSection("Section") +sec2, err := cfg.GetSection("SecTIOn") + +// key1 和 key2 指向同一个键对象 +key1, err := cfg.GetKey("Key") +key2, err := cfg.GetKey("KeY") +``` + +#### 类似 MySQL 配置中的布尔值键 + +MySQL 的配置文件中会出现没有具体值的布尔类型的键: + +```ini +[mysqld] +... +skip-host-cache +skip-name-resolve +``` + +默认情况下这被认为是缺失值而无法完成解析,但可以通过高级的加载选项对它们进行处理: + +```go +cfg, err := LoadSources(LoadOptions{AllowBooleanKeys: true}, "my.cnf")) +``` + +这些键的值永远为 `true`,且在保存到文件时也只会输出键名。 + +如果您想要通过程序来生成此类键,则可以使用 `NewBooleanKey`: + +```go +key, err := sec.NewBooleanKey("skip-host-cache") +``` + +#### 关于注释 + +下述几种情况的内容将被视为注释: + +1. 所有以 `#` 或 `;` 开头的行 +2. 所有在 `#` 或 `;` 之后的内容 +3. 分区标签后的文字 (即 `[分区名]` 之后的内容) + +如果你希望使用包含 `#` 或 `;` 的值,请使用 ``` ` ``` 或 ``` """ ``` 进行包覆。 + ### 操作分区(Section) 获取指定分区: @@ -56,7 +132,7 @@ section, err := cfg.GetSection("") 当您非常确定某个分区是存在的,可以使用以下简便方法: ```go -section := cfg.Section("") +section := cfg.Section("section name") ``` 如果不小心判断错了,要获取的分区其实是不存在的,那会发生什么呢?没事的,它会自动创建并返回一个对应的分区对象给您。 @@ -88,6 +164,12 @@ key, err := cfg.Section("").GetKey("key name") key := cfg.Section("").Key("key name") ``` +判断某个键是否存在: + +```go +yes := cfg.Section("").HasKey("key name") +``` + 创建一个新的键: ```go @@ -104,7 +186,7 @@ names := cfg.Section("").KeyStrings() 获取分区下的所有键值对的克隆: ```go -hash := cfg.GetSection("").KeysHash() +hash := cfg.Section("").KeysHash() ``` ### 操作键值(Value) @@ -126,12 +208,24 @@ val := cfg.Section("").Key("key name").Validate(func(in string) string { }) ``` +如果您不需要任何对值的自动转变功能(例如递归读取),可以直接获取原值(这种方式性能最佳): + +```go +val := cfg.Section("").Key("key name").Value() +``` + +判断某个原值是否存在: + +```go +yes := cfg.Section("").HasValue("test value") +``` + 获取其它类型的值: ```go // 布尔值的规则: -// true 当值为:1, t, T, TRUE, true, True, YES, yes, Yes, ON, on, On -// false 当值为:0, f, F, FALSE, false, False, NO, no, No, OFF, off, Off +// true 当值为:1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On +// false 当值为:0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off v, err = cfg.Section("").Key("BOOL").Bool() v, err = cfg.Section("").Key("FLOAT64").Float64() v, err = cfg.Section("").Key("INT").Int() @@ -205,6 +299,16 @@ cfg.Section("advance").Key("two_lines").String() // how about continuation lines cfg.Section("advance").Key("lots_of_lines").String() // 1 2 3 4 ``` +可是我有时候觉得两行连在一起特别没劲,怎么才能不自动连接两行呢? + +```go +cfg, err := ini.LoadSources(ini.LoadOptions{ + IgnoreContinuation: true, +}, "filename") +``` + +哇靠给力啊! + 需要注意的是,值两侧的单引号会被自动剔除: ```ini @@ -243,9 +347,13 @@ vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), min vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339 ``` -自动分割键值为切片(slice): +##### 自动分割键值到切片(slice) + +当存在无效输入时,使用零值代替: ```go +// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] +// Input: how, 2.2, are, you -> [0.0 2.2 0.0 0.0] vals = cfg.Section("").Key("STRINGS").Strings(",") vals = cfg.Section("").Key("FLOAT64S").Float64s(",") vals = cfg.Section("").Key("INTS").Ints(",") @@ -255,6 +363,32 @@ vals = cfg.Section("").Key("UINT64S").Uint64s(",") vals = cfg.Section("").Key("TIMES").Times(",") ``` +从结果切片中剔除无效输入: + +```go +// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] +// Input: how, 2.2, are, you -> [2.2] +vals = cfg.Section("").Key("FLOAT64S").ValidFloat64s(",") +vals = cfg.Section("").Key("INTS").ValidInts(",") +vals = cfg.Section("").Key("INT64S").ValidInt64s(",") +vals = cfg.Section("").Key("UINTS").ValidUints(",") +vals = cfg.Section("").Key("UINT64S").ValidUint64s(",") +vals = cfg.Section("").Key("TIMES").ValidTimes(",") +``` + +当存在无效输入时,直接返回错误: + +```go +// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] +// Input: how, 2.2, are, you -> error +vals = cfg.Section("").Key("FLOAT64S").StrictFloat64s(",") +vals = cfg.Section("").Key("INTS").StrictInts(",") +vals = cfg.Section("").Key("INT64S").StrictInt64s(",") +vals = cfg.Section("").Key("UINTS").StrictUints(",") +vals = cfg.Section("").Key("UINT64S").StrictUint64s(",") +vals = cfg.Section("").Key("TIMES").StrictTimes(",") +``` + ### 保存配置 终于到了这个时刻,是时候保存一下配置了。 @@ -275,9 +409,15 @@ cfg.WriteTo(writer) cfg.WriteToIndent(writer, "\t") ``` -### 高级用法 +默认情况下,空格将被用于对齐键值之间的等号以美化输出结果,以下代码可以禁用该功能: -#### 递归读取键值 +```go +ini.PrettyFormat = false +``` + +## 高级用法 + +### 递归读取键值 在获取所有键值的过程中,特殊语法 `%()s` 会被应用,其中 `` 可以是相同分区或者默认分区下的键名。字符串 `%()s` 会被相应的键值所替代,如果指定的键不存在,则会用空字符串替代。您可以最多使用 99 层的递归嵌套。 @@ -297,7 +437,7 @@ cfg.Section("author").Key("GITHUB").String() // https://github.com/Unknwon cfg.Section("package").Key("FULL_NAME").String() // github.com/go-ini/ini ``` -#### 读取父子分区 +### 读取父子分区 您可以在分区名称中使用 `.` 来表示两个或多个分区之间的父子关系。如果某个键在子分区中不存在,则会去它的父分区中再次寻找,直到没有父分区为止。 @@ -316,7 +456,28 @@ CLONE_URL = https://%(IMPORT_PATH)s cfg.Section("package.sub").Key("CLONE_URL").String() // https://gopkg.in/ini.v1 ``` -#### 读取自增键名 +#### 获取上级父分区下的所有键名 + +```go +cfg.Section("package.sub").ParentKeys() // ["CLONE_URL"] +``` + +### 无法解析的分区 + +如果遇到一些比较特殊的分区,它们不包含常见的键值对,而是没有固定格式的纯文本,则可以使用 `LoadOptions.UnparsableSections` 进行处理: + +```go +cfg, err := LoadSources(LoadOptions{UnparseableSections: []string{"COMMENTS"}}, `[COMMENTS] +<1> This slide has the fuel listed in the wrong units `)) + +body := cfg.Section("COMMENTS").Body() + +/* --- start --- +<1> This slide has the fuel listed in the wrong units +------ end --- */ +``` + +### 读取自增键名 如果数据源中的键名为 `-`,则认为该键使用了自增键名的特殊语法。计数器从 1 开始,并且分区之间是相互独立的。 @@ -398,8 +559,8 @@ p := &Person{ ```go type Embeded struct { Dates []time.Time `delim:"|"` - Places []string - None []int + Places []string `ini:"places,omitempty"` + None []int `ini:",omitempty"` } type Author struct { @@ -434,8 +595,7 @@ GPA = 2.8 [Embeded] Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00 -Places = HangZhou,Boston -None = +places = HangZhou,Boston ``` #### 名称映射器(Name Mapper) @@ -455,7 +615,7 @@ type Info struct{ } func main() { - err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("packag_name=ini")) + err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("package_name=ini")) // ... cfg, err := ini.Load([]byte("PACKAGE_NAME=ini")) @@ -469,6 +629,26 @@ func main() { 使用函数 `ini.ReflectFromWithMapper` 时也可应用相同的规则。 +#### 值映射器(Value Mapper) + +值映射器允许使用一个自定义函数自动展开值的具体内容,例如:运行时获取环境变量: + +```go +type Env struct { + Foo string `ini:"foo"` +} + +func main() { + cfg, err := ini.Load([]byte("[env]\nfoo = ${MY_VAR}\n") + cfg.ValueMapper = os.ExpandEnv + // ... + env := &Env{} + err = cfg.Section("env").MapTo(env) +} +``` + +本例中,`env.Foo` 将会是运行时所获取到环境变量 `MY_VAR` 的值。 + #### 映射/反射的其它说明 任何嵌入的结构都会被默认认作一个不同的分区,并且不会自动产生所谓的父子分区关联: diff --git a/vendor/github.com/go-ini/ini/error.go b/vendor/github.com/go-ini/ini/error.go new file mode 100644 index 0000000..80afe74 --- /dev/null +++ b/vendor/github.com/go-ini/ini/error.go @@ -0,0 +1,32 @@ +// Copyright 2016 Unknwon +// +// 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. + +package ini + +import ( + "fmt" +) + +type ErrDelimiterNotFound struct { + Line string +} + +func IsErrDelimiterNotFound(err error) bool { + _, ok := err.(ErrDelimiterNotFound) + return ok +} + +func (err ErrDelimiterNotFound) Error() string { + return fmt.Sprintf("key-value delimiter not found: %s", err.Line) +} diff --git a/vendor/github.com/go-ini/ini/ini.go b/vendor/github.com/go-ini/ini/ini.go index 1fee789..68d73aa 100644 --- a/vendor/github.com/go-ini/ini/ini.go +++ b/vendor/github.com/go-ini/ini/ini.go @@ -16,11 +16,11 @@ package ini import ( - "bufio" "bytes" "errors" "fmt" "io" + "io/ioutil" "os" "regexp" "runtime" @@ -31,25 +31,35 @@ import ( ) const ( + // Name for default section. You can use this constant or the string literal. + // In most of cases, an empty string is all you need to access the section. DEFAULT_SECTION = "DEFAULT" + // Maximum allowed depth when recursively substituing variable names. _DEPTH_VALUES = 99 - - _VERSION = "1.6.0" + _VERSION = "1.25.4" ) +// Version returns current package version literal. func Version() string { return _VERSION } var ( + // Delimiter to determine or compose a new line. + // This variable will be changed to "\r\n" automatically on Windows + // at package init time. LineBreak = "\n" // Variable regexp pattern: %(variable)s varPattern = regexp.MustCompile(`%\(([^\)]+)\)s`) - // Write spaces around "=" to look better. + // Indicate whether to align "=" sign with spaces to produce pretty output + // or reduce all possible spaces for compact format. PrettyFormat = true + + // Explicitly write DEFAULT section header + DefaultHeader = false ) func init() { @@ -67,11 +77,12 @@ func inSlice(str string, s []string) bool { return false } -// dataSource is a interface that returns file content. +// dataSource is an interface that returns object which can be read and closed. type dataSource interface { ReadCloser() (io.ReadCloser, error) } +// sourceFile represents an object that contains content on the local file system. type sourceFile struct { name string } @@ -92,597 +103,24 @@ func (rc *bytesReadCloser) Close() error { return nil } +// sourceData represents an object that contains content in memory. type sourceData struct { data []byte } func (s *sourceData) ReadCloser() (io.ReadCloser, error) { - return &bytesReadCloser{bytes.NewReader(s.data)}, nil -} - -// ____ __. -// | |/ _|____ ___.__. -// | <_/ __ < | | -// | | \ ___/\___ | -// |____|__ \___ > ____| -// \/ \/\/ - -// Key represents a key under a section. -type Key struct { - s *Section - Comment string - name string - value string - isAutoIncr bool -} - -// Name returns name of key. -func (k *Key) Name() string { - return k.name -} - -// Value returns raw value of key for performance purpose. -func (k *Key) Value() string { - return k.value -} - -// String returns string representation of value. -func (k *Key) String() string { - val := k.value - if strings.Index(val, "%") == -1 { - return val - } - - for i := 0; i < _DEPTH_VALUES; i++ { - vr := varPattern.FindString(val) - if len(vr) == 0 { - break - } - - // Take off leading '%(' and trailing ')s'. - noption := strings.TrimLeft(vr, "%(") - noption = strings.TrimRight(noption, ")s") - - // Search in the same section. - nk, err := k.s.GetKey(noption) - if err != nil { - // Search again in default section. - nk, _ = k.s.f.Section("").GetKey(noption) - } - - // Substitute by new value and take off leading '%(' and trailing ')s'. - val = strings.Replace(val, vr, nk.value, -1) - } - return val -} - -// Validate accepts a validate function which can -// return modifed result as key value. -func (k *Key) Validate(fn func(string) string) string { - return fn(k.String()) -} - -// parseBool returns the boolean value represented by the string. -// -// It accepts 1, t, T, TRUE, true, True, YES, yes, Yes, ON, on, On, -// 0, f, F, FALSE, false, False, NO, no, No, OFF, off, Off. -// Any other value returns an error. -func parseBool(str string) (value bool, err error) { - switch str { - case "1", "t", "T", "true", "TRUE", "True", "YES", "yes", "Yes", "ON", "on", "On": - return true, nil - case "0", "f", "F", "false", "FALSE", "False", "NO", "no", "No", "OFF", "off", "Off": - return false, nil - } - return false, fmt.Errorf("parsing \"%s\": invalid syntax", str) -} - -// Bool returns bool type value. -func (k *Key) Bool() (bool, error) { - return parseBool(k.String()) -} - -// Float64 returns float64 type value. -func (k *Key) Float64() (float64, error) { - return strconv.ParseFloat(k.String(), 64) -} - -// Int returns int type value. -func (k *Key) Int() (int, error) { - return strconv.Atoi(k.String()) -} - -// Int64 returns int64 type value. -func (k *Key) Int64() (int64, error) { - return strconv.ParseInt(k.String(), 10, 64) -} - -// Uint returns uint type valued. -func (k *Key) Uint() (uint, error) { - u, e := strconv.ParseUint(k.String(), 10, 64) - return uint(u), e -} - -// Uint64 returns uint64 type value. -func (k *Key) Uint64() (uint64, error) { - return strconv.ParseUint(k.String(), 10, 64) -} - -// Duration returns time.Duration type value. -func (k *Key) Duration() (time.Duration, error) { - return time.ParseDuration(k.String()) -} - -// TimeFormat parses with given format and returns time.Time type value. -func (k *Key) TimeFormat(format string) (time.Time, error) { - return time.Parse(format, k.String()) -} - -// Time parses with RFC3339 format and returns time.Time type value. -func (k *Key) Time() (time.Time, error) { - return k.TimeFormat(time.RFC3339) -} - -// MustString returns default value if key value is empty. -func (k *Key) MustString(defaultVal string) string { - val := k.String() - if len(val) == 0 { - return defaultVal - } - return val -} - -// MustBool always returns value without error, -// it returns false if error occurs. -func (k *Key) MustBool(defaultVal ...bool) bool { - val, err := k.Bool() - if len(defaultVal) > 0 && err != nil { - return defaultVal[0] - } - return val -} - -// MustFloat64 always returns value without error, -// it returns 0.0 if error occurs. -func (k *Key) MustFloat64(defaultVal ...float64) float64 { - val, err := k.Float64() - if len(defaultVal) > 0 && err != nil { - return defaultVal[0] - } - return val -} - -// MustInt always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustInt(defaultVal ...int) int { - val, err := k.Int() - if len(defaultVal) > 0 && err != nil { - return defaultVal[0] - } - return val -} - -// MustInt64 always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustInt64(defaultVal ...int64) int64 { - val, err := k.Int64() - if len(defaultVal) > 0 && err != nil { - return defaultVal[0] - } - return val -} - -// MustUint always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustUint(defaultVal ...uint) uint { - val, err := k.Uint() - if len(defaultVal) > 0 && err != nil { - return defaultVal[0] - } - return val -} - -// MustUint64 always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustUint64(defaultVal ...uint64) uint64 { - val, err := k.Uint64() - if len(defaultVal) > 0 && err != nil { - return defaultVal[0] - } - return val -} - -// MustDuration always returns value without error, -// it returns zero value if error occurs. -func (k *Key) MustDuration(defaultVal ...time.Duration) time.Duration { - val, err := k.Duration() - if len(defaultVal) > 0 && err != nil { - return defaultVal[0] - } - return val -} - -// MustTimeFormat always parses with given format and returns value without error, -// it returns zero value if error occurs. -func (k *Key) MustTimeFormat(format string, defaultVal ...time.Time) time.Time { - val, err := k.TimeFormat(format) - if len(defaultVal) > 0 && err != nil { - return defaultVal[0] - } - return val -} - -// MustTime always parses with RFC3339 format and returns value without error, -// it returns zero value if error occurs. -func (k *Key) MustTime(defaultVal ...time.Time) time.Time { - return k.MustTimeFormat(time.RFC3339, defaultVal...) -} - -// In always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) In(defaultVal string, candidates []string) string { - val := k.String() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InFloat64 always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InFloat64(defaultVal float64, candidates []float64) float64 { - val := k.MustFloat64() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InInt always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InInt(defaultVal int, candidates []int) int { - val := k.MustInt() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InInt64 always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InInt64(defaultVal int64, candidates []int64) int64 { - val := k.MustInt64() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InUint always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InUint(defaultVal uint, candidates []uint) uint { - val := k.MustUint() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InUint64 always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InUint64(defaultVal uint64, candidates []uint64) uint64 { - val := k.MustUint64() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InTimeFormat always parses with given format and returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InTimeFormat(format string, defaultVal time.Time, candidates []time.Time) time.Time { - val := k.MustTimeFormat(format) - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InTime always parses with RFC3339 format and returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InTime(defaultVal time.Time, candidates []time.Time) time.Time { - return k.InTimeFormat(time.RFC3339, defaultVal, candidates) -} - -// RangeFloat64 checks if value is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeFloat64(defaultVal, min, max float64) float64 { - val := k.MustFloat64() - if val < min || val > max { - return defaultVal - } - return val -} - -// RangeInt checks if value is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeInt(defaultVal, min, max int) int { - val := k.MustInt() - if val < min || val > max { - return defaultVal - } - return val -} - -// RangeInt64 checks if value is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeInt64(defaultVal, min, max int64) int64 { - val := k.MustInt64() - if val < min || val > max { - return defaultVal - } - return val -} - -// RangeTimeFormat checks if value with given format is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeTimeFormat(format string, defaultVal, min, max time.Time) time.Time { - val := k.MustTimeFormat(format) - if val.Unix() < min.Unix() || val.Unix() > max.Unix() { - return defaultVal - } - return val -} - -// RangeTime checks if value with RFC3339 format is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeTime(defaultVal, min, max time.Time) time.Time { - return k.RangeTimeFormat(time.RFC3339, defaultVal, min, max) -} - -// Strings returns list of string devide by given delimiter. -func (k *Key) Strings(delim string) []string { - str := k.String() - if len(str) == 0 { - return []string{} - } - - vals := strings.Split(str, delim) - for i := range vals { - vals[i] = strings.TrimSpace(vals[i]) - } - return vals -} - -// Float64s returns list of float64 devide by given delimiter. -func (k *Key) Float64s(delim string) []float64 { - strs := k.Strings(delim) - vals := make([]float64, len(strs)) - for i := range strs { - vals[i], _ = strconv.ParseFloat(strs[i], 64) - } - return vals -} - -// Ints returns list of int devide by given delimiter. -func (k *Key) Ints(delim string) []int { - strs := k.Strings(delim) - vals := make([]int, len(strs)) - for i := range strs { - vals[i], _ = strconv.Atoi(strs[i]) - } - return vals -} - -// Int64s returns list of int64 devide by given delimiter. -func (k *Key) Int64s(delim string) []int64 { - strs := k.Strings(delim) - vals := make([]int64, len(strs)) - for i := range strs { - vals[i], _ = strconv.ParseInt(strs[i], 10, 64) - } - return vals -} - -// Uints returns list of uint devide by given delimiter. -func (k *Key) Uints(delim string) []uint { - strs := k.Strings(delim) - vals := make([]uint, len(strs)) - for i := range strs { - u, _ := strconv.ParseUint(strs[i], 10, 64) - vals[i] = uint(u) - } - return vals -} - -// Uint64s returns list of uint64 devide by given delimiter. -func (k *Key) Uint64s(delim string) []uint64 { - strs := k.Strings(delim) - vals := make([]uint64, len(strs)) - for i := range strs { - vals[i], _ = strconv.ParseUint(strs[i], 10, 64) - } - return vals -} - -// TimesFormat parses with given format and returns list of time.Time devide by given delimiter. -func (k *Key) TimesFormat(format, delim string) []time.Time { - strs := k.Strings(delim) - vals := make([]time.Time, len(strs)) - for i := range strs { - vals[i], _ = time.Parse(format, strs[i]) - } - return vals -} - -// Times parses with RFC3339 format and returns list of time.Time devide by given delimiter. -func (k *Key) Times(delim string) []time.Time { - return k.TimesFormat(time.RFC3339, delim) -} - -// SetValue changes key value. -func (k *Key) SetValue(v string) { - k.value = v -} - -// _________ __ .__ -// / _____/ ____ _____/ |_|__| ____ ____ -// \_____ \_/ __ \_/ ___\ __\ |/ _ \ / \ -// / \ ___/\ \___| | | ( <_> ) | \ -// /_______ /\___ >\___ >__| |__|\____/|___| / -// \/ \/ \/ \/ - -// Section represents a config section. -type Section struct { - f *File - Comment string - name string - keys map[string]*Key - keyList []string - keysHash map[string]string -} - -func newSection(f *File, name string) *Section { - return &Section{f, "", name, make(map[string]*Key), make([]string, 0, 10), make(map[string]string)} -} - -// Name returns name of Section. -func (s *Section) Name() string { - return s.name -} - -// NewKey creates a new key to given section. -func (s *Section) NewKey(name, val string) (*Key, error) { - if len(name) == 0 { - return nil, errors.New("error creating new key: empty key name") - } - - if s.f.BlockMode { - s.f.lock.Lock() - defer s.f.lock.Unlock() - } - - if inSlice(name, s.keyList) { - s.keys[name].value = val - return s.keys[name], nil - } - - s.keyList = append(s.keyList, name) - s.keys[name] = &Key{s, "", name, val, false} - s.keysHash[name] = val - return s.keys[name], nil -} - -// GetKey returns key in section by given name. -func (s *Section) GetKey(name string) (*Key, error) { - // FIXME: change to section level lock? - if s.f.BlockMode { - s.f.lock.RLock() - } - key := s.keys[name] - if s.f.BlockMode { - s.f.lock.RUnlock() - } - - if key == nil { - // Check if it is a child-section. - sname := s.name - for { - if i := strings.LastIndex(sname, "."); i > -1 { - sname = sname[:i] - sec, err := s.f.GetSection(sname) - if err != nil { - continue - } - return sec.GetKey(name) - } else { - break - } - } - return nil, fmt.Errorf("error when getting key of section '%s': key '%s' not exists", s.name, name) - } - return key, nil -} - -// Key assumes named Key exists in section and returns a zero-value when not. -func (s *Section) Key(name string) *Key { - key, err := s.GetKey(name) - if err != nil { - // It's OK here because the only possible error is empty key name, - // but if it's empty, this piece of code won't be executed. - key, _ = s.NewKey(name, "") - return key - } - return key -} - -// Keys returns list of keys of section. -func (s *Section) Keys() []*Key { - keys := make([]*Key, len(s.keyList)) - for i := range s.keyList { - keys[i] = s.Key(s.keyList[i]) - } - return keys -} - -// KeyStrings returns list of key names of section. -func (s *Section) KeyStrings() []string { - list := make([]string, len(s.keyList)) - copy(list, s.keyList) - return list + return ioutil.NopCloser(bytes.NewReader(s.data)), nil } -// KeysHash returns keys hash consisting of names and values. -func (s *Section) KeysHash() map[string]string { - if s.f.BlockMode { - s.f.lock.RLock() - defer s.f.lock.RUnlock() - } - - hash := map[string]string{} - for key, value := range s.keysHash { - hash[key] = value - } - return hash +// sourceReadCloser represents an input stream with Close method. +type sourceReadCloser struct { + reader io.ReadCloser } -// DeleteKey deletes a key from section. -func (s *Section) DeleteKey(name string) { - if s.f.BlockMode { - s.f.lock.Lock() - defer s.f.lock.Unlock() - } - - for i, k := range s.keyList { - if k == name { - s.keyList = append(s.keyList[:i], s.keyList[i+1:]...) - delete(s.keys, name) - return - } - } +func (s *sourceReadCloser) ReadCloser() (io.ReadCloser, error) { + return s.reader, nil } -// ___________.__.__ -// \_ _____/|__| | ____ -// | __) | | | _/ __ \ -// | \ | | |_\ ___/ -// \___ / |__|____/\___ > -// \/ \/ - // File represents a combination of a or more INI file(s) in memory. type File struct { // Should make things safe, but sometimes doesn't matter. @@ -698,16 +136,20 @@ type File struct { // To keep data in order. sectionList []string + options LoadOptions + NameMapper + ValueMapper } // newFile initializes File object with given data sources. -func newFile(dataSources []dataSource) *File { +func newFile(dataSources []dataSource, opts LoadOptions) *File { return &File{ BlockMode: true, dataSources: dataSources, sections: make(map[string]*Section), sectionList: make([]string, 0, 10), + options: opts, } } @@ -717,14 +159,31 @@ func parseDataSource(source interface{}) (dataSource, error) { return sourceFile{s}, nil case []byte: return &sourceData{s}, nil + case io.ReadCloser: + return &sourceReadCloser{s}, nil default: return nil, fmt.Errorf("error parsing data source: unknown type '%s'", s) } } -// Load loads and parses from INI data sources. -// Arguments can be mixed of file name with string type, or raw data in []byte. -func Load(source interface{}, others ...interface{}) (_ *File, err error) { +type LoadOptions struct { + // Loose indicates whether the parser should ignore nonexistent files or return error. + Loose bool + // Insensitive indicates whether the parser forces all section and key names to lowercase. + Insensitive bool + // IgnoreContinuation indicates whether to ignore continuation lines while parsing. + IgnoreContinuation bool + // AllowBooleanKeys indicates whether to allow boolean type keys or treat as value is missing. + // This type of keys are mostly used in my.cnf. + AllowBooleanKeys bool + // AllowShadows indicates whether to keep track of keys with same name under same section. + AllowShadows bool + // Some INI formats allow group blocks that store a block of raw content that doesn't otherwise + // conform to key/value pairs. Specify the names of those blocks here. + UnparseableSections []string +} + +func LoadSources(opts LoadOptions, source interface{}, others ...interface{}) (_ *File, err error) { sources := make([]dataSource, len(others)+1) sources[0], err = parseDataSource(source) if err != nil { @@ -736,8 +195,36 @@ func Load(source interface{}, others ...interface{}) (_ *File, err error) { return nil, err } } - f := newFile(sources) - return f, f.Reload() + f := newFile(sources, opts) + if err = f.Reload(); err != nil { + return nil, err + } + return f, nil +} + +// Load loads and parses from INI data sources. +// Arguments can be mixed of file name with string type, or raw data in []byte. +// It will return error if list contains nonexistent files. +func Load(source interface{}, others ...interface{}) (*File, error) { + return LoadSources(LoadOptions{}, source, others...) +} + +// LooseLoad has exactly same functionality as Load function +// except it ignores nonexistent files instead of returning error. +func LooseLoad(source interface{}, others ...interface{}) (*File, error) { + return LoadSources(LoadOptions{Loose: true}, source, others...) +} + +// InsensitiveLoad has exactly same functionality as Load function +// except it forces all section and key names to be lowercased. +func InsensitiveLoad(source interface{}, others ...interface{}) (*File, error) { + return LoadSources(LoadOptions{Insensitive: true}, source, others...) +} + +// InsensitiveLoad has exactly same functionality as Load function +// except it allows have shadow keys. +func ShadowLoad(source interface{}, others ...interface{}) (*File, error) { + return LoadSources(LoadOptions{AllowShadows: true}, source, others...) } // Empty returns an empty file object. @@ -751,6 +238,8 @@ func Empty() *File { func (f *File) NewSection(name string) (*Section, error) { if len(name) == 0 { return nil, errors.New("error creating new section: empty section name") + } else if f.options.Insensitive && name != DEFAULT_SECTION { + name = strings.ToLower(name) } if f.BlockMode { @@ -767,6 +256,18 @@ func (f *File) NewSection(name string) (*Section, error) { return f.sections[name], nil } +// NewRawSection creates a new section with an unparseable body. +func (f *File) NewRawSection(name, body string) (*Section, error) { + section, err := f.NewSection(name) + if err != nil { + return nil, err + } + + section.isRawSection = true + section.rawBody = body + return section, nil +} + // NewSections creates a list of sections. func (f *File) NewSections(names ...string) (err error) { for _, name := range names { @@ -781,6 +282,8 @@ func (f *File) NewSections(names ...string) (err error) { func (f *File) GetSection(name string) (*Section, error) { if len(name) == 0 { name = DEFAULT_SECTION + } else if f.options.Insensitive { + name = strings.ToLower(name) } if f.BlockMode { @@ -790,7 +293,7 @@ func (f *File) GetSection(name string) (*Section, error) { sec := f.sections[name] if sec == nil { - return nil, fmt.Errorf("error when getting section: section '%s' not exists", name) + return nil, fmt.Errorf("section '%s' does not exist", name) } return sec, nil } @@ -843,240 +346,6 @@ func (f *File) DeleteSection(name string) { } } -func cutComment(str string) string { - i := strings.Index(str, "#") - if i == -1 { - return str - } - return str[:i] -} - -func checkMultipleLines(buf *bufio.Reader, line, val, valQuote string) (string, error) { - isEnd := false - for { - next, err := buf.ReadString('\n') - if err != nil { - if err != io.EOF { - return "", err - } - isEnd = true - } - pos := strings.LastIndex(next, valQuote) - if pos > -1 { - val += next[:pos] - break - } - val += next - if isEnd { - return "", fmt.Errorf("error parsing line: missing closing key quote from '%s' to '%s'", line, next) - } - } - return val, nil -} - -func checkContinuationLines(buf *bufio.Reader, val string) (string, bool, error) { - isEnd := false - for { - valLen := len(val) - if valLen == 0 || val[valLen-1] != '\\' { - break - } - val = val[:valLen-1] - - next, err := buf.ReadString('\n') - if err != nil { - if err != io.EOF { - return "", isEnd, err - } - isEnd = true - } - - next = strings.TrimSpace(next) - if len(next) == 0 { - break - } - val += next - } - return val, isEnd, nil -} - -// parse parses data through an io.Reader. -func (f *File) parse(reader io.Reader) error { - buf := bufio.NewReader(reader) - - // Handle BOM-UTF8. - // http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding - mask, err := buf.Peek(3) - if err == nil && len(mask) >= 3 && mask[0] == 239 && mask[1] == 187 && mask[2] == 191 { - buf.Read(mask) - } - - count := 1 - comments := "" - isEnd := false - - section, err := f.NewSection(DEFAULT_SECTION) - if err != nil { - return err - } - - for { - line, err := buf.ReadString('\n') - line = strings.TrimSpace(line) - length := len(line) - - // Check error and ignore io.EOF just for a moment. - if err != nil { - if err != io.EOF { - return fmt.Errorf("error reading next line: %v", err) - } - // The last line of file could be an empty line. - if length == 0 { - break - } - isEnd = true - } - - // Skip empty lines. - if length == 0 { - continue - } - - switch { - case line[0] == '#' || line[0] == ';': // Comments. - if len(comments) == 0 { - comments = line - } else { - comments += LineBreak + line - } - continue - case line[0] == '[' && line[length-1] == ']': // New sction. - section, err = f.NewSection(strings.TrimSpace(line[1 : length-1])) - if err != nil { - return err - } - - if len(comments) > 0 { - section.Comment = comments - comments = "" - } - // Reset counter. - count = 1 - continue - } - - // Other possibilities. - var ( - i int - keyQuote string - kname string - valQuote string - val string - ) - - // Key name surrounded by quotes. - if line[0] == '"' { - if length > 6 && line[0:3] == `"""` { - keyQuote = `"""` - } else { - keyQuote = `"` - } - } else if line[0] == '`' { - keyQuote = "`" - } - if len(keyQuote) > 0 { - qLen := len(keyQuote) - pos := strings.Index(line[qLen:], keyQuote) - if pos == -1 { - return fmt.Errorf("error parsing line: missing closing key quote: %s", line) - } - pos = pos + qLen - i = strings.IndexAny(line[pos:], "=:") - if i < 0 { - return fmt.Errorf("error parsing line: key-value delimiter not found: %s", line) - } else if i == pos { - return fmt.Errorf("error parsing line: key is empty: %s", line) - } - i = i + pos - kname = line[qLen:pos] // Just keep spaces inside quotes. - } else { - i = strings.IndexAny(line, "=:") - if i < 0 { - return fmt.Errorf("error parsing line: key-value delimiter not found: %s", line) - } else if i == 0 { - return fmt.Errorf("error parsing line: key is empty: %s", line) - } - kname = strings.TrimSpace(line[0:i]) - } - - isAutoIncr := false - // Auto increment. - if kname == "-" { - isAutoIncr = true - kname = "#" + fmt.Sprint(count) - count++ - } - - lineRight := strings.TrimSpace(line[i+1:]) - lineRightLength := len(lineRight) - firstChar := "" - if lineRightLength >= 2 { - firstChar = lineRight[0:1] - } - if firstChar == "`" { - valQuote = "`" - } else if firstChar == `"` { - if lineRightLength >= 3 && lineRight[0:3] == `"""` { - valQuote = `"""` - } else { - valQuote = `"` - } - } else if firstChar == `'` { - valQuote = `'` - } - - if len(valQuote) > 0 { - qLen := len(valQuote) - pos := strings.LastIndex(lineRight[qLen:], valQuote) - // For multiple-line value check. - if pos == -1 { - if valQuote == `"` || valQuote == `'` { - return fmt.Errorf("error parsing line: single quote does not allow multiple-line value: %s", line) - } - - val = lineRight[qLen:] + "\n" - val, err = checkMultipleLines(buf, line, val, valQuote) - if err != nil { - return err - } - } else { - val = lineRight[qLen : pos+qLen] - } - } else { - val = strings.TrimSpace(cutComment(lineRight)) - val, isEnd, err = checkContinuationLines(buf, val) - if err != nil { - return err - } - } - - k, err := section.NewKey(kname, val) - if err != nil { - return err - } - k.isAutoIncr = isAutoIncr - if len(comments) > 0 { - k.Comment = comments - comments = "" - } - - if isEnd { - break - } - } - return nil -} - func (f *File) reload(s dataSource) error { r, err := s.ReadCloser() if err != nil { @@ -1091,6 +360,11 @@ func (f *File) reload(s dataSource) error { func (f *File) Reload() (err error) { for _, s := range f.dataSources { if err = f.reload(s); err != nil { + // In loose mode, we create an empty default section for nonexistent files. + if os.IsNotExist(err) && f.options.Loose { + f.parse(bytes.NewBuffer(nil)) + continue + } return err } } @@ -1114,7 +388,9 @@ func (f *File) Append(source interface{}, others ...interface{}) error { return f.Reload() } -// WriteToIndent writes file content into io.Writer with given value indention. +// WriteToIndent writes content into io.Writer with given indention. +// If PrettyFormat has been set to be true, +// it will align "=" sign with spaces under each section. func (f *File) WriteToIndent(w io.Writer, indent string) (n int64, err error) { equalSign := "=" if PrettyFormat { @@ -1134,17 +410,46 @@ func (f *File) WriteToIndent(w io.Writer, indent string) (n int64, err error) { } } - if i > 0 { + if i > 0 || DefaultHeader { if _, err = buf.WriteString("[" + sname + "]" + LineBreak); err != nil { return 0, err } } else { - // Write nothing if default section is empty. + // Write nothing if default section is empty if len(sec.keyList) == 0 { continue } } + if sec.isRawSection { + if _, err = buf.WriteString(sec.rawBody); err != nil { + return 0, err + } + continue + } + + // Count and generate alignment length and buffer spaces using the + // longest key. Keys may be modifed if they contain certain characters so + // we need to take that into account in our calculation. + alignLength := 0 + if PrettyFormat { + for _, kname := range sec.keyList { + keyLength := len(kname) + // First case will surround key by ` and second by """ + if strings.ContainsAny(kname, "\"=:") { + keyLength += 2 + } else if strings.Contains(kname, "`") { + keyLength += 6 + } + + if keyLength > alignLength { + alignLength = keyLength + } + } + } + alignSpaces := bytes.Repeat([]byte(" "), alignLength) + + KEY_LIST: for _, kname := range sec.keyList { key := sec.Key(kname) if len(key.Comment) > 0 { @@ -1164,26 +469,44 @@ func (f *File) WriteToIndent(w io.Writer, indent string) (n int64, err error) { } switch { - case key.isAutoIncr: + case key.isAutoIncrement: kname = "-" - case strings.Contains(kname, "`") || strings.Contains(kname, `"`): - kname = `"""` + kname + `"""` - case strings.Contains(kname, `=`) || strings.Contains(kname, `:`): + case strings.ContainsAny(kname, "\"=:"): kname = "`" + kname + "`" + case strings.Contains(kname, "`"): + kname = `"""` + kname + `"""` } - val := key.value - // In case key value contains "\n", "`" or "\"". - if strings.Contains(val, "\n") || strings.Contains(val, "`") || strings.Contains(val, `"`) || - strings.Contains(val, "#") { - val = `"""` + val + `"""` - } - if _, err = buf.WriteString(kname + equalSign + val + LineBreak); err != nil { - return 0, err + for _, val := range key.ValueWithShadows() { + if _, err = buf.WriteString(kname); err != nil { + return 0, err + } + + if key.isBooleanType { + if kname != sec.keyList[len(sec.keyList)-1] { + buf.WriteString(LineBreak) + } + continue KEY_LIST + } + + // Write out alignment spaces before "=" sign + if PrettyFormat { + buf.Write(alignSpaces[:alignLength-len(kname)]) + } + + // In case key value contains "\n", "`", "\"", "#" or ";" + if strings.ContainsAny(val, "\n`") { + val = `"""` + val + `"""` + } else if strings.ContainsAny(val, "#;") { + val = "`" + val + "`" + } + if _, err = buf.WriteString(equalSign + val + LineBreak); err != nil { + return 0, err + } } } - // Put a line between sections. + // Put a line between sections if _, err = buf.WriteString(LineBreak); err != nil { return 0, err } diff --git a/vendor/github.com/go-ini/ini/key.go b/vendor/github.com/go-ini/ini/key.go new file mode 100644 index 0000000..852696f --- /dev/null +++ b/vendor/github.com/go-ini/ini/key.go @@ -0,0 +1,703 @@ +// Copyright 2014 Unknwon +// +// 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. + +package ini + +import ( + "errors" + "fmt" + "strconv" + "strings" + "time" +) + +// Key represents a key under a section. +type Key struct { + s *Section + name string + value string + isAutoIncrement bool + isBooleanType bool + + isShadow bool + shadows []*Key + + Comment string +} + +// newKey simply return a key object with given values. +func newKey(s *Section, name, val string) *Key { + return &Key{ + s: s, + name: name, + value: val, + } +} + +func (k *Key) addShadow(val string) error { + if k.isShadow { + return errors.New("cannot add shadow to another shadow key") + } else if k.isAutoIncrement || k.isBooleanType { + return errors.New("cannot add shadow to auto-increment or boolean key") + } + + shadow := newKey(k.s, k.name, val) + shadow.isShadow = true + k.shadows = append(k.shadows, shadow) + return nil +} + +// AddShadow adds a new shadow key to itself. +func (k *Key) AddShadow(val string) error { + if !k.s.f.options.AllowShadows { + return errors.New("shadow key is not allowed") + } + return k.addShadow(val) +} + +// ValueMapper represents a mapping function for values, e.g. os.ExpandEnv +type ValueMapper func(string) string + +// Name returns name of key. +func (k *Key) Name() string { + return k.name +} + +// Value returns raw value of key for performance purpose. +func (k *Key) Value() string { + return k.value +} + +// ValueWithShadows returns raw values of key and its shadows if any. +func (k *Key) ValueWithShadows() []string { + if len(k.shadows) == 0 { + return []string{k.value} + } + vals := make([]string, len(k.shadows)+1) + vals[0] = k.value + for i := range k.shadows { + vals[i+1] = k.shadows[i].value + } + return vals +} + +// transformValue takes a raw value and transforms to its final string. +func (k *Key) transformValue(val string) string { + if k.s.f.ValueMapper != nil { + val = k.s.f.ValueMapper(val) + } + + // Fail-fast if no indicate char found for recursive value + if !strings.Contains(val, "%") { + return val + } + for i := 0; i < _DEPTH_VALUES; i++ { + vr := varPattern.FindString(val) + if len(vr) == 0 { + break + } + + // Take off leading '%(' and trailing ')s'. + noption := strings.TrimLeft(vr, "%(") + noption = strings.TrimRight(noption, ")s") + + // Search in the same section. + nk, err := k.s.GetKey(noption) + if err != nil { + // Search again in default section. + nk, _ = k.s.f.Section("").GetKey(noption) + } + + // Substitute by new value and take off leading '%(' and trailing ')s'. + val = strings.Replace(val, vr, nk.value, -1) + } + return val +} + +// String returns string representation of value. +func (k *Key) String() string { + return k.transformValue(k.value) +} + +// Validate accepts a validate function which can +// return modifed result as key value. +func (k *Key) Validate(fn func(string) string) string { + return fn(k.String()) +} + +// parseBool returns the boolean value represented by the string. +// +// It accepts 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On, +// 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off. +// Any other value returns an error. +func parseBool(str string) (value bool, err error) { + switch str { + case "1", "t", "T", "true", "TRUE", "True", "YES", "yes", "Yes", "y", "ON", "on", "On": + return true, nil + case "0", "f", "F", "false", "FALSE", "False", "NO", "no", "No", "n", "OFF", "off", "Off": + return false, nil + } + return false, fmt.Errorf("parsing \"%s\": invalid syntax", str) +} + +// Bool returns bool type value. +func (k *Key) Bool() (bool, error) { + return parseBool(k.String()) +} + +// Float64 returns float64 type value. +func (k *Key) Float64() (float64, error) { + return strconv.ParseFloat(k.String(), 64) +} + +// Int returns int type value. +func (k *Key) Int() (int, error) { + return strconv.Atoi(k.String()) +} + +// Int64 returns int64 type value. +func (k *Key) Int64() (int64, error) { + return strconv.ParseInt(k.String(), 10, 64) +} + +// Uint returns uint type valued. +func (k *Key) Uint() (uint, error) { + u, e := strconv.ParseUint(k.String(), 10, 64) + return uint(u), e +} + +// Uint64 returns uint64 type value. +func (k *Key) Uint64() (uint64, error) { + return strconv.ParseUint(k.String(), 10, 64) +} + +// Duration returns time.Duration type value. +func (k *Key) Duration() (time.Duration, error) { + return time.ParseDuration(k.String()) +} + +// TimeFormat parses with given format and returns time.Time type value. +func (k *Key) TimeFormat(format string) (time.Time, error) { + return time.Parse(format, k.String()) +} + +// Time parses with RFC3339 format and returns time.Time type value. +func (k *Key) Time() (time.Time, error) { + return k.TimeFormat(time.RFC3339) +} + +// MustString returns default value if key value is empty. +func (k *Key) MustString(defaultVal string) string { + val := k.String() + if len(val) == 0 { + k.value = defaultVal + return defaultVal + } + return val +} + +// MustBool always returns value without error, +// it returns false if error occurs. +func (k *Key) MustBool(defaultVal ...bool) bool { + val, err := k.Bool() + if len(defaultVal) > 0 && err != nil { + k.value = strconv.FormatBool(defaultVal[0]) + return defaultVal[0] + } + return val +} + +// MustFloat64 always returns value without error, +// it returns 0.0 if error occurs. +func (k *Key) MustFloat64(defaultVal ...float64) float64 { + val, err := k.Float64() + if len(defaultVal) > 0 && err != nil { + k.value = strconv.FormatFloat(defaultVal[0], 'f', -1, 64) + return defaultVal[0] + } + return val +} + +// MustInt always returns value without error, +// it returns 0 if error occurs. +func (k *Key) MustInt(defaultVal ...int) int { + val, err := k.Int() + if len(defaultVal) > 0 && err != nil { + k.value = strconv.FormatInt(int64(defaultVal[0]), 10) + return defaultVal[0] + } + return val +} + +// MustInt64 always returns value without error, +// it returns 0 if error occurs. +func (k *Key) MustInt64(defaultVal ...int64) int64 { + val, err := k.Int64() + if len(defaultVal) > 0 && err != nil { + k.value = strconv.FormatInt(defaultVal[0], 10) + return defaultVal[0] + } + return val +} + +// MustUint always returns value without error, +// it returns 0 if error occurs. +func (k *Key) MustUint(defaultVal ...uint) uint { + val, err := k.Uint() + if len(defaultVal) > 0 && err != nil { + k.value = strconv.FormatUint(uint64(defaultVal[0]), 10) + return defaultVal[0] + } + return val +} + +// MustUint64 always returns value without error, +// it returns 0 if error occurs. +func (k *Key) MustUint64(defaultVal ...uint64) uint64 { + val, err := k.Uint64() + if len(defaultVal) > 0 && err != nil { + k.value = strconv.FormatUint(defaultVal[0], 10) + return defaultVal[0] + } + return val +} + +// MustDuration always returns value without error, +// it returns zero value if error occurs. +func (k *Key) MustDuration(defaultVal ...time.Duration) time.Duration { + val, err := k.Duration() + if len(defaultVal) > 0 && err != nil { + k.value = defaultVal[0].String() + return defaultVal[0] + } + return val +} + +// MustTimeFormat always parses with given format and returns value without error, +// it returns zero value if error occurs. +func (k *Key) MustTimeFormat(format string, defaultVal ...time.Time) time.Time { + val, err := k.TimeFormat(format) + if len(defaultVal) > 0 && err != nil { + k.value = defaultVal[0].Format(format) + return defaultVal[0] + } + return val +} + +// MustTime always parses with RFC3339 format and returns value without error, +// it returns zero value if error occurs. +func (k *Key) MustTime(defaultVal ...time.Time) time.Time { + return k.MustTimeFormat(time.RFC3339, defaultVal...) +} + +// In always returns value without error, +// it returns default value if error occurs or doesn't fit into candidates. +func (k *Key) In(defaultVal string, candidates []string) string { + val := k.String() + for _, cand := range candidates { + if val == cand { + return val + } + } + return defaultVal +} + +// InFloat64 always returns value without error, +// it returns default value if error occurs or doesn't fit into candidates. +func (k *Key) InFloat64(defaultVal float64, candidates []float64) float64 { + val := k.MustFloat64() + for _, cand := range candidates { + if val == cand { + return val + } + } + return defaultVal +} + +// InInt always returns value without error, +// it returns default value if error occurs or doesn't fit into candidates. +func (k *Key) InInt(defaultVal int, candidates []int) int { + val := k.MustInt() + for _, cand := range candidates { + if val == cand { + return val + } + } + return defaultVal +} + +// InInt64 always returns value without error, +// it returns default value if error occurs or doesn't fit into candidates. +func (k *Key) InInt64(defaultVal int64, candidates []int64) int64 { + val := k.MustInt64() + for _, cand := range candidates { + if val == cand { + return val + } + } + return defaultVal +} + +// InUint always returns value without error, +// it returns default value if error occurs or doesn't fit into candidates. +func (k *Key) InUint(defaultVal uint, candidates []uint) uint { + val := k.MustUint() + for _, cand := range candidates { + if val == cand { + return val + } + } + return defaultVal +} + +// InUint64 always returns value without error, +// it returns default value if error occurs or doesn't fit into candidates. +func (k *Key) InUint64(defaultVal uint64, candidates []uint64) uint64 { + val := k.MustUint64() + for _, cand := range candidates { + if val == cand { + return val + } + } + return defaultVal +} + +// InTimeFormat always parses with given format and returns value without error, +// it returns default value if error occurs or doesn't fit into candidates. +func (k *Key) InTimeFormat(format string, defaultVal time.Time, candidates []time.Time) time.Time { + val := k.MustTimeFormat(format) + for _, cand := range candidates { + if val == cand { + return val + } + } + return defaultVal +} + +// InTime always parses with RFC3339 format and returns value without error, +// it returns default value if error occurs or doesn't fit into candidates. +func (k *Key) InTime(defaultVal time.Time, candidates []time.Time) time.Time { + return k.InTimeFormat(time.RFC3339, defaultVal, candidates) +} + +// RangeFloat64 checks if value is in given range inclusively, +// and returns default value if it's not. +func (k *Key) RangeFloat64(defaultVal, min, max float64) float64 { + val := k.MustFloat64() + if val < min || val > max { + return defaultVal + } + return val +} + +// RangeInt checks if value is in given range inclusively, +// and returns default value if it's not. +func (k *Key) RangeInt(defaultVal, min, max int) int { + val := k.MustInt() + if val < min || val > max { + return defaultVal + } + return val +} + +// RangeInt64 checks if value is in given range inclusively, +// and returns default value if it's not. +func (k *Key) RangeInt64(defaultVal, min, max int64) int64 { + val := k.MustInt64() + if val < min || val > max { + return defaultVal + } + return val +} + +// RangeTimeFormat checks if value with given format is in given range inclusively, +// and returns default value if it's not. +func (k *Key) RangeTimeFormat(format string, defaultVal, min, max time.Time) time.Time { + val := k.MustTimeFormat(format) + if val.Unix() < min.Unix() || val.Unix() > max.Unix() { + return defaultVal + } + return val +} + +// RangeTime checks if value with RFC3339 format is in given range inclusively, +// and returns default value if it's not. +func (k *Key) RangeTime(defaultVal, min, max time.Time) time.Time { + return k.RangeTimeFormat(time.RFC3339, defaultVal, min, max) +} + +// Strings returns list of string divided by given delimiter. +func (k *Key) Strings(delim string) []string { + str := k.String() + if len(str) == 0 { + return []string{} + } + + vals := strings.Split(str, delim) + for i := range vals { + // vals[i] = k.transformValue(strings.TrimSpace(vals[i])) + vals[i] = strings.TrimSpace(vals[i]) + } + return vals +} + +// StringsWithShadows returns list of string divided by given delimiter. +// Shadows will also be appended if any. +func (k *Key) StringsWithShadows(delim string) []string { + vals := k.ValueWithShadows() + results := make([]string, 0, len(vals)*2) + for i := range vals { + if len(vals) == 0 { + continue + } + + results = append(results, strings.Split(vals[i], delim)...) + } + + for i := range results { + results[i] = k.transformValue(strings.TrimSpace(results[i])) + } + return results +} + +// Float64s returns list of float64 divided by given delimiter. Any invalid input will be treated as zero value. +func (k *Key) Float64s(delim string) []float64 { + vals, _ := k.getFloat64s(delim, true, false) + return vals +} + +// Ints returns list of int divided by given delimiter. Any invalid input will be treated as zero value. +func (k *Key) Ints(delim string) []int { + vals, _ := k.parseInts(k.Strings(delim), true, false) + return vals +} + +// Int64s returns list of int64 divided by given delimiter. Any invalid input will be treated as zero value. +func (k *Key) Int64s(delim string) []int64 { + vals, _ := k.parseInt64s(k.Strings(delim), true, false) + return vals +} + +// Uints returns list of uint divided by given delimiter. Any invalid input will be treated as zero value. +func (k *Key) Uints(delim string) []uint { + vals, _ := k.getUints(delim, true, false) + return vals +} + +// Uint64s returns list of uint64 divided by given delimiter. Any invalid input will be treated as zero value. +func (k *Key) Uint64s(delim string) []uint64 { + vals, _ := k.getUint64s(delim, true, false) + return vals +} + +// TimesFormat parses with given format and returns list of time.Time divided by given delimiter. +// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC). +func (k *Key) TimesFormat(format, delim string) []time.Time { + vals, _ := k.getTimesFormat(format, delim, true, false) + return vals +} + +// Times parses with RFC3339 format and returns list of time.Time divided by given delimiter. +// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC). +func (k *Key) Times(delim string) []time.Time { + return k.TimesFormat(time.RFC3339, delim) +} + +// ValidFloat64s returns list of float64 divided by given delimiter. If some value is not float, then +// it will not be included to result list. +func (k *Key) ValidFloat64s(delim string) []float64 { + vals, _ := k.getFloat64s(delim, false, false) + return vals +} + +// ValidInts returns list of int divided by given delimiter. If some value is not integer, then it will +// not be included to result list. +func (k *Key) ValidInts(delim string) []int { + vals, _ := k.parseInts(k.Strings(delim), false, false) + return vals +} + +// ValidInt64s returns list of int64 divided by given delimiter. If some value is not 64-bit integer, +// then it will not be included to result list. +func (k *Key) ValidInt64s(delim string) []int64 { + vals, _ := k.parseInt64s(k.Strings(delim), false, false) + return vals +} + +// ValidUints returns list of uint divided by given delimiter. If some value is not unsigned integer, +// then it will not be included to result list. +func (k *Key) ValidUints(delim string) []uint { + vals, _ := k.getUints(delim, false, false) + return vals +} + +// ValidUint64s returns list of uint64 divided by given delimiter. If some value is not 64-bit unsigned +// integer, then it will not be included to result list. +func (k *Key) ValidUint64s(delim string) []uint64 { + vals, _ := k.getUint64s(delim, false, false) + return vals +} + +// ValidTimesFormat parses with given format and returns list of time.Time divided by given delimiter. +func (k *Key) ValidTimesFormat(format, delim string) []time.Time { + vals, _ := k.getTimesFormat(format, delim, false, false) + return vals +} + +// ValidTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter. +func (k *Key) ValidTimes(delim string) []time.Time { + return k.ValidTimesFormat(time.RFC3339, delim) +} + +// StrictFloat64s returns list of float64 divided by given delimiter or error on first invalid input. +func (k *Key) StrictFloat64s(delim string) ([]float64, error) { + return k.getFloat64s(delim, false, true) +} + +// StrictInts returns list of int divided by given delimiter or error on first invalid input. +func (k *Key) StrictInts(delim string) ([]int, error) { + return k.parseInts(k.Strings(delim), false, true) +} + +// StrictInt64s returns list of int64 divided by given delimiter or error on first invalid input. +func (k *Key) StrictInt64s(delim string) ([]int64, error) { + return k.parseInt64s(k.Strings(delim), false, true) +} + +// StrictUints returns list of uint divided by given delimiter or error on first invalid input. +func (k *Key) StrictUints(delim string) ([]uint, error) { + return k.getUints(delim, false, true) +} + +// StrictUint64s returns list of uint64 divided by given delimiter or error on first invalid input. +func (k *Key) StrictUint64s(delim string) ([]uint64, error) { + return k.getUint64s(delim, false, true) +} + +// StrictTimesFormat parses with given format and returns list of time.Time divided by given delimiter +// or error on first invalid input. +func (k *Key) StrictTimesFormat(format, delim string) ([]time.Time, error) { + return k.getTimesFormat(format, delim, false, true) +} + +// StrictTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter +// or error on first invalid input. +func (k *Key) StrictTimes(delim string) ([]time.Time, error) { + return k.StrictTimesFormat(time.RFC3339, delim) +} + +// getFloat64s returns list of float64 divided by given delimiter. +func (k *Key) getFloat64s(delim string, addInvalid, returnOnInvalid bool) ([]float64, error) { + strs := k.Strings(delim) + vals := make([]float64, 0, len(strs)) + for _, str := range strs { + val, err := strconv.ParseFloat(str, 64) + if err != nil && returnOnInvalid { + return nil, err + } + if err == nil || addInvalid { + vals = append(vals, val) + } + } + return vals, nil +} + +// parseInts transforms strings to ints. +func (k *Key) parseInts(strs []string, addInvalid, returnOnInvalid bool) ([]int, error) { + vals := make([]int, 0, len(strs)) + for _, str := range strs { + val, err := strconv.Atoi(str) + if err != nil && returnOnInvalid { + return nil, err + } + if err == nil || addInvalid { + vals = append(vals, val) + } + } + return vals, nil +} + +// parseInt64s transforms strings to int64s. +func (k *Key) parseInt64s(strs []string, addInvalid, returnOnInvalid bool) ([]int64, error) { + vals := make([]int64, 0, len(strs)) + for _, str := range strs { + val, err := strconv.ParseInt(str, 10, 64) + if err != nil && returnOnInvalid { + return nil, err + } + if err == nil || addInvalid { + vals = append(vals, val) + } + } + return vals, nil +} + +// getUints returns list of uint divided by given delimiter. +func (k *Key) getUints(delim string, addInvalid, returnOnInvalid bool) ([]uint, error) { + strs := k.Strings(delim) + vals := make([]uint, 0, len(strs)) + for _, str := range strs { + val, err := strconv.ParseUint(str, 10, 0) + if err != nil && returnOnInvalid { + return nil, err + } + if err == nil || addInvalid { + vals = append(vals, uint(val)) + } + } + return vals, nil +} + +// getUint64s returns list of uint64 divided by given delimiter. +func (k *Key) getUint64s(delim string, addInvalid, returnOnInvalid bool) ([]uint64, error) { + strs := k.Strings(delim) + vals := make([]uint64, 0, len(strs)) + for _, str := range strs { + val, err := strconv.ParseUint(str, 10, 64) + if err != nil && returnOnInvalid { + return nil, err + } + if err == nil || addInvalid { + vals = append(vals, val) + } + } + return vals, nil +} + +// getTimesFormat parses with given format and returns list of time.Time divided by given delimiter. +func (k *Key) getTimesFormat(format, delim string, addInvalid, returnOnInvalid bool) ([]time.Time, error) { + strs := k.Strings(delim) + vals := make([]time.Time, 0, len(strs)) + for _, str := range strs { + val, err := time.Parse(format, str) + if err != nil && returnOnInvalid { + return nil, err + } + if err == nil || addInvalid { + vals = append(vals, val) + } + } + return vals, nil +} + +// SetValue changes key value. +func (k *Key) SetValue(v string) { + if k.s.f.BlockMode { + k.s.f.lock.Lock() + defer k.s.f.lock.Unlock() + } + + k.value = v + k.s.keysHash[k.name] = v +} diff --git a/vendor/github.com/go-ini/ini/parser.go b/vendor/github.com/go-ini/ini/parser.go new file mode 100644 index 0000000..673ef80 --- /dev/null +++ b/vendor/github.com/go-ini/ini/parser.go @@ -0,0 +1,358 @@ +// Copyright 2015 Unknwon +// +// 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. + +package ini + +import ( + "bufio" + "bytes" + "fmt" + "io" + "strconv" + "strings" + "unicode" +) + +type tokenType int + +const ( + _TOKEN_INVALID tokenType = iota + _TOKEN_COMMENT + _TOKEN_SECTION + _TOKEN_KEY +) + +type parser struct { + buf *bufio.Reader + isEOF bool + count int + comment *bytes.Buffer +} + +func newParser(r io.Reader) *parser { + return &parser{ + buf: bufio.NewReader(r), + count: 1, + comment: &bytes.Buffer{}, + } +} + +// BOM handles header of UTF-8, UTF-16 LE and UTF-16 BE's BOM format. +// http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding +func (p *parser) BOM() error { + mask, err := p.buf.Peek(2) + if err != nil && err != io.EOF { + return err + } else if len(mask) < 2 { + return nil + } + + switch { + case mask[0] == 254 && mask[1] == 255: + fallthrough + case mask[0] == 255 && mask[1] == 254: + p.buf.Read(mask) + case mask[0] == 239 && mask[1] == 187: + mask, err := p.buf.Peek(3) + if err != nil && err != io.EOF { + return err + } else if len(mask) < 3 { + return nil + } + if mask[2] == 191 { + p.buf.Read(mask) + } + } + return nil +} + +func (p *parser) readUntil(delim byte) ([]byte, error) { + data, err := p.buf.ReadBytes(delim) + if err != nil { + if err == io.EOF { + p.isEOF = true + } else { + return nil, err + } + } + return data, nil +} + +func cleanComment(in []byte) ([]byte, bool) { + i := bytes.IndexAny(in, "#;") + if i == -1 { + return nil, false + } + return in[i:], true +} + +func readKeyName(in []byte) (string, int, error) { + line := string(in) + + // Check if key name surrounded by quotes. + var keyQuote string + if line[0] == '"' { + if len(line) > 6 && string(line[0:3]) == `"""` { + keyQuote = `"""` + } else { + keyQuote = `"` + } + } else if line[0] == '`' { + keyQuote = "`" + } + + // Get out key name + endIdx := -1 + if len(keyQuote) > 0 { + startIdx := len(keyQuote) + // FIXME: fail case -> """"""name"""=value + pos := strings.Index(line[startIdx:], keyQuote) + if pos == -1 { + return "", -1, fmt.Errorf("missing closing key quote: %s", line) + } + pos += startIdx + + // Find key-value delimiter + i := strings.IndexAny(line[pos+startIdx:], "=:") + if i < 0 { + return "", -1, ErrDelimiterNotFound{line} + } + endIdx = pos + i + return strings.TrimSpace(line[startIdx:pos]), endIdx + startIdx + 1, nil + } + + endIdx = strings.IndexAny(line, "=:") + if endIdx < 0 { + return "", -1, ErrDelimiterNotFound{line} + } + return strings.TrimSpace(line[0:endIdx]), endIdx + 1, nil +} + +func (p *parser) readMultilines(line, val, valQuote string) (string, error) { + for { + data, err := p.readUntil('\n') + if err != nil { + return "", err + } + next := string(data) + + pos := strings.LastIndex(next, valQuote) + if pos > -1 { + val += next[:pos] + + comment, has := cleanComment([]byte(next[pos:])) + if has { + p.comment.Write(bytes.TrimSpace(comment)) + } + break + } + val += next + if p.isEOF { + return "", fmt.Errorf("missing closing key quote from '%s' to '%s'", line, next) + } + } + return val, nil +} + +func (p *parser) readContinuationLines(val string) (string, error) { + for { + data, err := p.readUntil('\n') + if err != nil { + return "", err + } + next := strings.TrimSpace(string(data)) + + if len(next) == 0 { + break + } + val += next + if val[len(val)-1] != '\\' { + break + } + val = val[:len(val)-1] + } + return val, nil +} + +// hasSurroundedQuote check if and only if the first and last characters +// are quotes \" or \'. +// It returns false if any other parts also contain same kind of quotes. +func hasSurroundedQuote(in string, quote byte) bool { + return len(in) > 2 && in[0] == quote && in[len(in)-1] == quote && + strings.IndexByte(in[1:], quote) == len(in)-2 +} + +func (p *parser) readValue(in []byte, ignoreContinuation bool) (string, error) { + line := strings.TrimLeftFunc(string(in), unicode.IsSpace) + if len(line) == 0 { + return "", nil + } + + var valQuote string + if len(line) > 3 && string(line[0:3]) == `"""` { + valQuote = `"""` + } else if line[0] == '`' { + valQuote = "`" + } + + if len(valQuote) > 0 { + startIdx := len(valQuote) + pos := strings.LastIndex(line[startIdx:], valQuote) + // Check for multi-line value + if pos == -1 { + return p.readMultilines(line, line[startIdx:], valQuote) + } + + return line[startIdx : pos+startIdx], nil + } + + // Won't be able to reach here if value only contains whitespace. + line = strings.TrimSpace(line) + + // Check continuation lines when desired. + if !ignoreContinuation && line[len(line)-1] == '\\' { + return p.readContinuationLines(line[:len(line)-1]) + } + + i := strings.IndexAny(line, "#;") + if i > -1 { + p.comment.WriteString(line[i:]) + line = strings.TrimSpace(line[:i]) + } + + // Trim single quotes + if hasSurroundedQuote(line, '\'') || + hasSurroundedQuote(line, '"') { + line = line[1 : len(line)-1] + } + return line, nil +} + +// parse parses data through an io.Reader. +func (f *File) parse(reader io.Reader) (err error) { + p := newParser(reader) + if err = p.BOM(); err != nil { + return fmt.Errorf("BOM: %v", err) + } + + // Ignore error because default section name is never empty string. + section, _ := f.NewSection(DEFAULT_SECTION) + + var line []byte + var inUnparseableSection bool + for !p.isEOF { + line, err = p.readUntil('\n') + if err != nil { + return err + } + + line = bytes.TrimLeftFunc(line, unicode.IsSpace) + if len(line) == 0 { + continue + } + + // Comments + if line[0] == '#' || line[0] == ';' { + // Note: we do not care ending line break, + // it is needed for adding second line, + // so just clean it once at the end when set to value. + p.comment.Write(line) + continue + } + + // Section + if line[0] == '[' { + // Read to the next ']' (TODO: support quoted strings) + // TODO(unknwon): use LastIndexByte when stop supporting Go1.4 + closeIdx := bytes.LastIndex(line, []byte("]")) + if closeIdx == -1 { + return fmt.Errorf("unclosed section: %s", line) + } + + name := string(line[1:closeIdx]) + section, err = f.NewSection(name) + if err != nil { + return err + } + + comment, has := cleanComment(line[closeIdx+1:]) + if has { + p.comment.Write(comment) + } + + section.Comment = strings.TrimSpace(p.comment.String()) + + // Reset aotu-counter and comments + p.comment.Reset() + p.count = 1 + + inUnparseableSection = false + for i := range f.options.UnparseableSections { + if f.options.UnparseableSections[i] == name || + (f.options.Insensitive && strings.ToLower(f.options.UnparseableSections[i]) == strings.ToLower(name)) { + inUnparseableSection = true + continue + } + } + continue + } + + if inUnparseableSection { + section.isRawSection = true + section.rawBody += string(line) + continue + } + + kname, offset, err := readKeyName(line) + if err != nil { + // Treat as boolean key when desired, and whole line is key name. + if IsErrDelimiterNotFound(err) && f.options.AllowBooleanKeys { + kname, err := p.readValue(line, f.options.IgnoreContinuation) + if err != nil { + return err + } + key, err := section.NewBooleanKey(kname) + if err != nil { + return err + } + key.Comment = strings.TrimSpace(p.comment.String()) + p.comment.Reset() + continue + } + return err + } + + // Auto increment. + isAutoIncr := false + if kname == "-" { + isAutoIncr = true + kname = "#" + strconv.Itoa(p.count) + p.count++ + } + + value, err := p.readValue(line[offset:], f.options.IgnoreContinuation) + if err != nil { + return err + } + + key, err := section.NewKey(kname, value) + if err != nil { + return err + } + key.isAutoIncrement = isAutoIncr + key.Comment = strings.TrimSpace(p.comment.String()) + p.comment.Reset() + } + return nil +} diff --git a/vendor/github.com/go-ini/ini/section.go b/vendor/github.com/go-ini/ini/section.go new file mode 100644 index 0000000..c9fa27e --- /dev/null +++ b/vendor/github.com/go-ini/ini/section.go @@ -0,0 +1,234 @@ +// Copyright 2014 Unknwon +// +// 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. + +package ini + +import ( + "errors" + "fmt" + "strings" +) + +// Section represents a config section. +type Section struct { + f *File + Comment string + name string + keys map[string]*Key + keyList []string + keysHash map[string]string + + isRawSection bool + rawBody string +} + +func newSection(f *File, name string) *Section { + return &Section{ + f: f, + name: name, + keys: make(map[string]*Key), + keyList: make([]string, 0, 10), + keysHash: make(map[string]string), + } +} + +// Name returns name of Section. +func (s *Section) Name() string { + return s.name +} + +// Body returns rawBody of Section if the section was marked as unparseable. +// It still follows the other rules of the INI format surrounding leading/trailing whitespace. +func (s *Section) Body() string { + return strings.TrimSpace(s.rawBody) +} + +// NewKey creates a new key to given section. +func (s *Section) NewKey(name, val string) (*Key, error) { + if len(name) == 0 { + return nil, errors.New("error creating new key: empty key name") + } else if s.f.options.Insensitive { + name = strings.ToLower(name) + } + + if s.f.BlockMode { + s.f.lock.Lock() + defer s.f.lock.Unlock() + } + + if inSlice(name, s.keyList) { + if s.f.options.AllowShadows { + if err := s.keys[name].addShadow(val); err != nil { + return nil, err + } + } else { + s.keys[name].value = val + } + return s.keys[name], nil + } + + s.keyList = append(s.keyList, name) + s.keys[name] = newKey(s, name, val) + s.keysHash[name] = val + return s.keys[name], nil +} + +// NewBooleanKey creates a new boolean type key to given section. +func (s *Section) NewBooleanKey(name string) (*Key, error) { + key, err := s.NewKey(name, "true") + if err != nil { + return nil, err + } + + key.isBooleanType = true + return key, nil +} + +// GetKey returns key in section by given name. +func (s *Section) GetKey(name string) (*Key, error) { + // FIXME: change to section level lock? + if s.f.BlockMode { + s.f.lock.RLock() + } + if s.f.options.Insensitive { + name = strings.ToLower(name) + } + key := s.keys[name] + if s.f.BlockMode { + s.f.lock.RUnlock() + } + + if key == nil { + // Check if it is a child-section. + sname := s.name + for { + if i := strings.LastIndex(sname, "."); i > -1 { + sname = sname[:i] + sec, err := s.f.GetSection(sname) + if err != nil { + continue + } + return sec.GetKey(name) + } else { + break + } + } + return nil, fmt.Errorf("error when getting key of section '%s': key '%s' not exists", s.name, name) + } + return key, nil +} + +// HasKey returns true if section contains a key with given name. +func (s *Section) HasKey(name string) bool { + key, _ := s.GetKey(name) + return key != nil +} + +// Haskey is a backwards-compatible name for HasKey. +func (s *Section) Haskey(name string) bool { + return s.HasKey(name) +} + +// HasValue returns true if section contains given raw value. +func (s *Section) HasValue(value string) bool { + if s.f.BlockMode { + s.f.lock.RLock() + defer s.f.lock.RUnlock() + } + + for _, k := range s.keys { + if value == k.value { + return true + } + } + return false +} + +// Key assumes named Key exists in section and returns a zero-value when not. +func (s *Section) Key(name string) *Key { + key, err := s.GetKey(name) + if err != nil { + // It's OK here because the only possible error is empty key name, + // but if it's empty, this piece of code won't be executed. + key, _ = s.NewKey(name, "") + return key + } + return key +} + +// Keys returns list of keys of section. +func (s *Section) Keys() []*Key { + keys := make([]*Key, len(s.keyList)) + for i := range s.keyList { + keys[i] = s.Key(s.keyList[i]) + } + return keys +} + +// ParentKeys returns list of keys of parent section. +func (s *Section) ParentKeys() []*Key { + var parentKeys []*Key + sname := s.name + for { + if i := strings.LastIndex(sname, "."); i > -1 { + sname = sname[:i] + sec, err := s.f.GetSection(sname) + if err != nil { + continue + } + parentKeys = append(parentKeys, sec.Keys()...) + } else { + break + } + + } + return parentKeys +} + +// KeyStrings returns list of key names of section. +func (s *Section) KeyStrings() []string { + list := make([]string, len(s.keyList)) + copy(list, s.keyList) + return list +} + +// KeysHash returns keys hash consisting of names and values. +func (s *Section) KeysHash() map[string]string { + if s.f.BlockMode { + s.f.lock.RLock() + defer s.f.lock.RUnlock() + } + + hash := map[string]string{} + for key, value := range s.keysHash { + hash[key] = value + } + return hash +} + +// DeleteKey deletes a key from section. +func (s *Section) DeleteKey(name string) { + if s.f.BlockMode { + s.f.lock.Lock() + defer s.f.lock.Unlock() + } + + for i, k := range s.keyList { + if k == name { + s.keyList = append(s.keyList[:i], s.keyList[i+1:]...) + delete(s.keys, name) + return + } + } +} diff --git a/vendor/github.com/go-ini/ini/struct.go b/vendor/github.com/go-ini/ini/struct.go index c118437..509c682 100644 --- a/vendor/github.com/go-ini/ini/struct.go +++ b/vendor/github.com/go-ini/ini/struct.go @@ -19,6 +19,7 @@ import ( "errors" "fmt" "reflect" + "strings" "time" "unicode" ) @@ -76,10 +77,69 @@ func parseDelim(actual string) string { var reflectTime = reflect.TypeOf(time.Now()).Kind() +// setSliceWithProperType sets proper values to slice based on its type. +func setSliceWithProperType(key *Key, field reflect.Value, delim string, allowShadow bool) error { + var strs []string + if allowShadow { + strs = key.StringsWithShadows(delim) + } else { + strs = key.Strings(delim) + } + + numVals := len(strs) + if numVals == 0 { + return nil + } + + var vals interface{} + + sliceOf := field.Type().Elem().Kind() + switch sliceOf { + case reflect.String: + vals = strs + case reflect.Int: + vals, _ = key.parseInts(strs, true, false) + case reflect.Int64: + vals, _ = key.parseInt64s(strs, true, false) + case reflect.Uint: + vals = key.Uints(delim) + case reflect.Uint64: + vals = key.Uint64s(delim) + case reflect.Float64: + vals = key.Float64s(delim) + case reflectTime: + vals = key.Times(delim) + default: + return fmt.Errorf("unsupported type '[]%s'", sliceOf) + } + + slice := reflect.MakeSlice(field.Type(), numVals, numVals) + for i := 0; i < numVals; i++ { + switch sliceOf { + case reflect.String: + slice.Index(i).Set(reflect.ValueOf(vals.([]string)[i])) + case reflect.Int: + slice.Index(i).Set(reflect.ValueOf(vals.([]int)[i])) + case reflect.Int64: + slice.Index(i).Set(reflect.ValueOf(vals.([]int64)[i])) + case reflect.Uint: + slice.Index(i).Set(reflect.ValueOf(vals.([]uint)[i])) + case reflect.Uint64: + slice.Index(i).Set(reflect.ValueOf(vals.([]uint64)[i])) + case reflect.Float64: + slice.Index(i).Set(reflect.ValueOf(vals.([]float64)[i])) + case reflectTime: + slice.Index(i).Set(reflect.ValueOf(vals.([]time.Time)[i])) + } + } + field.Set(slice) + return nil +} + // setWithProperType sets proper value to field based on its type, // but it does not return error for failing parsing, // because we want to use default value that is already assigned to strcut. -func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error { +func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string, allowShadow bool) error { switch t.Kind() { case reflect.String: if len(key.String()) == 0 { @@ -94,20 +154,22 @@ func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim stri field.SetBool(boolVal) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: durationVal, err := key.Duration() - if err == nil { + // Skip zero value + if err == nil && int(durationVal) > 0 { field.Set(reflect.ValueOf(durationVal)) return nil } intVal, err := key.Int64() - if err != nil { + if err != nil || intVal == 0 { return nil } field.SetInt(intVal) // byte is an alias for uint8, so supporting uint8 breaks support for byte case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: durationVal, err := key.Duration() - if err == nil { + // Skip zero value + if err == nil && int(durationVal) > 0 { field.Set(reflect.ValueOf(durationVal)) return nil } @@ -118,7 +180,7 @@ func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim stri } field.SetUint(uintVal) - case reflect.Float64: + case reflect.Float32, reflect.Float64: floatVal, err := key.Float64() if err != nil { return nil @@ -131,35 +193,25 @@ func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim stri } field.Set(reflect.ValueOf(timeVal)) case reflect.Slice: - vals := key.Strings(delim) - numVals := len(vals) - if numVals == 0 { - return nil - } - - sliceOf := field.Type().Elem().Kind() - - var times []time.Time - if sliceOf == reflectTime { - times = key.Times(delim) - } - - slice := reflect.MakeSlice(field.Type(), numVals, numVals) - for i := 0; i < numVals; i++ { - switch sliceOf { - case reflectTime: - slice.Index(i).Set(reflect.ValueOf(times[i])) - default: - slice.Index(i).Set(reflect.ValueOf(vals[i])) - } - } - field.Set(slice) + return setSliceWithProperType(key, field, delim, allowShadow) default: return fmt.Errorf("unsupported type '%s'", t) } return nil } +func parseTagOptions(tag string) (rawName string, omitEmpty bool, allowShadow bool) { + opts := strings.SplitN(tag, ",", 3) + rawName = opts[0] + if len(opts) > 1 { + omitEmpty = opts[1] == "omitempty" + } + if len(opts) > 2 { + allowShadow = opts[2] == "allowshadow" + } + return rawName, omitEmpty, allowShadow +} + func (s *Section) mapTo(val reflect.Value) error { if val.Kind() == reflect.Ptr { val = val.Elem() @@ -175,7 +227,8 @@ func (s *Section) mapTo(val reflect.Value) error { continue } - fieldName := s.parseFieldName(tpField.Name, tag) + rawName, _, allowShadow := parseTagOptions(tag) + fieldName := s.parseFieldName(tpField.Name, rawName) if len(fieldName) == 0 || !field.CanSet() { continue } @@ -196,7 +249,8 @@ func (s *Section) mapTo(val reflect.Value) error { } if key, err := s.GetKey(fieldName); err == nil { - if err = setWithProperType(tpField.Type, key, field, parseDelim(tpField.Tag.Get("delim"))); err != nil { + delim := parseDelim(tpField.Tag.Get("delim")) + if err = setWithProperType(tpField.Type, key, field, delim, allowShadow); err != nil { return fmt.Errorf("error mapping field(%s): %v", fieldName, err) } } @@ -238,40 +292,81 @@ func MapTo(v, source interface{}, others ...interface{}) error { return MapToWithMapper(v, nil, source, others...) } -// reflectWithProperType does the opposite thing with setWithProperType. +// reflectSliceWithProperType does the opposite thing as setSliceWithProperType. +func reflectSliceWithProperType(key *Key, field reflect.Value, delim string) error { + slice := field.Slice(0, field.Len()) + if field.Len() == 0 { + return nil + } + + var buf bytes.Buffer + sliceOf := field.Type().Elem().Kind() + for i := 0; i < field.Len(); i++ { + switch sliceOf { + case reflect.String: + buf.WriteString(slice.Index(i).String()) + case reflect.Int, reflect.Int64: + buf.WriteString(fmt.Sprint(slice.Index(i).Int())) + case reflect.Uint, reflect.Uint64: + buf.WriteString(fmt.Sprint(slice.Index(i).Uint())) + case reflect.Float64: + buf.WriteString(fmt.Sprint(slice.Index(i).Float())) + case reflectTime: + buf.WriteString(slice.Index(i).Interface().(time.Time).Format(time.RFC3339)) + default: + return fmt.Errorf("unsupported type '[]%s'", sliceOf) + } + buf.WriteString(delim) + } + key.SetValue(buf.String()[:buf.Len()-1]) + return nil +} + +// reflectWithProperType does the opposite thing as setWithProperType. func reflectWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error { switch t.Kind() { case reflect.String: key.SetValue(field.String()) - case reflect.Bool, - reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, - reflect.Float64, - reflectTime: - key.SetValue(fmt.Sprint(field)) + case reflect.Bool: + key.SetValue(fmt.Sprint(field.Bool())) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + key.SetValue(fmt.Sprint(field.Int())) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: + key.SetValue(fmt.Sprint(field.Uint())) + case reflect.Float32, reflect.Float64: + key.SetValue(fmt.Sprint(field.Float())) + case reflectTime: + key.SetValue(fmt.Sprint(field.Interface().(time.Time).Format(time.RFC3339))) case reflect.Slice: - vals := field.Slice(0, field.Len()) - if field.Len() == 0 { - return nil - } - - var buf bytes.Buffer - isTime := fmt.Sprint(field.Type()) == "[]time.Time" - for i := 0; i < field.Len(); i++ { - if isTime { - buf.WriteString(vals.Index(i).Interface().(time.Time).Format(time.RFC3339)) - } else { - buf.WriteString(fmt.Sprint(vals.Index(i))) - } - buf.WriteString(delim) - } - key.SetValue(buf.String()[:buf.Len()-1]) + return reflectSliceWithProperType(key, field, delim) default: return fmt.Errorf("unsupported type '%s'", t) } return nil } +// CR: copied from encoding/json/encode.go with modifications of time.Time support. +// TODO: add more test coverage. +func isEmptyValue(v reflect.Value) bool { + switch v.Kind() { + case reflect.Array, reflect.Map, reflect.Slice, reflect.String: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflectTime: + return v.Interface().(time.Time).IsZero() + case reflect.Interface, reflect.Ptr: + return v.IsNil() + } + return false +} + func (s *Section) reflectFrom(val reflect.Value) error { if val.Kind() == reflect.Ptr { val = val.Elem() @@ -287,13 +382,18 @@ func (s *Section) reflectFrom(val reflect.Value) error { continue } - fieldName := s.parseFieldName(tpField.Name, tag) + opts := strings.SplitN(tag, ",", 2) + if len(opts) == 2 && opts[1] == "omitempty" && isEmptyValue(field) { + continue + } + + fieldName := s.parseFieldName(tpField.Name, opts[0]) if len(fieldName) == 0 || !field.CanSet() { continue } if (tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous) || - (tpField.Type.Kind() == reflect.Struct) { + (tpField.Type.Kind() == reflect.Struct && tpField.Type.Name() != "Time") { // Note: The only error here is section doesn't exist. sec, err := s.f.GetSection(fieldName) if err != nil { @@ -301,7 +401,7 @@ func (s *Section) reflectFrom(val reflect.Value) error { sec, _ = s.f.NewSection(fieldName) } if err = sec.reflectFrom(field); err != nil { - return fmt.Errorf("error reflecting field(%s): %v", fieldName, err) + return fmt.Errorf("error reflecting field (%s): %v", fieldName, err) } continue } @@ -312,7 +412,7 @@ func (s *Section) reflectFrom(val reflect.Value) error { key, _ = s.NewKey(fieldName, "") } if err = reflectWithProperType(tpField.Type, key, field, parseDelim(tpField.Tag.Get("delim"))); err != nil { - return fmt.Errorf("error reflecting field(%s): %v", fieldName, err) + return fmt.Errorf("error reflecting field (%s): %v", fieldName, err) } } diff --git a/vendor/github.com/hashicorp/go-getter/README.md b/vendor/github.com/hashicorp/go-getter/README.md index 30aed32..4a0b6a6 100644 --- a/vendor/github.com/hashicorp/go-getter/README.md +++ b/vendor/github.com/hashicorp/go-getter/README.md @@ -210,6 +210,12 @@ None a commit SHA, a branch name, etc. If it is a named ref such as a branch name, go-getter will update it to the latest on each get. + * `sshkey` - An SSH private key to use during clones. The provided key must + be a base64-encoded string. For example, to generate a suitable `sshkey` + from a private key file on disk, you would run `base64 -w0 `. + + **Note**: Git 2.3+ is required to use this feature. + ### Mercurial (`hg`) * `rev` - The Mercurial revision to checkout. diff --git a/vendor/github.com/hashicorp/go-getter/client.go b/vendor/github.com/hashicorp/go-getter/client.go index 5a039db..876812a 100644 --- a/vendor/github.com/hashicorp/go-getter/client.go +++ b/vendor/github.com/hashicorp/go-getter/client.go @@ -153,7 +153,7 @@ func (c *Client) Get() error { // We don't appear to... but is it part of the filename? matchingLen := 0 for k, _ := range decompressors { - if strings.HasSuffix(u.Path, k) && len(k) > matchingLen { + if strings.HasSuffix(u.Path, "."+k) && len(k) > matchingLen { archiveV = k matchingLen = len(k) } @@ -222,13 +222,18 @@ func (c *Client) Get() error { checksumValue = b } - // For now, any means file. In the future, we'll ask the getter - // what it thinks it is. if mode == ClientModeAny { - mode = ClientModeFile + // Ask the getter which client mode to use + mode, err = g.ClientMode(u) + if err != nil { + return err + } - // Destination is the base name of the URL path - dst = filepath.Join(dst, filepath.Base(u.Path)) + // Destination is the base name of the URL path in "any" mode when + // a file source is detected. + if mode == ClientModeFile { + dst = filepath.Join(dst, filepath.Base(u.Path)) + } } // If we're not downloading a directory, then just download the file diff --git a/vendor/github.com/hashicorp/go-getter/get.go b/vendor/github.com/hashicorp/go-getter/get.go index cd9a411..c3236f5 100644 --- a/vendor/github.com/hashicorp/go-getter/get.go +++ b/vendor/github.com/hashicorp/go-getter/get.go @@ -35,6 +35,10 @@ type Getter interface { // reference a single file. If possible, the Getter should check if // the remote end contains the same file and no-op this operation. GetFile(string, *url.URL) error + + // ClientMode returns the mode based on the given URL. This is used to + // allow clients to let the getters decide which mode to use. + ClientMode(*url.URL) (ClientMode, error) } // Getters is the mapping of scheme to the Getter implementation that will diff --git a/vendor/github.com/hashicorp/go-getter/get_file.go b/vendor/github.com/hashicorp/go-getter/get_file.go index 341cd0e..e5d2d61 100644 --- a/vendor/github.com/hashicorp/go-getter/get_file.go +++ b/vendor/github.com/hashicorp/go-getter/get_file.go @@ -1,8 +1,32 @@ package getter +import ( + "net/url" + "os" +) + // FileGetter is a Getter implementation that will download a module from // a file scheme. type FileGetter struct { // Copy, if set to true, will copy data instead of using a symlink Copy bool } + +func (g *FileGetter) ClientMode(u *url.URL) (ClientMode, error) { + path := u.Path + if u.RawPath != "" { + path = u.RawPath + } + + fi, err := os.Stat(path) + if err != nil { + return 0, err + } + + // Check if the source is a directory. + if fi.IsDir() { + return ClientModeDir, nil + } + + return ClientModeFile, nil +} diff --git a/vendor/github.com/hashicorp/go-getter/get_file_unix.go b/vendor/github.com/hashicorp/go-getter/get_file_unix.go index 693680a..c89a2d5 100644 --- a/vendor/github.com/hashicorp/go-getter/get_file_unix.go +++ b/vendor/github.com/hashicorp/go-getter/get_file_unix.go @@ -55,7 +55,7 @@ func (g *FileGetter) GetFile(dst string, u *url.URL) error { path = u.RawPath } - // The source path must exist and be a directory to be usable. + // The source path must exist and be a file to be usable. if fi, err := os.Stat(path); err != nil { return fmt.Errorf("source path error: %s", err) } else if fi.IsDir() { diff --git a/vendor/github.com/hashicorp/go-getter/get_git.go b/vendor/github.com/hashicorp/go-getter/get_git.go index 1bf0dc7..0728139 100644 --- a/vendor/github.com/hashicorp/go-getter/get_git.go +++ b/vendor/github.com/hashicorp/go-getter/get_git.go @@ -1,58 +1,105 @@ package getter import ( + "encoding/base64" "fmt" "io/ioutil" "net/url" "os" "os/exec" "path/filepath" + "strings" urlhelper "github.com/hashicorp/go-getter/helper/url" + "github.com/hashicorp/go-version" ) // GitGetter is a Getter implementation that will download a module from // a git repository. type GitGetter struct{} +func (g *GitGetter) ClientMode(_ *url.URL) (ClientMode, error) { + return ClientModeDir, nil +} + func (g *GitGetter) Get(dst string, u *url.URL) error { if _, err := exec.LookPath("git"); err != nil { return fmt.Errorf("git must be available and on the PATH") } // Extract some query parameters we use - var ref string + var ref, sshKey string q := u.Query() if len(q) > 0 { ref = q.Get("ref") q.Del("ref") + sshKey = q.Get("sshkey") + q.Del("sshkey") + // Copy the URL var newU url.URL = *u u = &newU u.RawQuery = q.Encode() } - // First: clone or update the repository + var sshKeyFile string + if sshKey != "" { + // Check that the git version is sufficiently new. + if err := checkGitVersion("2.3"); err != nil { + return fmt.Errorf("Error using ssh key: %v", err) + } + + // We have an SSH key - decode it. + raw, err := base64.StdEncoding.DecodeString(sshKey) + if err != nil { + return err + } + + // Create a temp file for the key and ensure it is removed. + fh, err := ioutil.TempFile("", "go-getter") + if err != nil { + return err + } + sshKeyFile = fh.Name() + defer os.Remove(sshKeyFile) + + // Set the permissions prior to writing the key material. + if err := os.Chmod(sshKeyFile, 0600); err != nil { + return err + } + + // Write the raw key into the temp file. + _, err = fh.Write(raw) + fh.Close() + if err != nil { + return err + } + } + + // Clone or update the repository _, err := os.Stat(dst) if err != nil && !os.IsNotExist(err) { return err } if err == nil { - err = g.update(dst, ref) + err = g.update(dst, sshKeyFile, ref) } else { - err = g.clone(dst, u) + err = g.clone(dst, sshKeyFile, u) } if err != nil { return err } // Next: check out the proper tag/branch if it is specified, and checkout - if ref == "" { - return nil + if ref != "" { + if err := g.checkout(dst, ref); err != nil { + return err + } } - return g.checkout(dst, ref) + // Lastly, download any/all submodules. + return g.fetchSubmodules(dst, sshKeyFile) } // GetFile for Git doesn't support updating at this time. It will download @@ -92,16 +139,18 @@ func (g *GitGetter) checkout(dst string, ref string) error { return getRunCommand(cmd) } -func (g *GitGetter) clone(dst string, u *url.URL) error { +func (g *GitGetter) clone(dst, sshKeyFile string, u *url.URL) error { cmd := exec.Command("git", "clone", u.String(), dst) + setupGitEnv(cmd, sshKeyFile) return getRunCommand(cmd) } -func (g *GitGetter) update(dst string, ref string) error { +func (g *GitGetter) update(dst, sshKeyFile, ref string) error { // Determine if we're a branch. If we're NOT a branch, then we just // switch to master prior to checking out cmd := exec.Command("git", "show-ref", "-q", "--verify", "refs/heads/"+ref) cmd.Dir = dst + if getRunCommand(cmd) != nil { // Not a branch, switch to master. This will also catch non-existent // branches, in which case we want to switch to master and then @@ -116,5 +165,61 @@ func (g *GitGetter) update(dst string, ref string) error { cmd = exec.Command("git", "pull", "--ff-only") cmd.Dir = dst + setupGitEnv(cmd, sshKeyFile) return getRunCommand(cmd) } + +// fetchSubmodules downloads any configured submodules recursively. +func (g *GitGetter) fetchSubmodules(dst, sshKeyFile string) error { + cmd := exec.Command("git", "submodule", "update", "--init", "--recursive") + cmd.Dir = dst + setupGitEnv(cmd, sshKeyFile) + return getRunCommand(cmd) +} + +// setupGitEnv sets up the environment for the given command. This is used to +// pass configuration data to git and ssh and enables advanced cloning methods. +func setupGitEnv(cmd *exec.Cmd, sshKeyFile string) { + var sshOpts []string + + if sshKeyFile != "" { + // We have an SSH key temp file configured, tell ssh about this. + sshOpts = append(sshOpts, "-i", sshKeyFile) + } + + cmd.Env = append(os.Environ(), + // Set the ssh command to use for clones. + "GIT_SSH_COMMAND=ssh "+strings.Join(sshOpts, " "), + ) +} + +// checkGitVersion is used to check the version of git installed on the system +// against a known minimum version. Returns an error if the installed version +// is older than the given minimum. +func checkGitVersion(min string) error { + want, err := version.NewVersion(min) + if err != nil { + return err + } + + out, err := exec.Command("git", "version").Output() + if err != nil { + return err + } + + fields := strings.Fields(string(out)) + if len(fields) != 3 { + return fmt.Errorf("Unexpected 'git version' output: %q", string(out)) + } + + have, err := version.NewVersion(fields[2]) + if err != nil { + return err + } + + if have.LessThan(want) { + return fmt.Errorf("Required git version = %s, have %s", want, have) + } + + return nil +} diff --git a/vendor/github.com/hashicorp/go-getter/get_hg.go b/vendor/github.com/hashicorp/go-getter/get_hg.go index 542bef1..820bdd4 100644 --- a/vendor/github.com/hashicorp/go-getter/get_hg.go +++ b/vendor/github.com/hashicorp/go-getter/get_hg.go @@ -16,6 +16,10 @@ import ( // a Mercurial repository. type HgGetter struct{} +func (g *HgGetter) ClientMode(_ *url.URL) (ClientMode, error) { + return ClientModeDir, nil +} + func (g *HgGetter) Get(dst string, u *url.URL) error { if _, err := exec.LookPath("hg"); err != nil { return fmt.Errorf("hg must be available and on the PATH") diff --git a/vendor/github.com/hashicorp/go-getter/get_http.go b/vendor/github.com/hashicorp/go-getter/get_http.go index d64b238..3c02034 100644 --- a/vendor/github.com/hashicorp/go-getter/get_http.go +++ b/vendor/github.com/hashicorp/go-getter/get_http.go @@ -38,6 +38,13 @@ type HttpGetter struct { Netrc bool } +func (g *HttpGetter) ClientMode(u *url.URL) (ClientMode, error) { + if strings.HasSuffix(u.Path, "/") { + return ClientModeDir, nil + } + return ClientModeFile, nil +} + func (g *HttpGetter) Get(dst string, u *url.URL) error { // Copy the URL so we can modify it var newU url.URL = *u diff --git a/vendor/github.com/hashicorp/go-getter/get_mock.go b/vendor/github.com/hashicorp/go-getter/get_mock.go index a7d3d30..882e694 100644 --- a/vendor/github.com/hashicorp/go-getter/get_mock.go +++ b/vendor/github.com/hashicorp/go-getter/get_mock.go @@ -43,3 +43,10 @@ func (g *MockGetter) GetFile(dst string, u *url.URL) error { } return g.GetFileErr } + +func (g *MockGetter) ClientMode(u *url.URL) (ClientMode, error) { + if l := len(u.Path); l > 0 && u.Path[l-1:] == "/" { + return ClientModeDir, nil + } + return ClientModeFile, nil +} diff --git a/vendor/github.com/hashicorp/go-getter/get_s3.go b/vendor/github.com/hashicorp/go-getter/get_s3.go index bcfcbfc..d3bffeb 100644 --- a/vendor/github.com/hashicorp/go-getter/get_s3.go +++ b/vendor/github.com/hashicorp/go-getter/get_s3.go @@ -20,6 +20,45 @@ import ( // a S3 bucket. type S3Getter struct{} +func (g *S3Getter) ClientMode(u *url.URL) (ClientMode, error) { + // Parse URL + region, bucket, path, _, creds, err := g.parseUrl(u) + if err != nil { + return 0, err + } + + // Create client config + config := g.getAWSConfig(region, creds) + sess := session.New(config) + client := s3.New(sess) + + // List the object(s) at the given prefix + req := &s3.ListObjectsInput{ + Bucket: aws.String(bucket), + Prefix: aws.String(path), + } + resp, err := client.ListObjects(req) + if err != nil { + return 0, err + } + + for _, o := range resp.Contents { + // Use file mode on exact match. + if *o.Key == path { + return ClientModeFile, nil + } + + // Use dir mode if child keys are found. + if strings.HasPrefix(*o.Key, path+"/") { + return ClientModeDir, nil + } + } + + // There was no match, so just return file mode. The download is going + // to fail but we will let S3 return the proper error later. + return ClientModeFile, nil +} + func (g *S3Getter) Get(dst string, u *url.URL) error { // Parse URL region, bucket, path, _, creds, err := g.parseUrl(u) diff --git a/vendor/github.com/hashicorp/go-plugin/client.go b/vendor/github.com/hashicorp/go-plugin/client.go index e559f71..9f8a0f2 100644 --- a/vendor/github.com/hashicorp/go-plugin/client.go +++ b/vendor/github.com/hashicorp/go-plugin/client.go @@ -28,6 +28,7 @@ var Killed uint32 = 0 // This is a slice of the "managed" clients which are cleaned up when // calling Cleanup var managedClients = make([]*Client, 0, 5) +var managedClientsLock sync.Mutex // Error types var ( @@ -130,6 +131,7 @@ func CleanupClients() { // Kill all the managed clients in parallel and use a WaitGroup // to wait for them all to finish up. var wg sync.WaitGroup + managedClientsLock.Lock() for _, client := range managedClients { wg.Add(1) @@ -138,6 +140,7 @@ func CleanupClients() { wg.Done() }(client) } + managedClientsLock.Unlock() log.Println("[DEBUG] plugin: waiting for all plugin processes to complete...") wg.Wait() @@ -173,7 +176,9 @@ func NewClient(config *ClientConfig) (c *Client) { c = &Client{config: config} if config.Managed { + managedClientsLock.Lock() managedClients = append(managedClients, c) + managedClientsLock.Unlock() } return @@ -239,15 +244,58 @@ func (c *Client) Exited() bool { // // This method can safely be called multiple times. func (c *Client) Kill() { - if c.process == nil { + // Grab a lock to read some private fields. + c.l.Lock() + process := c.process + addr := c.address + doneCh := c.doneLogging + c.l.Unlock() + + // If there is no process, we never started anything. Nothing to kill. + if process == nil { return } - // Kill the process - c.process.Kill() + // We need to check for address here. It is possible that the plugin + // started (process != nil) but has no address (addr == nil) if the + // plugin failed at startup. If we do have an address, we need to close + // the plugin net connections. + graceful := false + if addr != nil { + // Close the client to cleanly exit the process. + client, err := c.Client() + if err == nil { + err = client.Close() + + // If there is no error, then we attempt to wait for a graceful + // exit. If there was an error, we assume that graceful cleanup + // won't happen and just force kill. + graceful = err == nil + if err != nil { + // If there was an error just log it. We're going to force + // kill in a moment anyways. + log.Printf( + "[WARN] plugin: error closing client during Kill: %s", err) + } + } + } + + // If we're attempting a graceful exit, then we wait for a short period + // of time to allow that to happen. To wait for this we just wait on the + // doneCh which would be closed if the process exits. + if graceful { + select { + case <-doneCh: + return + case <-time.After(250 * time.Millisecond): + } + } + + // If graceful exiting failed, just kill it + process.Kill() // Wait for the client to finish logging so we have a complete log - <-c.doneLogging + <-doneCh } // Starts the underlying subprocess, communicating with it to negotiate diff --git a/vendor/github.com/hashicorp/go-plugin/rpc_client.go b/vendor/github.com/hashicorp/go-plugin/rpc_client.go index e6d613b..29f9bf0 100644 --- a/vendor/github.com/hashicorp/go-plugin/rpc_client.go +++ b/vendor/github.com/hashicorp/go-plugin/rpc_client.go @@ -76,6 +76,13 @@ func (c *RPCClient) SyncStreams(stdout io.Writer, stderr io.Writer) error { // Close closes the connection. The client is no longer usable after this // is called. func (c *RPCClient) Close() error { + // Call the control channel and ask it to gracefully exit. If this + // errors, then we save it so that we always return an error but we + // want to try to close the other channels anyways. + var empty struct{} + returnErr := c.control.Call("Control.Quit", true, &empty) + + // Close the other streams we have if err := c.control.Close(); err != nil { return err } @@ -85,8 +92,14 @@ func (c *RPCClient) Close() error { if err := c.stderr.Close(); err != nil { return err } + if err := c.broker.Close(); err != nil { + return err + } - return c.broker.Close() + // Return back the error we got from Control.Quit. This is very important + // since we MUST return non-nil error if this fails so that Client.Kill + // will properly try a process.Kill. + return returnErr } func (c *RPCClient) Dispense(name string) (interface{}, error) { diff --git a/vendor/github.com/hashicorp/go-plugin/rpc_server.go b/vendor/github.com/hashicorp/go-plugin/rpc_server.go index 714b047..3984dc8 100644 --- a/vendor/github.com/hashicorp/go-plugin/rpc_server.go +++ b/vendor/github.com/hashicorp/go-plugin/rpc_server.go @@ -7,12 +7,16 @@ import ( "log" "net" "net/rpc" + "sync" "github.com/hashicorp/yamux" ) // RPCServer listens for network connections and then dispenses interface // implementations over net/rpc. +// +// After setting the fields below, they shouldn't be read again directly +// from the structure which may be reading/writing them concurrently. type RPCServer struct { Plugins map[string]Plugin @@ -22,6 +26,12 @@ type RPCServer struct { // make our own custom one we pipe across. Stdout io.Reader Stderr io.Reader + + // DoneCh should be set to a non-nil channel that will be closed + // when the control requests the RPC server to end. + DoneCh chan<- struct{} + + lock sync.Mutex } // Accept accepts connections on a listener and serves requests for @@ -84,6 +94,9 @@ func (s *RPCServer) ServeConn(conn io.ReadWriteCloser) { // Use the control connection to build the dispenser and serve the // connection. server := rpc.NewServer() + server.RegisterName("Control", &controlServer{ + server: s, + }) server.RegisterName("Dispenser", &dispenseServer{ broker: broker, plugins: s.Plugins, @@ -91,6 +104,35 @@ func (s *RPCServer) ServeConn(conn io.ReadWriteCloser) { server.ServeConn(control) } +// done is called internally by the control server to trigger the +// doneCh to close which is listened to by the main process to cleanly +// exit. +func (s *RPCServer) done() { + s.lock.Lock() + defer s.lock.Unlock() + + if s.DoneCh != nil { + close(s.DoneCh) + s.DoneCh = nil + } +} + +// dispenseServer dispenses variousinterface implementations for Terraform. +type controlServer struct { + server *RPCServer +} + +func (c *controlServer) Quit( + null bool, response *struct{}) error { + // End the server + c.server.done() + + // Always return true + *response = struct{}{} + + return nil +} + // dispenseServer dispenses variousinterface implementations for Terraform. type dispenseServer struct { broker *MuxBroker diff --git a/vendor/github.com/hashicorp/go-plugin/server.go b/vendor/github.com/hashicorp/go-plugin/server.go index 4e3a552..b5c5270 100644 --- a/vendor/github.com/hashicorp/go-plugin/server.go +++ b/vendor/github.com/hashicorp/go-plugin/server.go @@ -98,11 +98,15 @@ func Serve(opts *ServeConfig) { } defer listener.Close() + // Create the channel to tell us when we're done + doneCh := make(chan struct{}) + // Create the RPC server to dispense server := &RPCServer{ Plugins: opts.Plugins, Stdout: stdout_r, Stderr: stderr_r, + DoneCh: doneCh, } // Output the address and service name to stdout so that core can bring it up. @@ -134,7 +138,10 @@ func Serve(opts *ServeConfig) { os.Stderr = stderr_w // Serve - server.Accept(listener) + go server.Accept(listener) + + // Wait for the graceful exit + <-doneCh } func serverListener() (net.Listener, error) { @@ -183,5 +190,33 @@ func serverListener_unix() (net.Listener, error) { return nil, err } - return net.Listen("unix", path) + l, err := net.Listen("unix", path) + if err != nil { + return nil, err + } + + // Wrap the listener in rmListener so that the Unix domain socket file + // is removed on close. + return &rmListener{ + Listener: l, + Path: path, + }, nil +} + +// rmListener is an implementation of net.Listener that forwards most +// calls to the listener but also removes a file as part of the close. We +// use this to cleanup the unix domain socket on close. +type rmListener struct { + net.Listener + Path string +} + +func (l *rmListener) Close() error { + // Close the listener itself + if err := l.Listener.Close(); err != nil { + return err + } + + // Remove the file + return os.Remove(l.Path) } diff --git a/vendor/github.com/hashicorp/go-version/README.md b/vendor/github.com/hashicorp/go-version/README.md index 1d50070..6f3a15c 100644 --- a/vendor/github.com/hashicorp/go-version/README.md +++ b/vendor/github.com/hashicorp/go-version/README.md @@ -1,5 +1,5 @@ # Versioning Library for Go -[![Build Status](https://travis-ci.org/hashicorp/go-version.svg?branch=master)](https://travis-ci.org/hashicorp/go-version) +[![Build Status](https://travis-ci.org/hashicorp/go-version.svg?branch=master)](https://travis-ci.org/hashicorp/go-version) go-version is a library for parsing versions and version constraints, and verifying versions against a set of constraints. go-version diff --git a/vendor/github.com/hashicorp/go-version/constraint.go b/vendor/github.com/hashicorp/go-version/constraint.go index 091cfab..8c73df0 100644 --- a/vendor/github.com/hashicorp/go-version/constraint.go +++ b/vendor/github.com/hashicorp/go-version/constraint.go @@ -37,7 +37,7 @@ func init() { } ops := make([]string, 0, len(constraintOperators)) - for k, _ := range constraintOperators { + for k := range constraintOperators { ops = append(ops, regexp.QuoteMeta(k)) } @@ -142,15 +142,37 @@ func constraintLessThanEqual(v, c *Version) bool { } func constraintPessimistic(v, c *Version) bool { + // If the version being checked is naturally less than the constraint, then there + // is no way for the version to be valid against the constraint if v.LessThan(c) { return false } + // We'll use this more than once, so grab the length now so it's a little cleaner + // to write the later checks + cs := len(c.segments) + // If the version being checked has less specificity than the constraint, then there + // is no way for the version to be valid against the constraint + if cs > len(v.segments) { + return false + } + + // Check the segments in the constraint against those in the version. If the version + // being checked, at any point, does not have the same values in each index of the + // constraints segments, then it cannot be valid against the constraint. for i := 0; i < c.si-1; i++ { if v.segments[i] != c.segments[i] { return false } } + // Check the last part of the segment in the constraint. If the version segment at + // this index is less than the constraints segment at this index, then it cannot + // be valid against the constraint + if c.segments[cs-1] > v.segments[cs-1] { + return false + } + + // If nothing has rejected the version by now, it's valid return true } diff --git a/vendor/github.com/hashicorp/go-version/version.go b/vendor/github.com/hashicorp/go-version/version.go index d0e0b0c..ae2f6b6 100644 --- a/vendor/github.com/hashicorp/go-version/version.go +++ b/vendor/github.com/hashicorp/go-version/version.go @@ -14,8 +14,8 @@ var versionRegexp *regexp.Regexp // The raw regular expression string used for testing the validity // of a version. -const VersionRegexpRaw string = `([0-9]+(\.[0-9]+){0,2})` + - `(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + +const VersionRegexpRaw string = `v?([0-9]+(\.[0-9]+)*?)` + + `(-?([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + `(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + `?` @@ -23,7 +23,7 @@ const VersionRegexpRaw string = `([0-9]+(\.[0-9]+){0,2})` + type Version struct { metadata string pre string - segments []int + segments []int64 si int } @@ -38,20 +38,23 @@ func NewVersion(v string) (*Version, error) { if matches == nil { return nil, fmt.Errorf("Malformed version: %s", v) } - segmentsStr := strings.Split(matches[1], ".") - segments := make([]int, len(segmentsStr), 3) + segments := make([]int64, len(segmentsStr)) si := 0 for i, str := range segmentsStr { - val, err := strconv.ParseInt(str, 10, 32) + val, err := strconv.ParseInt(str, 10, 64) if err != nil { return nil, fmt.Errorf( "Error parsing version: %s", err) } - segments[i] = int(val) - si += 1 + segments[i] = int64(val) + si++ } + + // Even though we could support more than three segments, if we + // got less than three, pad it with 0s. This is to cover the basic + // default usecase of semver, which is MAJOR.MINOR.PATCH at the minimum for i := len(segments); i < 3; i++ { segments = append(segments, 0) } @@ -86,8 +89,8 @@ func (v *Version) Compare(other *Version) int { return 0 } - segmentsSelf := v.Segments() - segmentsOther := other.Segments() + segmentsSelf := v.Segments64() + segmentsOther := other.Segments64() // If the segments are the same, we must compare on prerelease info if reflect.DeepEqual(segmentsSelf, segmentsOther) { @@ -106,21 +109,56 @@ func (v *Version) Compare(other *Version) int { return comparePrereleases(preSelf, preOther) } + // Get the highest specificity (hS), or if they're equal, just use segmentSelf length + lenSelf := len(segmentsSelf) + lenOther := len(segmentsOther) + hS := lenSelf + if lenSelf < lenOther { + hS = lenOther + } // Compare the segments - for i := 0; i < len(segmentsSelf); i++ { + // Because a constraint could have more/less specificity than the version it's + // checking, we need to account for a lopsided or jagged comparison + for i := 0; i < hS; i++ { + if i > lenSelf-1 { + // This means Self had the lower specificity + // Check to see if the remaining segments in Other are all zeros + if !allZero(segmentsOther[i:]) { + // if not, it means that Other has to be greater than Self + return -1 + } + break + } else if i > lenOther-1 { + // this means Other had the lower specificity + // Check to see if the remaining segments in Self are all zeros - + if !allZero(segmentsSelf[i:]) { + //if not, it means that Self has to be greater than Other + return 1 + } + break + } lhs := segmentsSelf[i] rhs := segmentsOther[i] - if lhs == rhs { continue } else if lhs < rhs { return -1 - } else { - return 1 } + // Otherwis, rhs was > lhs, they're not equal + return 1 } - panic("should not be reached") + // if we got this far, they're equal + return 0 +} + +func allZero(segs []int64) bool { + for _, s := range segs { + if s != 0 { + return false + } + } + return true } func comparePart(preSelf string, preOther string) int { @@ -226,12 +264,25 @@ func (v *Version) Prerelease() string { return v.pre } -// Segments returns the numeric segments of the version as a slice. +// Segments returns the numeric segments of the version as a slice of ints. // // This excludes any metadata or pre-release information. For example, // for a version "1.2.3-beta", segments will return a slice of // 1, 2, 3. func (v *Version) Segments() []int { + segmentSlice := make([]int, len(v.segments)) + for i, v := range v.segments { + segmentSlice[i] = int(v) + } + return segmentSlice +} + +// Segments64 returns the numeric segments of the version as a slice of int64s. +// +// This excludes any metadata or pre-release information. For example, +// for a version "1.2.3-beta", segments will return a slice of +// 1, 2, 3. +func (v *Version) Segments64() []int64 { return v.segments } @@ -239,7 +290,13 @@ func (v *Version) Segments() []int { // and metadata information. func (v *Version) String() string { var buf bytes.Buffer - fmt.Fprintf(&buf, "%d.%d.%d", v.segments[0], v.segments[1], v.segments[2]) + fmtParts := make([]string, len(v.segments)) + for i, s := range v.segments { + // We can ignore err here since we've pre-parsed the values in segments + str := strconv.FormatInt(s, 10) + fmtParts[i] = str + } + fmt.Fprintf(&buf, strings.Join(fmtParts, ".")) if v.pre != "" { fmt.Fprintf(&buf, "-%s", v.pre) } diff --git a/vendor/github.com/hashicorp/hcl/decoder.go b/vendor/github.com/hashicorp/hcl/decoder.go index c8a077d..0b39c1b 100644 --- a/vendor/github.com/hashicorp/hcl/decoder.go +++ b/vendor/github.com/hashicorp/hcl/decoder.go @@ -91,7 +91,7 @@ func (d *decoder) decode(name string, node ast.Node, result reflect.Value) error return d.decodeBool(name, node, result) case reflect.Float64: return d.decodeFloat(name, node, result) - case reflect.Int: + case reflect.Int, reflect.Int32, reflect.Int64: return d.decodeInt(name, node, result) case reflect.Interface: // When we see an interface, we make our own thing @@ -164,7 +164,11 @@ func (d *decoder) decodeInt(name string, node ast.Node, result reflect.Value) er return err } - result.Set(reflect.ValueOf(int(v))) + if result.Kind() == reflect.Interface { + result.Set(reflect.ValueOf(int(v))) + } else { + result.SetInt(v) + } return nil case token.STRING: v, err := strconv.ParseInt(n.Token.Value().(string), 0, 0) @@ -172,7 +176,11 @@ func (d *decoder) decodeInt(name string, node ast.Node, result reflect.Value) er return err } - result.Set(reflect.ValueOf(int(v))) + if result.Kind() == reflect.Interface { + result.Set(reflect.ValueOf(int(v))) + } else { + result.SetInt(v) + } return nil } } diff --git a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go b/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go index 476ed04..6e54bed 100644 --- a/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go +++ b/vendor/github.com/hashicorp/hcl/hcl/parser/parser.go @@ -346,7 +346,7 @@ func (p *Parser) listType() (*ast.ListType, error) { } } switch tok.Type { - case token.NUMBER, token.FLOAT, token.STRING, token.HEREDOC: + case token.BOOL, token.NUMBER, token.FLOAT, token.STRING, token.HEREDOC: node, err := p.literalType() if err != nil { return nil, err @@ -388,12 +388,16 @@ func (p *Parser) listType() (*ast.ListType, error) { } l.Add(node) needComma = true - case token.BOOL: - // TODO(arslan) should we support? not supported by HCL yet case token.LBRACK: - // TODO(arslan) should we support nested lists? Even though it's - // written in README of HCL, it's not a part of the grammar - // (not defined in parse.y) + node, err := p.listType() + if err != nil { + return nil, &PosError{ + Pos: tok.Pos, + Err: fmt.Errorf( + "error while trying to parse list within list: %s", err), + } + } + l.Add(node) case token.RBRACK: // finished l.Rbrack = p.tok.Pos diff --git a/vendor/github.com/hashicorp/terraform/config/append.go b/vendor/github.com/hashicorp/terraform/config/append.go index a421df4..5f4e89e 100644 --- a/vendor/github.com/hashicorp/terraform/config/append.go +++ b/vendor/github.com/hashicorp/terraform/config/append.go @@ -35,8 +35,13 @@ func Append(c1, c2 *Config) (*Config, error) { c.Atlas = c2.Atlas } - c.Terraform = c1.Terraform - if c2.Terraform != nil { + // merge Terraform blocks + if c1.Terraform != nil { + c.Terraform = c1.Terraform + if c2.Terraform != nil { + c.Terraform.Merge(c2.Terraform) + } + } else { c.Terraform = c2.Terraform } diff --git a/vendor/github.com/hashicorp/terraform/config/config.go b/vendor/github.com/hashicorp/terraform/config/config.go index e1543a1..f944cad 100644 --- a/vendor/github.com/hashicorp/terraform/config/config.go +++ b/vendor/github.com/hashicorp/terraform/config/config.go @@ -9,7 +9,6 @@ import ( "strings" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/go-version" "github.com/hashicorp/hil" "github.com/hashicorp/hil/ast" "github.com/hashicorp/terraform/helper/hilmapstructure" @@ -41,12 +40,6 @@ type Config struct { unknownKeys []string } -// Terraform is the Terraform meta-configuration that can be present -// in configuration files for configuring Terraform itself. -type Terraform struct { - RequiredVersion string `hcl:"required_version"` // Required Terraform version (constraint) -} - // AtlasConfig is the configuration for building in HashiCorp's Atlas. type AtlasConfig struct { Name string @@ -136,6 +129,9 @@ type Provisioner struct { Type string RawConfig *RawConfig ConnInfo *RawConfig + + When ProvisionerWhen + OnFailure ProvisionerOnFailure } // Copy returns a copy of this Provisioner @@ -144,6 +140,8 @@ func (p *Provisioner) Copy() *Provisioner { Type: p.Type, RawConfig: p.RawConfig.Copy(), ConnInfo: p.ConnInfo.Copy(), + When: p.When, + OnFailure: p.OnFailure, } } @@ -213,7 +211,14 @@ func (r *Module) Id() string { // Count returns the count of this resource. func (r *Resource) Count() (int, error) { - v, err := strconv.ParseInt(r.RawCount.Value().(string), 0, 0) + raw := r.RawCount.Value() + count, ok := r.RawCount.Value().(string) + if !ok { + return 0, fmt.Errorf( + "expected count to be a string or int, got %T", raw) + } + + v, err := strconv.ParseInt(count, 0, 0) if err != nil { return 0, err } @@ -248,26 +253,7 @@ func (c *Config) Validate() error { // Validate the Terraform config if tf := c.Terraform; tf != nil { - if raw := tf.RequiredVersion; raw != "" { - // Check that the value has no interpolations - rc, err := NewRawConfig(map[string]interface{}{ - "root": raw, - }) - if err != nil { - errs = append(errs, fmt.Errorf( - "terraform.required_version: %s", err)) - } else if len(rc.Interpolations) > 0 { - errs = append(errs, fmt.Errorf( - "terraform.required_version: cannot contain interpolations")) - } else { - // Check it is valid - _, err := version.NewConstraint(raw) - if err != nil { - errs = append(errs, fmt.Errorf( - "terraform.required_version: invalid syntax: %s", err)) - } - } - } + errs = append(errs, c.Terraform.Validate()...) } vars := c.InterpolatedVariables() @@ -299,8 +285,15 @@ func (c *Config) Validate() error { } interp := false - fn := func(ast.Node) (interface{}, error) { - interp = true + fn := func(n ast.Node) (interface{}, error) { + // LiteralNode is a literal string (outside of a ${ ... } sequence). + // interpolationWalker skips most of these. but in particular it + // visits those that have escaped sequences (like $${foo}) as a + // signal that *some* processing is required on this string. For + // our purposes here though, this is fine and not an interpolation. + if _, ok := n.(*ast.LiteralNode); !ok { + interp = true + } return "", nil } @@ -506,25 +499,22 @@ func (c *Config) Validate() error { "%s: resource count can't reference count variable: %s", n, v.FullKey())) - case *ModuleVariable: - errs = append(errs, fmt.Errorf( - "%s: resource count can't reference module variable: %s", - n, - v.FullKey())) - case *ResourceVariable: - errs = append(errs, fmt.Errorf( - "%s: resource count can't reference resource variable: %s", - n, - v.FullKey())) case *SimpleVariable: errs = append(errs, fmt.Errorf( "%s: resource count can't reference variable: %s", n, v.FullKey())) + + // Good + case *ModuleVariable: + case *ResourceVariable: + case *TerraformVariable: case *UserVariable: - // Good + default: - panic(fmt.Sprintf("Unknown type in count var in %s: %T", n, v)) + errs = append(errs, fmt.Errorf( + "Internal error. Unknown type in count var in %s: %T", + n, v)) } } @@ -553,7 +543,7 @@ func (c *Config) Validate() error { // Validate DependsOn errs = append(errs, c.validateDependsOn(n, r.DependsOn, resources, modules)...) - // Verify provisioners don't contain any splats + // Verify provisioners for _, p := range r.Provisioners { // This validation checks that there are now splat variables // referencing ourself. This currently is not allowed. @@ -585,6 +575,17 @@ func (c *Config) Validate() error { break } } + + // Check for invalid when/onFailure values, though this should be + // picked up by the loader we check here just in case. + if p.When == ProvisionerWhenInvalid { + errs = append(errs, fmt.Errorf( + "%s: provisioner 'when' value is invalid", n)) + } + if p.OnFailure == ProvisionerOnFailureInvalid { + errs = append(errs, fmt.Errorf( + "%s: provisioner 'on_failure' value is invalid", n)) + } } // Verify ignore_changes contains valid entries diff --git a/vendor/github.com/hashicorp/terraform/config/config_string.go b/vendor/github.com/hashicorp/terraform/config/config_string.go index f11290e..0b3abbc 100644 --- a/vendor/github.com/hashicorp/terraform/config/config_string.go +++ b/vendor/github.com/hashicorp/terraform/config/config_string.go @@ -50,6 +50,26 @@ func (c *Config) TestString() string { return strings.TrimSpace(buf.String()) } +func terraformStr(t *Terraform) string { + result := "" + + if b := t.Backend; b != nil { + result += fmt.Sprintf("backend (%s)\n", b.Type) + + keys := make([]string, 0, len(b.RawConfig.Raw)) + for k, _ := range b.RawConfig.Raw { + keys = append(keys, k) + } + sort.Strings(keys) + + for _, k := range keys { + result += fmt.Sprintf(" %s\n", k) + } + } + + return strings.TrimSpace(result) +} + func modulesStr(ms []*Module) string { result := "" order := make([]int, 0, len(ms)) @@ -214,7 +234,16 @@ func resourcesStr(rs []*Resource) string { if len(r.Provisioners) > 0 { result += fmt.Sprintf(" provisioners\n") for _, p := range r.Provisioners { - result += fmt.Sprintf(" %s\n", p.Type) + when := "" + if p.When != ProvisionerWhenCreate { + when = fmt.Sprintf(" (%s)", p.When.String()) + } + + result += fmt.Sprintf(" %s%s\n", p.Type, when) + + if p.OnFailure != ProvisionerOnFailureFail { + result += fmt.Sprintf(" on_failure = %s\n", p.OnFailure.String()) + } ks := make([]string, 0, len(p.RawConfig.Raw)) for k, _ := range p.RawConfig.Raw { diff --git a/vendor/github.com/hashicorp/terraform/config/config_terraform.go b/vendor/github.com/hashicorp/terraform/config/config_terraform.go new file mode 100644 index 0000000..8535c96 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/config/config_terraform.go @@ -0,0 +1,117 @@ +package config + +import ( + "fmt" + "strings" + + "github.com/hashicorp/go-version" + "github.com/mitchellh/hashstructure" +) + +// Terraform is the Terraform meta-configuration that can be present +// in configuration files for configuring Terraform itself. +type Terraform struct { + RequiredVersion string `hcl:"required_version"` // Required Terraform version (constraint) + Backend *Backend // See Backend struct docs +} + +// Validate performs the validation for just the Terraform configuration. +func (t *Terraform) Validate() []error { + var errs []error + + if raw := t.RequiredVersion; raw != "" { + // Check that the value has no interpolations + rc, err := NewRawConfig(map[string]interface{}{ + "root": raw, + }) + if err != nil { + errs = append(errs, fmt.Errorf( + "terraform.required_version: %s", err)) + } else if len(rc.Interpolations) > 0 { + errs = append(errs, fmt.Errorf( + "terraform.required_version: cannot contain interpolations")) + } else { + // Check it is valid + _, err := version.NewConstraint(raw) + if err != nil { + errs = append(errs, fmt.Errorf( + "terraform.required_version: invalid syntax: %s", err)) + } + } + } + + if t.Backend != nil { + errs = append(errs, t.Backend.Validate()...) + } + + return errs +} + +// Merge t with t2. +// Any conflicting fields are overwritten by t2. +func (t *Terraform) Merge(t2 *Terraform) { + if t2.RequiredVersion != "" { + t.RequiredVersion = t2.RequiredVersion + } + + if t2.Backend != nil { + t.Backend = t2.Backend + } +} + +// Backend is the configuration for the "backend" to use with Terraform. +// A backend is responsible for all major behavior of Terraform's core. +// The abstraction layer above the core (the "backend") allows for behavior +// such as remote operation. +type Backend struct { + Type string + RawConfig *RawConfig + + // Hash is a unique hash code representing the original configuration + // of the backend. This won't be recomputed unless Rehash is called. + Hash uint64 +} + +// Rehash returns a unique content hash for this backend's configuration +// as a uint64 value. +func (b *Backend) Rehash() uint64 { + // If we have no backend, the value is zero + if b == nil { + return 0 + } + + // Use hashstructure to hash only our type with the config. + code, err := hashstructure.Hash(map[string]interface{}{ + "type": b.Type, + "config": b.RawConfig.Raw, + }, nil) + + // This should never happen since we have just some basic primitives + // so panic if there is an error. + if err != nil { + panic(err) + } + + return code +} + +func (b *Backend) Validate() []error { + if len(b.RawConfig.Interpolations) > 0 { + return []error{fmt.Errorf(strings.TrimSpace(errBackendInterpolations))} + } + + return nil +} + +const errBackendInterpolations = ` +terraform.backend: configuration cannot contain interpolations + +The backend configuration is loaded by Terraform extremely early, before +the core of Terraform can be initialized. This is necessary because the backend +dictates the behavior of that core. The core is what handles interpolation +processing. Because of this, interpolations cannot be used in backend +configuration. + +If you'd like to parameterize backend configuration, we recommend using +partial configuration with the "-backend-config" flag to "terraform init". +` diff --git a/vendor/github.com/hashicorp/terraform/config/interpolate.go b/vendor/github.com/hashicorp/terraform/config/interpolate.go index 5867c63..bbb3555 100644 --- a/vendor/github.com/hashicorp/terraform/config/interpolate.go +++ b/vendor/github.com/hashicorp/terraform/config/interpolate.go @@ -84,6 +84,13 @@ type SimpleVariable struct { Key string } +// TerraformVariable is a "terraform."-prefixed variable used to access +// metadata about the Terraform run. +type TerraformVariable struct { + Field string + key string +} + // A UserVariable is a variable that is referencing a user variable // that is inputted from outside the configuration. This looks like // "${var.foo}" @@ -101,6 +108,8 @@ func NewInterpolatedVariable(v string) (InterpolatedVariable, error) { return NewPathVariable(v) } else if strings.HasPrefix(v, "self.") { return NewSelfVariable(v) + } else if strings.HasPrefix(v, "terraform.") { + return NewTerraformVariable(v) } else if strings.HasPrefix(v, "var.") { return NewUserVariable(v) } else if strings.HasPrefix(v, "module.") { @@ -278,6 +287,22 @@ func (v *SimpleVariable) GoString() string { return fmt.Sprintf("*%#v", *v) } +func NewTerraformVariable(key string) (*TerraformVariable, error) { + field := key[len("terraform."):] + return &TerraformVariable{ + Field: field, + key: key, + }, nil +} + +func (v *TerraformVariable) FullKey() string { + return v.key +} + +func (v *TerraformVariable) GoString() string { + return fmt.Sprintf("*%#v", *v) +} + func NewUserVariable(key string) (*UserVariable, error) { name := key[len("var."):] elem := "" diff --git a/vendor/github.com/hashicorp/terraform/config/interpolate_funcs.go b/vendor/github.com/hashicorp/terraform/config/interpolate_funcs.go index c7bcafc..cc09e38 100644 --- a/vendor/github.com/hashicorp/terraform/config/interpolate_funcs.go +++ b/vendor/github.com/hashicorp/terraform/config/interpolate_funcs.go @@ -11,6 +11,7 @@ import ( "io/ioutil" "math" "net" + "path/filepath" "regexp" "sort" "strconv" @@ -52,6 +53,7 @@ func listVariableValueToStringSlice(values []ast.Variable) ([]string, error) { // Funcs is the mapping of built-in functions for configuration. func Funcs() map[string]ast.Function { return map[string]ast.Function{ + "basename": interpolationFuncBasename(), "base64decode": interpolationFuncBase64Decode(), "base64encode": interpolationFuncBase64Encode(), "base64sha256": interpolationFuncBase64Sha256(), @@ -62,6 +64,7 @@ func Funcs() map[string]ast.Function { "coalesce": interpolationFuncCoalesce(), "compact": interpolationFuncCompact(), "concat": interpolationFuncConcat(), + "dirname": interpolationFuncDirname(), "distinct": interpolationFuncDistinct(), "element": interpolationFuncElement(), "file": interpolationFuncFile(), @@ -79,13 +82,16 @@ func Funcs() map[string]ast.Function { "md5": interpolationFuncMd5(), "merge": interpolationFuncMerge(), "min": interpolationFuncMin(), + "pathexpand": interpolationFuncPathExpand(), "uuid": interpolationFuncUUID(), "replace": interpolationFuncReplace(), "sha1": interpolationFuncSha1(), "sha256": interpolationFuncSha256(), "signum": interpolationFuncSignum(), + "slice": interpolationFuncSlice(), "sort": interpolationFuncSort(), "split": interpolationFuncSplit(), + "substr": interpolationFuncSubstr(), "timestamp": interpolationFuncTimestamp(), "title": interpolationFuncTitle(), "trimspace": interpolationFuncTrimSpace(), @@ -431,6 +437,17 @@ func interpolationFuncMin() ast.Function { } } +// interpolationFuncPathExpand will expand any `~`'s found with the full file path +func interpolationFuncPathExpand() ast.Function { + return ast.Function{ + ArgTypes: []ast.Type{ast.TypeString}, + ReturnType: ast.TypeString, + Callback: func(args []interface{}) (interface{}, error) { + return homedir.Expand(args[0].(string)) + }, + } +} + // interpolationFuncCeil returns the the least integer value greater than or equal to the argument func interpolationFuncCeil() ast.Function { return ast.Function{ @@ -586,6 +603,17 @@ func interpolationFuncIndex() ast.Function { } } +// interpolationFuncBasename implements the "dirname" function. +func interpolationFuncDirname() ast.Function { + return ast.Function{ + ArgTypes: []ast.Type{ast.TypeString}, + ReturnType: ast.TypeString, + Callback: func(args []interface{}) (interface{}, error) { + return filepath.Dir(args[0].(string)), nil + }, + } +} + // interpolationFuncDistinct implements the "distinct" function that // removes duplicate elements from a list. func interpolationFuncDistinct() ast.Function { @@ -781,6 +809,42 @@ func interpolationFuncSignum() ast.Function { } } +// interpolationFuncSlice returns a portion of the input list between from, inclusive and to, exclusive. +func interpolationFuncSlice() ast.Function { + return ast.Function{ + ArgTypes: []ast.Type{ + ast.TypeList, // inputList + ast.TypeInt, // from + ast.TypeInt, // to + }, + ReturnType: ast.TypeList, + Variadic: false, + Callback: func(args []interface{}) (interface{}, error) { + inputList := args[0].([]ast.Variable) + from := args[1].(int) + to := args[2].(int) + + if from < 0 { + return nil, fmt.Errorf("from index must be >= 0") + } + if to > len(inputList) { + return nil, fmt.Errorf("to index must be <= length of the input list") + } + if from > to { + return nil, fmt.Errorf("from index must be <= to index") + } + + var outputList []ast.Variable + for i, val := range inputList { + if i >= from && i < to { + outputList = append(outputList, val) + } + } + return outputList, nil + }, + } +} + // interpolationFuncSort sorts a list of a strings lexographically func interpolationFuncSort() ast.Function { return ast.Function{ @@ -956,6 +1020,17 @@ func interpolationFuncValues(vs map[string]ast.Variable) ast.Function { } } +// interpolationFuncBasename implements the "basename" function. +func interpolationFuncBasename() ast.Function { + return ast.Function{ + ArgTypes: []ast.Type{ast.TypeString}, + ReturnType: ast.TypeString, + Callback: func(args []interface{}) (interface{}, error) { + return filepath.Base(args[0].(string)), nil + }, + } +} + // interpolationFuncBase64Encode implements the "base64encode" function that // allows Base64 encoding. func interpolationFuncBase64Encode() ast.Function { @@ -1134,3 +1209,48 @@ func interpolationFuncTitle() ast.Function { }, } } + +// interpolationFuncSubstr implements the "substr" function that allows strings +// to be truncated. +func interpolationFuncSubstr() ast.Function { + return ast.Function{ + ArgTypes: []ast.Type{ + ast.TypeString, // input string + ast.TypeInt, // offset + ast.TypeInt, // length + }, + ReturnType: ast.TypeString, + Callback: func(args []interface{}) (interface{}, error) { + str := args[0].(string) + offset := args[1].(int) + length := args[2].(int) + + // Interpret a negative offset as being equivalent to a positive + // offset taken from the end of the string. + if offset < 0 { + offset += len(str) + } + + // Interpret a length of `-1` as indicating that the substring + // should start at `offset` and continue until the end of the + // string. Any other negative length (other than `-1`) is invalid. + if length == -1 { + length = len(str) + } else if length >= 0 { + length += offset + } else { + return nil, fmt.Errorf("length should be a non-negative integer") + } + + if offset > len(str) { + return nil, fmt.Errorf("offset cannot be larger than the length of the string") + } + + if length > len(str) { + return nil, fmt.Errorf("'offset + length' cannot be larger than the length of the string") + } + + return str[offset:length], nil + }, + } +} diff --git a/vendor/github.com/hashicorp/terraform/config/interpolate_walk.go b/vendor/github.com/hashicorp/terraform/config/interpolate_walk.go index 81fa812..ead3d10 100644 --- a/vendor/github.com/hashicorp/terraform/config/interpolate_walk.go +++ b/vendor/github.com/hashicorp/terraform/config/interpolate_walk.go @@ -206,6 +206,12 @@ func (w *interpolationWalker) Primitive(v reflect.Value) error { } func (w *interpolationWalker) replaceCurrent(v reflect.Value) { + // if we don't have at least 2 values, we're not going to find a map, but + // we could panic. + if len(w.cs) < 2 { + return + } + c := w.cs[len(w.cs)-2] switch c.Kind() { case reflect.Map: diff --git a/vendor/github.com/hashicorp/terraform/config/loader_hcl.go b/vendor/github.com/hashicorp/terraform/config/loader_hcl.go index 88f6fd0..a40ad5b 100644 --- a/vendor/github.com/hashicorp/terraform/config/loader_hcl.go +++ b/vendor/github.com/hashicorp/terraform/config/loader_hcl.go @@ -209,6 +209,27 @@ func loadTerraformHcl(list *ast.ObjectList) (*Terraform, error) { // Get our one item item := list.Items[0] + // This block should have an empty top level ObjectItem. If there are keys + // here, it's likely because we have a flattened JSON object, and we can + // lift this into a nested ObjectList to decode properly. + if len(item.Keys) > 0 { + item = &ast.ObjectItem{ + Val: &ast.ObjectType{ + List: &ast.ObjectList{ + Items: []*ast.ObjectItem{item}, + }, + }, + } + } + + // We need the item value as an ObjectList + var listVal *ast.ObjectList + if ot, ok := item.Val.(*ast.ObjectType); ok { + listVal = ot.List + } else { + return nil, fmt.Errorf("terraform block: should be an object") + } + // NOTE: We purposely don't validate unknown HCL keys here so that // we can potentially read _future_ Terraform version config (to // still be able to validate the required version). @@ -223,9 +244,62 @@ func loadTerraformHcl(list *ast.ObjectList) (*Terraform, error) { err) } + // If we have provisioners, then parse those out + if os := listVal.Filter("backend"); len(os.Items) > 0 { + var err error + config.Backend, err = loadTerraformBackendHcl(os) + if err != nil { + return nil, fmt.Errorf( + "Error reading backend config for terraform block: %s", + err) + } + } + return &config, nil } +// Loads the Backend configuration from an object list. +func loadTerraformBackendHcl(list *ast.ObjectList) (*Backend, error) { + if len(list.Items) > 1 { + return nil, fmt.Errorf("only one 'backend' block allowed") + } + + // Get our one item + item := list.Items[0] + + // Verify the keys + if len(item.Keys) != 1 { + return nil, fmt.Errorf( + "position %s: 'backend' must be followed by exactly one string: a type", + item.Pos()) + } + + typ := item.Keys[0].Token.Value().(string) + + // Decode the raw config + var config map[string]interface{} + if err := hcl.DecodeObject(&config, item.Val); err != nil { + return nil, fmt.Errorf( + "Error reading backend config: %s", + err) + } + + rawConfig, err := NewRawConfig(config) + if err != nil { + return nil, fmt.Errorf( + "Error reading backend config: %s", + err) + } + + b := &Backend{ + Type: typ, + RawConfig: rawConfig, + } + b.Hash = b.Rehash() + + return b, nil +} + // Given a handle to a HCL object, this transforms it into the Atlas // configuration. func loadAtlasHcl(list *ast.ObjectList) (*AtlasConfig, error) { @@ -849,8 +923,40 @@ func loadProvisionersHcl(list *ast.ObjectList, connInfo map[string]interface{}) return nil, err } - // Delete the "connection" section, handle separately + // Parse the "when" value + when := ProvisionerWhenCreate + if v, ok := config["when"]; ok { + switch v { + case "create": + when = ProvisionerWhenCreate + case "destroy": + when = ProvisionerWhenDestroy + default: + return nil, fmt.Errorf( + "position %s: 'provisioner' when must be 'create' or 'destroy'", + item.Pos()) + } + } + + // Parse the "on_failure" value + onFailure := ProvisionerOnFailureFail + if v, ok := config["on_failure"]; ok { + switch v { + case "continue": + onFailure = ProvisionerOnFailureContinue + case "fail": + onFailure = ProvisionerOnFailureFail + default: + return nil, fmt.Errorf( + "position %s: 'provisioner' on_failure must be 'continue' or 'fail'", + item.Pos()) + } + } + + // Delete fields we special case delete(config, "connection") + delete(config, "when") + delete(config, "on_failure") rawConfig, err := NewRawConfig(config) if err != nil { @@ -889,6 +995,8 @@ func loadProvisionersHcl(list *ast.ObjectList, connInfo map[string]interface{}) Type: n, RawConfig: rawConfig, ConnInfo: connRaw, + When: when, + OnFailure: onFailure, }) } diff --git a/vendor/github.com/hashicorp/terraform/config/merge.go b/vendor/github.com/hashicorp/terraform/config/merge.go index 2e76865..db214be 100644 --- a/vendor/github.com/hashicorp/terraform/config/merge.go +++ b/vendor/github.com/hashicorp/terraform/config/merge.go @@ -32,9 +32,13 @@ func Merge(c1, c2 *Config) (*Config, error) { c.Atlas = c2.Atlas } - // Merge the Terraform configuration, which is a complete overwrite. - c.Terraform = c1.Terraform - if c2.Terraform != nil { + // Merge the Terraform configuration + if c1.Terraform != nil { + c.Terraform = c1.Terraform + if c2.Terraform != nil { + c.Terraform.Merge(c2.Terraform) + } + } else { c.Terraform = c2.Terraform } diff --git a/vendor/github.com/hashicorp/terraform/config/module/inode.go b/vendor/github.com/hashicorp/terraform/config/module/inode.go index b9be7e3..8603ee2 100644 --- a/vendor/github.com/hashicorp/terraform/config/module/inode.go +++ b/vendor/github.com/hashicorp/terraform/config/module/inode.go @@ -1,4 +1,4 @@ -// +build linux darwin openbsd solaris +// +build linux darwin openbsd netbsd solaris package module diff --git a/vendor/github.com/hashicorp/terraform/config/module/testing.go b/vendor/github.com/hashicorp/terraform/config/module/testing.go new file mode 100644 index 0000000..fc9e733 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/config/module/testing.go @@ -0,0 +1,38 @@ +package module + +import ( + "io/ioutil" + "os" + "testing" + + "github.com/hashicorp/go-getter" +) + +// TestTree loads a module at the given path and returns the tree as well +// as a function that should be deferred to clean up resources. +func TestTree(t *testing.T, path string) (*Tree, func()) { + // Create a temporary directory for module storage + dir, err := ioutil.TempDir("", "tf") + if err != nil { + t.Fatalf("err: %s", err) + return nil, nil + } + + // Load the module + mod, err := NewTreeModule("", path) + if err != nil { + t.Fatalf("err: %s", err) + return nil, nil + } + + // Get the child modules + s := &getter.FolderStorage{StorageDir: dir} + if err := mod.Load(s, GetModeGet); err != nil { + t.Fatalf("err: %s", err) + return nil, nil + } + + return mod, func() { + os.RemoveAll(dir) + } +} diff --git a/vendor/github.com/hashicorp/terraform/config/module/tree.go b/vendor/github.com/hashicorp/terraform/config/module/tree.go index 777389b..b6f90fd 100644 --- a/vendor/github.com/hashicorp/terraform/config/module/tree.go +++ b/vendor/github.com/hashicorp/terraform/config/module/tree.go @@ -259,19 +259,26 @@ func (t *Tree) Validate() error { } // If something goes wrong, here is our error template - newErr := &TreeError{Name: []string{t.Name()}} + newErr := &treeError{Name: []string{t.Name()}} + + // Terraform core does not handle root module children named "root". + // We plan to fix this in the future but this bug was brought up in + // the middle of a release and we don't want to introduce wide-sweeping + // changes at that time. + if len(t.path) == 1 && t.name == "root" { + return fmt.Errorf("root module cannot contain module named 'root'") + } // Validate our configuration first. if err := t.config.Validate(); err != nil { - newErr.Err = err - return newErr + newErr.Add(err) } // If we're the root, we do extra validation. This validation usually // requires the entire tree (since children don't have parent pointers). if len(t.path) == 0 { if err := t.validateProviderAlias(); err != nil { - return err + newErr.Add(err) } } @@ -285,7 +292,7 @@ func (t *Tree) Validate() error { continue } - verr, ok := err.(*TreeError) + verr, ok := err.(*treeError) if !ok { // Unknown error, just return... return err @@ -293,7 +300,7 @@ func (t *Tree) Validate() error { // Append ourselves to the error and then return verr.Name = append(verr.Name, t.Name()) - return verr + newErr.AddChild(verr) } // Go over all the modules and verify that any parameters are valid @@ -319,10 +326,9 @@ func (t *Tree) Validate() error { // Compare to the keys in our raw config for the module for k, _ := range m.RawConfig.Raw { if _, ok := varMap[k]; !ok { - newErr.Err = fmt.Errorf( + newErr.Add(fmt.Errorf( "module %s: %s is not a valid parameter", - m.Name, k) - return newErr + m.Name, k)) } // Remove the required @@ -331,10 +337,9 @@ func (t *Tree) Validate() error { // If we have any required left over, they aren't set. for k, _ := range requiredMap { - newErr.Err = fmt.Errorf( - "module %s: required variable %s not set", - m.Name, k) - return newErr + newErr.Add(fmt.Errorf( + "module %s: required variable %q not set", + m.Name, k)) } } @@ -349,8 +354,10 @@ func (t *Tree) Validate() error { tree, ok := children[mv.Name] if !ok { - // This should never happen because Load watches us - panic("module not found in children: " + mv.Name) + newErr.Add(fmt.Errorf( + "%s: undefined module referenced %s", + source, mv.Name)) + continue } found := false @@ -361,33 +368,61 @@ func (t *Tree) Validate() error { } } if !found { - newErr.Err = fmt.Errorf( + newErr.Add(fmt.Errorf( "%s: %s is not a valid output for module %s", - source, mv.Field, mv.Name) - return newErr + source, mv.Field, mv.Name)) } } } - return nil + return newErr.ErrOrNil() +} + +// treeError is an error use by Tree.Validate to accumulates all +// validation errors. +type treeError struct { + Name []string + Errs []error + Children []*treeError +} + +func (e *treeError) Add(err error) { + e.Errs = append(e.Errs, err) +} + +func (e *treeError) AddChild(err *treeError) { + e.Children = append(e.Children, err) } -// TreeError is an error returned by Tree.Validate if an error occurs -// with validation. -type TreeError struct { - Name []string - Err error +func (e *treeError) ErrOrNil() error { + if len(e.Errs) > 0 || len(e.Children) > 0 { + return e + } + return nil } -func (e *TreeError) Error() string { - // Build up the name - var buf bytes.Buffer - for _, n := range e.Name { - buf.WriteString(n) - buf.WriteString(".") +func (e *treeError) Error() string { + name := strings.Join(e.Name, ".") + var out bytes.Buffer + fmt.Fprintf(&out, "module %s: ", name) + + if len(e.Errs) == 1 { + // single like error + out.WriteString(e.Errs[0].Error()) + } else { + // multi-line error + for _, err := range e.Errs { + fmt.Fprintf(&out, "\n %s", err) + } + } + + if len(e.Children) > 0 { + // start the next error on a new line + out.WriteString("\n ") + } + for _, child := range e.Children { + out.WriteString(child.Error()) } - buf.Truncate(buf.Len() - 1) - // Format the value - return fmt.Sprintf("module %s: %s", buf.String(), e.Err) + return out.String() } diff --git a/vendor/github.com/hashicorp/terraform/config/provisioner_enums.go b/vendor/github.com/hashicorp/terraform/config/provisioner_enums.go new file mode 100644 index 0000000..00fd43f --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/config/provisioner_enums.go @@ -0,0 +1,40 @@ +package config + +// ProvisionerWhen is an enum for valid values for when to run provisioners. +type ProvisionerWhen int + +const ( + ProvisionerWhenInvalid ProvisionerWhen = iota + ProvisionerWhenCreate + ProvisionerWhenDestroy +) + +var provisionerWhenStrs = map[ProvisionerWhen]string{ + ProvisionerWhenInvalid: "invalid", + ProvisionerWhenCreate: "create", + ProvisionerWhenDestroy: "destroy", +} + +func (v ProvisionerWhen) String() string { + return provisionerWhenStrs[v] +} + +// ProvisionerOnFailure is an enum for valid values for on_failure options +// for provisioners. +type ProvisionerOnFailure int + +const ( + ProvisionerOnFailureInvalid ProvisionerOnFailure = iota + ProvisionerOnFailureContinue + ProvisionerOnFailureFail +) + +var provisionerOnFailureStrs = map[ProvisionerOnFailure]string{ + ProvisionerOnFailureInvalid: "invalid", + ProvisionerOnFailureContinue: "continue", + ProvisionerOnFailureFail: "fail", +} + +func (v ProvisionerOnFailure) String() string { + return provisionerOnFailureStrs[v] +} diff --git a/vendor/github.com/hashicorp/terraform/config/resource_mode_string.go b/vendor/github.com/hashicorp/terraform/config/resource_mode_string.go index 930645f..ea68b4f 100644 --- a/vendor/github.com/hashicorp/terraform/config/resource_mode_string.go +++ b/vendor/github.com/hashicorp/terraform/config/resource_mode_string.go @@ -1,4 +1,4 @@ -// Code generated by "stringer -type=ResourceMode -output=resource_mode_string.go resource_mode.go"; DO NOT EDIT +// Code generated by "stringer -type=ResourceMode -output=resource_mode_string.go resource_mode.go"; DO NOT EDIT. package config diff --git a/vendor/github.com/hashicorp/terraform/dag/dag.go b/vendor/github.com/hashicorp/terraform/dag/dag.go index ed7d77e..f8776bc 100644 --- a/vendor/github.com/hashicorp/terraform/dag/dag.go +++ b/vendor/github.com/hashicorp/terraform/dag/dag.go @@ -2,11 +2,8 @@ package dag import ( "fmt" - "log" "sort" "strings" - "sync" - "time" "github.com/hashicorp/go-multierror" ) @@ -169,94 +166,9 @@ func (g *AcyclicGraph) Cycles() [][]Vertex { func (g *AcyclicGraph) Walk(cb WalkFunc) error { defer g.debug.BeginOperation(typeWalk, "").End("") - // Cache the vertices since we use it multiple times - vertices := g.Vertices() - - // Build the waitgroup that signals when we're done - var wg sync.WaitGroup - wg.Add(len(vertices)) - doneCh := make(chan struct{}) - go func() { - defer close(doneCh) - wg.Wait() - }() - - // The map of channels to watch to wait for vertices to finish - vertMap := make(map[Vertex]chan struct{}) - for _, v := range vertices { - vertMap[v] = make(chan struct{}) - } - - // The map of whether a vertex errored or not during the walk - var errLock sync.Mutex - var errs error - errMap := make(map[Vertex]bool) - for _, v := range vertices { - // Build our list of dependencies and the list of channels to - // wait on until we start executing for this vertex. - deps := AsVertexList(g.DownEdges(v)) - depChs := make([]<-chan struct{}, len(deps)) - for i, dep := range deps { - depChs[i] = vertMap[dep] - } - - // Get our channel so that we can close it when we're done - ourCh := vertMap[v] - - // Start the goroutine to wait for our dependencies - readyCh := make(chan bool) - go func(v Vertex, deps []Vertex, chs []<-chan struct{}, readyCh chan<- bool) { - // First wait for all the dependencies - for i, ch := range chs { - DepSatisfied: - for { - select { - case <-ch: - break DepSatisfied - case <-time.After(time.Second * 5): - log.Printf("[DEBUG] vertex %q, waiting for: %q", - VertexName(v), VertexName(deps[i])) - } - } - log.Printf("[DEBUG] vertex %q, got dep: %q", - VertexName(v), VertexName(deps[i])) - } - - // Then, check the map to see if any of our dependencies failed - errLock.Lock() - defer errLock.Unlock() - for _, dep := range deps { - if errMap[dep] { - errMap[v] = true - readyCh <- false - return - } - } - - readyCh <- true - }(v, deps, depChs, readyCh) - - // Start the goroutine that executes - go func(v Vertex, doneCh chan<- struct{}, readyCh <-chan bool) { - defer close(doneCh) - defer wg.Done() - - var err error - if ready := <-readyCh; ready { - err = cb(v) - } - - errLock.Lock() - defer errLock.Unlock() - if err != nil { - errMap[v] = true - errs = multierror.Append(errs, err) - } - }(v, ourCh, readyCh) - } - - <-doneCh - return errs + w := &Walker{Callback: cb, Reverse: true} + w.Update(g) + return w.Wait() } // simple convenience helper for converting a dag.Set to a []Vertex diff --git a/vendor/github.com/hashicorp/terraform/dag/dot.go b/vendor/github.com/hashicorp/terraform/dag/dot.go index 2deb7cc..7e6d2af 100644 --- a/vendor/github.com/hashicorp/terraform/dag/dot.go +++ b/vendor/github.com/hashicorp/terraform/dag/dot.go @@ -79,7 +79,7 @@ func (g *marshalGraph) Dot(opts *DotOpts) []byte { return w.Bytes() } -func (v *marshalVertex) dot(g *marshalGraph) []byte { +func (v *marshalVertex) dot(g *marshalGraph, opts *DotOpts) []byte { var buf bytes.Buffer graphName := g.Name if graphName == "" { @@ -89,7 +89,7 @@ func (v *marshalVertex) dot(g *marshalGraph) []byte { name := v.Name attrs := v.Attrs if v.graphNodeDotter != nil { - node := v.graphNodeDotter.DotNode(name, nil) + node := v.graphNodeDotter.DotNode(name, opts) if node == nil { return []byte{} } @@ -171,7 +171,7 @@ func (g *marshalGraph) writeBody(opts *DotOpts, w *indentWriter) { continue } - w.Write(v.dot(g)) + w.Write(v.dot(g, opts)) } var dotEdges []string diff --git a/vendor/github.com/hashicorp/terraform/dag/set.go b/vendor/github.com/hashicorp/terraform/dag/set.go index d4b2922..3929c9d 100644 --- a/vendor/github.com/hashicorp/terraform/dag/set.go +++ b/vendor/github.com/hashicorp/terraform/dag/set.go @@ -48,6 +48,9 @@ func (s *Set) Include(v interface{}) bool { // Intersection computes the set intersection with other. func (s *Set) Intersection(other *Set) *Set { result := new(Set) + if s == nil { + return result + } if other != nil { for _, v := range s.m { if other.Include(v) { @@ -59,6 +62,25 @@ func (s *Set) Intersection(other *Set) *Set { return result } +// Difference returns a set with the elements that s has but +// other doesn't. +func (s *Set) Difference(other *Set) *Set { + result := new(Set) + if s != nil { + for k, v := range s.m { + var ok bool + if other != nil { + _, ok = other.m[k] + } + if !ok { + result.Add(v) + } + } + } + + return result +} + // Len is the number of items in the set. func (s *Set) Len() int { if s == nil { diff --git a/vendor/github.com/hashicorp/terraform/dag/walk.go b/vendor/github.com/hashicorp/terraform/dag/walk.go new file mode 100644 index 0000000..a74f114 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/dag/walk.go @@ -0,0 +1,445 @@ +package dag + +import ( + "errors" + "fmt" + "log" + "sync" + "time" + + "github.com/hashicorp/go-multierror" +) + +// Walker is used to walk every vertex of a graph in parallel. +// +// A vertex will only be walked when the dependencies of that vertex have +// been walked. If two vertices can be walked at the same time, they will be. +// +// Update can be called to update the graph. This can be called even during +// a walk, cahnging vertices/edges mid-walk. This should be done carefully. +// If a vertex is removed but has already been executed, the result of that +// execution (any error) is still returned by Wait. Changing or re-adding +// a vertex that has already executed has no effect. Changing edges of +// a vertex that has already executed has no effect. +// +// Non-parallelism can be enforced by introducing a lock in your callback +// function. However, the goroutine overhead of a walk will remain. +// Walker will create V*2 goroutines (one for each vertex, and dependency +// waiter for each vertex). In general this should be of no concern unless +// there are a huge number of vertices. +// +// The walk is depth first by default. This can be changed with the Reverse +// option. +// +// A single walker is only valid for one graph walk. After the walk is complete +// you must construct a new walker to walk again. State for the walk is never +// deleted in case vertices or edges are changed. +type Walker struct { + // Callback is what is called for each vertex + Callback WalkFunc + + // Reverse, if true, causes the source of an edge to depend on a target. + // When false (default), the target depends on the source. + Reverse bool + + // changeLock must be held to modify any of the fields below. Only Update + // should modify these fields. Modifying them outside of Update can cause + // serious problems. + changeLock sync.Mutex + vertices Set + edges Set + vertexMap map[Vertex]*walkerVertex + + // wait is done when all vertices have executed. It may become "undone" + // if new vertices are added. + wait sync.WaitGroup + + // errMap contains the errors recorded so far for execution. Reading + // and writing should hold errLock. + errMap map[Vertex]error + errLock sync.Mutex +} + +type walkerVertex struct { + // These should only be set once on initialization and never written again. + // They are not protected by a lock since they don't need to be since + // they are write-once. + + // DoneCh is closed when this vertex has completed execution, regardless + // of success. + // + // CancelCh is closed when the vertex should cancel execution. If execution + // is already complete (DoneCh is closed), this has no effect. Otherwise, + // execution is cancelled as quickly as possible. + DoneCh chan struct{} + CancelCh chan struct{} + + // Dependency information. Any changes to any of these fields requires + // holding DepsLock. + // + // DepsCh is sent a single value that denotes whether the upstream deps + // were successful (no errors). Any value sent means that the upstream + // dependencies are complete. No other values will ever be sent again. + // + // DepsUpdateCh is closed when there is a new DepsCh set. + DepsCh chan bool + DepsUpdateCh chan struct{} + DepsLock sync.Mutex + + // Below is not safe to read/write in parallel. This behavior is + // enforced by changes only happening in Update. Nothing else should + // ever modify these. + deps map[Vertex]chan struct{} + depsCancelCh chan struct{} +} + +// errWalkUpstream is used in the errMap of a walk to note that an upstream +// dependency failed so this vertex wasn't run. This is not shown in the final +// user-returned error. +var errWalkUpstream = errors.New("upstream dependency failed") + +// Wait waits for the completion of the walk and returns any errors ( +// in the form of a multierror) that occurred. Update should be called +// to populate the walk with vertices and edges prior to calling this. +// +// Wait will return as soon as all currently known vertices are complete. +// If you plan on calling Update with more vertices in the future, you +// should not call Wait until after this is done. +func (w *Walker) Wait() error { + // Wait for completion + w.wait.Wait() + + // Grab the error lock + w.errLock.Lock() + defer w.errLock.Unlock() + + // Build the error + var result error + for v, err := range w.errMap { + if err != nil && err != errWalkUpstream { + result = multierror.Append(result, fmt.Errorf( + "%s: %s", VertexName(v), err)) + } + } + + return result +} + +// Update updates the currently executing walk with the given graph. +// This will perform a diff of the vertices and edges and update the walker. +// Already completed vertices remain completed (including any errors during +// their execution). +// +// This returns immediately once the walker is updated; it does not wait +// for completion of the walk. +// +// Multiple Updates can be called in parallel. Update can be called at any +// time during a walk. +func (w *Walker) Update(g *AcyclicGraph) { + var v, e *Set + if g != nil { + v, e = g.vertices, g.edges + } + + // Grab the change lock so no more updates happen but also so that + // no new vertices are executed during this time since we may be + // removing them. + w.changeLock.Lock() + defer w.changeLock.Unlock() + + // Initialize fields + if w.vertexMap == nil { + w.vertexMap = make(map[Vertex]*walkerVertex) + } + + // Calculate all our sets + newEdges := e.Difference(&w.edges) + oldEdges := w.edges.Difference(e) + newVerts := v.Difference(&w.vertices) + oldVerts := w.vertices.Difference(v) + + // Add the new vertices + for _, raw := range newVerts.List() { + v := raw.(Vertex) + + // Add to the waitgroup so our walk is not done until everything finishes + w.wait.Add(1) + + // Add to our own set so we know about it already + log.Printf("[DEBUG] dag/walk: added new vertex: %q", VertexName(v)) + w.vertices.Add(raw) + + // Initialize the vertex info + info := &walkerVertex{ + DoneCh: make(chan struct{}), + CancelCh: make(chan struct{}), + deps: make(map[Vertex]chan struct{}), + } + + // Add it to the map and kick off the walk + w.vertexMap[v] = info + } + + // Remove the old vertices + for _, raw := range oldVerts.List() { + v := raw.(Vertex) + + // Get the vertex info so we can cancel it + info, ok := w.vertexMap[v] + if !ok { + // This vertex for some reason was never in our map. This + // shouldn't be possible. + continue + } + + // Cancel the vertex + close(info.CancelCh) + + // Delete it out of the map + delete(w.vertexMap, v) + + log.Printf("[DEBUG] dag/walk: removed vertex: %q", VertexName(v)) + w.vertices.Delete(raw) + } + + // Add the new edges + var changedDeps Set + for _, raw := range newEdges.List() { + edge := raw.(Edge) + waiter, dep := w.edgeParts(edge) + + // Get the info for the waiter + waiterInfo, ok := w.vertexMap[waiter] + if !ok { + // Vertex doesn't exist... shouldn't be possible but ignore. + continue + } + + // Get the info for the dep + depInfo, ok := w.vertexMap[dep] + if !ok { + // Vertex doesn't exist... shouldn't be possible but ignore. + continue + } + + // Add the dependency to our waiter + waiterInfo.deps[dep] = depInfo.DoneCh + + // Record that the deps changed for this waiter + changedDeps.Add(waiter) + + log.Printf( + "[DEBUG] dag/walk: added edge: %q waiting on %q", + VertexName(waiter), VertexName(dep)) + w.edges.Add(raw) + } + + // Process reoved edges + for _, raw := range oldEdges.List() { + edge := raw.(Edge) + waiter, dep := w.edgeParts(edge) + + // Get the info for the waiter + waiterInfo, ok := w.vertexMap[waiter] + if !ok { + // Vertex doesn't exist... shouldn't be possible but ignore. + continue + } + + // Delete the dependency from the waiter + delete(waiterInfo.deps, dep) + + // Record that the deps changed for this waiter + changedDeps.Add(waiter) + + log.Printf( + "[DEBUG] dag/walk: removed edge: %q waiting on %q", + VertexName(waiter), VertexName(dep)) + w.edges.Delete(raw) + } + + // For each vertex with changed dependencies, we need to kick off + // a new waiter and notify the vertex of the changes. + for _, raw := range changedDeps.List() { + v := raw.(Vertex) + info, ok := w.vertexMap[v] + if !ok { + // Vertex doesn't exist... shouldn't be possible but ignore. + continue + } + + // Create a new done channel + doneCh := make(chan bool, 1) + + // Create the channel we close for cancellation + cancelCh := make(chan struct{}) + + // Build a new deps copy + deps := make(map[Vertex]<-chan struct{}) + for k, v := range info.deps { + deps[k] = v + } + + // Update the update channel + info.DepsLock.Lock() + if info.DepsUpdateCh != nil { + close(info.DepsUpdateCh) + } + info.DepsCh = doneCh + info.DepsUpdateCh = make(chan struct{}) + info.DepsLock.Unlock() + + // Cancel the older waiter + if info.depsCancelCh != nil { + close(info.depsCancelCh) + } + info.depsCancelCh = cancelCh + + log.Printf( + "[DEBUG] dag/walk: dependencies changed for %q, sending new deps", + VertexName(v)) + + // Start the waiter + go w.waitDeps(v, deps, doneCh, cancelCh) + } + + // Start all the new vertices. We do this at the end so that all + // the edge waiters and changes are setup above. + for _, raw := range newVerts.List() { + v := raw.(Vertex) + go w.walkVertex(v, w.vertexMap[v]) + } +} + +// edgeParts returns the waiter and the dependency, in that order. +// The waiter is waiting on the dependency. +func (w *Walker) edgeParts(e Edge) (Vertex, Vertex) { + if w.Reverse { + return e.Source(), e.Target() + } + + return e.Target(), e.Source() +} + +// walkVertex walks a single vertex, waiting for any dependencies before +// executing the callback. +func (w *Walker) walkVertex(v Vertex, info *walkerVertex) { + // When we're done executing, lower the waitgroup count + defer w.wait.Done() + + // When we're done, always close our done channel + defer close(info.DoneCh) + + // Wait for our dependencies. We create a [closed] deps channel so + // that we can immediately fall through to load our actual DepsCh. + var depsSuccess bool + var depsUpdateCh chan struct{} + depsCh := make(chan bool, 1) + depsCh <- true + close(depsCh) + for { + select { + case <-info.CancelCh: + // Cancel + return + + case depsSuccess = <-depsCh: + // Deps complete! Mark as nil to trigger completion handling. + depsCh = nil + + case <-depsUpdateCh: + // New deps, reloop + } + + // Check if we have updated dependencies. This can happen if the + // dependencies were satisfied exactly prior to an Update occuring. + // In that case, we'd like to take into account new dependencies + // if possible. + info.DepsLock.Lock() + if info.DepsCh != nil { + depsCh = info.DepsCh + info.DepsCh = nil + } + if info.DepsUpdateCh != nil { + depsUpdateCh = info.DepsUpdateCh + } + info.DepsLock.Unlock() + + // If we still have no deps channel set, then we're done! + if depsCh == nil { + break + } + } + + // If we passed dependencies, we just want to check once more that + // we're not cancelled, since this can happen just as dependencies pass. + select { + case <-info.CancelCh: + // Cancelled during an update while dependencies completed. + return + default: + } + + // Run our callback or note that our upstream failed + var err error + if depsSuccess { + log.Printf("[DEBUG] dag/walk: walking %q", VertexName(v)) + err = w.Callback(v) + } else { + log.Printf("[DEBUG] dag/walk: upstream errored, not walking %q", VertexName(v)) + err = errWalkUpstream + } + + // Record the error + if err != nil { + w.errLock.Lock() + defer w.errLock.Unlock() + + if w.errMap == nil { + w.errMap = make(map[Vertex]error) + } + w.errMap[v] = err + } +} + +func (w *Walker) waitDeps( + v Vertex, + deps map[Vertex]<-chan struct{}, + doneCh chan<- bool, + cancelCh <-chan struct{}) { + // For each dependency given to us, wait for it to complete + for dep, depCh := range deps { + DepSatisfied: + for { + select { + case <-depCh: + // Dependency satisfied! + break DepSatisfied + + case <-cancelCh: + // Wait cancelled. Note that we didn't satisfy dependencies + // so that anything waiting on us also doesn't run. + doneCh <- false + return + + case <-time.After(time.Second * 5): + log.Printf("[DEBUG] dag/walk: vertex %q, waiting for: %q", + VertexName(v), VertexName(dep)) + } + } + } + + // Dependencies satisfied! We need to check if any errored + w.errLock.Lock() + defer w.errLock.Unlock() + for dep, _ := range deps { + if w.errMap[dep] != nil { + // One of our dependencies failed, so return false + doneCh <- false + return + } + } + + // All dependencies satisfied and successful + doneCh <- true +} diff --git a/vendor/github.com/hashicorp/terraform/flatmap/expand.go b/vendor/github.com/hashicorp/terraform/flatmap/expand.go index b2072a6..e325077 100644 --- a/vendor/github.com/hashicorp/terraform/flatmap/expand.go +++ b/vendor/github.com/hashicorp/terraform/flatmap/expand.go @@ -2,8 +2,11 @@ package flatmap import ( "fmt" + "sort" "strconv" "strings" + + "github.com/hashicorp/hil" ) // Expand takes a map and a key (prefix) and expands that value into @@ -21,7 +24,14 @@ func Expand(m map[string]string, key string) interface{} { } // Check if the key is an array, and if so, expand the array - if _, ok := m[key+".#"]; ok { + if v, ok := m[key+".#"]; ok { + // If the count of the key is unknown, then just put the unknown + // value in the value itself. This will be detected by Terraform + // core later. + if v == hil.UnknownValue { + return v + } + return expandArray(m, key) } @@ -42,9 +52,54 @@ func expandArray(m map[string]string, prefix string) []interface{} { panic(err) } + // The Schema "Set" type stores its values in an array format, but using + // numeric hash values instead of ordinal keys. Take the set of keys + // regardless of value, and expand them in numeric order. + // See GH-11042 for more details. + keySet := map[int]bool{} + computed := map[string]bool{} + for k := range m { + if !strings.HasPrefix(k, prefix+".") { + continue + } + + key := k[len(prefix)+1:] + idx := strings.Index(key, ".") + if idx != -1 { + key = key[:idx] + } + + // skip the count value + if key == "#" { + continue + } + + // strip the computed flag if there is one + if strings.HasPrefix(key, "~") { + key = key[1:] + computed[key] = true + } + + k, err := strconv.Atoi(key) + if err != nil { + panic(err) + } + keySet[int(k)] = true + } + + keysList := make([]int, 0, num) + for key := range keySet { + keysList = append(keysList, key) + } + sort.Ints(keysList) + result := make([]interface{}, num) - for i := 0; i < int(num); i++ { - result[i] = Expand(m, fmt.Sprintf("%s.%d", prefix, i)) + for i, key := range keysList { + keyString := strconv.Itoa(key) + if computed[keyString] { + keyString = "~" + keyString + } + result[i] = Expand(m, fmt.Sprintf("%s.%s", prefix, keyString)) } return result diff --git a/vendor/github.com/hashicorp/terraform/helper/experiment/experiment.go b/vendor/github.com/hashicorp/terraform/helper/experiment/experiment.go index 9910110..18b8837 100644 --- a/vendor/github.com/hashicorp/terraform/helper/experiment/experiment.go +++ b/vendor/github.com/hashicorp/terraform/helper/experiment/experiment.go @@ -50,12 +50,9 @@ import ( // of definition and use. This allows the compiler to enforce references // so it becomes easy to remove the features. var ( - // Reuse the old graphs from TF 0.7.x. These will be removed at some point. - X_legacyGraph = newBasicID("legacy-graph", "LEGACY_GRAPH", false) - // Shadow graph. This is already on by default. Disabling it will be // allowed for awhile in order for it to not block operations. - X_shadow = newBasicID("shadow", "SHADOW", true) + X_shadow = newBasicID("shadow", "SHADOW", false) ) // Global variables this package uses because we are a package @@ -75,7 +72,6 @@ var ( func init() { // The list of all experiments, update this when an experiment is added. All = []ID{ - X_legacyGraph, X_shadow, x_force, } diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/backend.go b/vendor/github.com/hashicorp/terraform/helper/schema/backend.go new file mode 100644 index 0000000..33fe2c1 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/helper/schema/backend.go @@ -0,0 +1,94 @@ +package schema + +import ( + "context" + + "github.com/hashicorp/terraform/terraform" +) + +// Backend represents a partial backend.Backend implementation and simplifies +// the creation of configuration loading and validation. +// +// Unlike other schema structs such as Provider, this struct is meant to be +// embedded within your actual implementation. It provides implementations +// only for Input and Configure and gives you a method for accessing the +// configuration in the form of a ResourceData that you're expected to call +// from the other implementation funcs. +type Backend struct { + // Schema is the schema for the configuration of this backend. If this + // Backend has no configuration this can be omitted. + Schema map[string]*Schema + + // ConfigureFunc is called to configure the backend. Use the + // FromContext* methods to extract information from the context. + // This can be nil, in which case nothing will be called but the + // config will still be stored. + ConfigureFunc func(context.Context) error + + config *ResourceData +} + +const ( + backendConfigKey = iota +) + +// FromContextBackendConfig extracts a ResourceData with the configuration +// from the context. This should only be called by Backend functions. +func FromContextBackendConfig(ctx context.Context) *ResourceData { + return ctx.Value(backendConfigKey).(*ResourceData) +} + +func (b *Backend) Input( + input terraform.UIInput, + c *terraform.ResourceConfig) (*terraform.ResourceConfig, error) { + if b == nil { + return c, nil + } + + return schemaMap(b.Schema).Input(input, c) +} + +func (b *Backend) Validate(c *terraform.ResourceConfig) ([]string, []error) { + if b == nil { + return nil, nil + } + + return schemaMap(b.Schema).Validate(c) +} + +func (b *Backend) Configure(c *terraform.ResourceConfig) error { + if b == nil { + return nil + } + + sm := schemaMap(b.Schema) + + // Get a ResourceData for this configuration. To do this, we actually + // generate an intermediary "diff" although that is never exposed. + diff, err := sm.Diff(nil, c) + if err != nil { + return err + } + + data, err := sm.Data(nil, diff) + if err != nil { + return err + } + b.config = data + + if b.ConfigureFunc != nil { + err = b.ConfigureFunc(context.WithValue( + context.Background(), backendConfigKey, data)) + if err != nil { + return err + } + } + + return nil +} + +// Config returns the configuration. This is available after Configure is +// called. +func (b *Backend) Config() *ResourceData { + return b.config +} diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/field_reader_config.go b/vendor/github.com/hashicorp/terraform/helper/schema/field_reader_config.go index 53ff520..f958bbc 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/field_reader_config.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/field_reader_config.go @@ -79,10 +79,35 @@ func (r *ConfigFieldReader) readField( k := strings.Join(address, ".") schema := schemaList[len(schemaList)-1] + + // If we're getting the single element of a promoted list, then + // check to see if we have a single element we need to promote. + if address[len(address)-1] == "0" && len(schemaList) > 1 { + lastSchema := schemaList[len(schemaList)-2] + if lastSchema.Type == TypeList && lastSchema.PromoteSingle { + k := strings.Join(address[:len(address)-1], ".") + result, err := r.readPrimitive(k, schema) + if err == nil { + return result, nil + } + } + } + switch schema.Type { case TypeBool, TypeFloat, TypeInt, TypeString: return r.readPrimitive(k, schema) case TypeList: + // If we support promotion then we first check if we have a lone + // value that we must promote. + // a value that is alone. + if schema.PromoteSingle { + result, err := r.readPrimitive(k, schema.Elem.(*Schema)) + if err == nil && result.Exists { + result.Value = []interface{}{result.Value} + return result, nil + } + } + return readListField(&nestedConfigFieldReader{r}, address, schema) case TypeMap: return r.readMap(k, schema) diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/getsource_string.go b/vendor/github.com/hashicorp/terraform/helper/schema/getsource_string.go index 790dbff..3a97629 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/getsource_string.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/getsource_string.go @@ -1,4 +1,4 @@ -// Code generated by "stringer -type=getSource resource_data_get_source.go"; DO NOT EDIT +// Code generated by "stringer -type=getSource resource_data_get_source.go"; DO NOT EDIT. package schema diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/provider.go b/vendor/github.com/hashicorp/terraform/helper/schema/provider.go index 5b50d54..d52d2f5 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/provider.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/provider.go @@ -50,8 +50,15 @@ type Provider struct { // See the ConfigureFunc documentation for more information. ConfigureFunc ConfigureFunc + // MetaReset is called by TestReset to reset any state stored in the meta + // interface. This is especially important if the StopContext is stored by + // the provider. + MetaReset func() error + meta interface{} + // a mutex is required because TestReset can directly repalce the stopCtx + stopMu sync.Mutex stopCtx context.Context stopCtxCancel context.CancelFunc stopOnce sync.Once @@ -124,20 +131,43 @@ func (p *Provider) Stopped() bool { // StopCh returns a channel that is closed once the provider is stopped. func (p *Provider) StopContext() context.Context { p.stopOnce.Do(p.stopInit) + + p.stopMu.Lock() + defer p.stopMu.Unlock() + return p.stopCtx } func (p *Provider) stopInit() { + p.stopMu.Lock() + defer p.stopMu.Unlock() + p.stopCtx, p.stopCtxCancel = context.WithCancel(context.Background()) } // Stop implementation of terraform.ResourceProvider interface. func (p *Provider) Stop() error { p.stopOnce.Do(p.stopInit) + + p.stopMu.Lock() + defer p.stopMu.Unlock() + p.stopCtxCancel() return nil } +// TestReset resets any state stored in the Provider, and will call TestReset +// on Meta if it implements the TestProvider interface. +// This may be used to reset the schema.Provider at the start of a test, and is +// automatically called by resource.Test. +func (p *Provider) TestReset() error { + p.stopInit() + if p.MetaReset != nil { + return p.MetaReset() + } + return nil +} + // Input implementation of terraform.ResourceProvider interface. func (p *Provider) Input( input terraform.UIInput, diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/provisioner.go b/vendor/github.com/hashicorp/terraform/helper/schema/provisioner.go new file mode 100644 index 0000000..6ac3fc1 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/helper/schema/provisioner.go @@ -0,0 +1,180 @@ +package schema + +import ( + "context" + "errors" + "fmt" + "sync" + + "github.com/hashicorp/go-multierror" + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/terraform" +) + +// Provisioner represents a resource provisioner in Terraform and properly +// implements all of the ResourceProvisioner API. +// +// This higher level structure makes it much easier to implement a new or +// custom provisioner for Terraform. +// +// The function callbacks for this structure are all passed a context object. +// This context object has a number of pre-defined values that can be accessed +// via the global functions defined in context.go. +type Provisioner struct { + // ConnSchema is the schema for the connection settings for this + // provisioner. + // + // The keys of this map are the configuration keys, and the value is + // the schema describing the value of the configuration. + // + // NOTE: The value of connection keys can only be strings for now. + ConnSchema map[string]*Schema + + // Schema is the schema for the usage of this provisioner. + // + // The keys of this map are the configuration keys, and the value is + // the schema describing the value of the configuration. + Schema map[string]*Schema + + // ApplyFunc is the function for executing the provisioner. This is required. + // It is given a context. See the Provisioner struct docs for more + // information. + ApplyFunc func(ctx context.Context) error + + stopCtx context.Context + stopCtxCancel context.CancelFunc + stopOnce sync.Once +} + +// These constants are the keys that can be used to access data in +// the context parameters for Provisioners. +const ( + connDataInvalid int = iota + + // This returns a *ResourceData for the connection information. + // Guaranteed to never be nil. + ProvConnDataKey + + // This returns a *ResourceData for the config information. + // Guaranteed to never be nil. + ProvConfigDataKey + + // This returns a terraform.UIOutput. Guaranteed to never be nil. + ProvOutputKey + + // This returns the raw InstanceState passed to Apply. Guaranteed to + // be set, but may be nil. + ProvRawStateKey +) + +// InternalValidate should be called to validate the structure +// of the provisioner. +// +// This should be called in a unit test to verify before release that this +// structure is properly configured for use. +func (p *Provisioner) InternalValidate() error { + if p == nil { + return errors.New("provisioner is nil") + } + + var validationErrors error + { + sm := schemaMap(p.ConnSchema) + if err := sm.InternalValidate(sm); err != nil { + validationErrors = multierror.Append(validationErrors, err) + } + } + + { + sm := schemaMap(p.Schema) + if err := sm.InternalValidate(sm); err != nil { + validationErrors = multierror.Append(validationErrors, err) + } + } + + if p.ApplyFunc == nil { + validationErrors = multierror.Append(validationErrors, fmt.Errorf( + "ApplyFunc must not be nil")) + } + + return validationErrors +} + +// StopContext returns a context that checks whether a provisioner is stopped. +func (p *Provisioner) StopContext() context.Context { + p.stopOnce.Do(p.stopInit) + return p.stopCtx +} + +func (p *Provisioner) stopInit() { + p.stopCtx, p.stopCtxCancel = context.WithCancel(context.Background()) +} + +// Stop implementation of terraform.ResourceProvisioner interface. +func (p *Provisioner) Stop() error { + p.stopOnce.Do(p.stopInit) + p.stopCtxCancel() + return nil +} + +func (p *Provisioner) Validate(c *terraform.ResourceConfig) ([]string, []error) { + return schemaMap(p.Schema).Validate(c) +} + +// Apply implementation of terraform.ResourceProvisioner interface. +func (p *Provisioner) Apply( + o terraform.UIOutput, + s *terraform.InstanceState, + c *terraform.ResourceConfig) error { + var connData, configData *ResourceData + + { + // We first need to turn the connection information into a + // terraform.ResourceConfig so that we can use that type to more + // easily build a ResourceData structure. We do this by simply treating + // the conn info as configuration input. + raw := make(map[string]interface{}) + if s != nil { + for k, v := range s.Ephemeral.ConnInfo { + raw[k] = v + } + } + + c, err := config.NewRawConfig(raw) + if err != nil { + return err + } + + sm := schemaMap(p.ConnSchema) + diff, err := sm.Diff(nil, terraform.NewResourceConfig(c)) + if err != nil { + return err + } + connData, err = sm.Data(nil, diff) + if err != nil { + return err + } + } + + { + // Build the configuration data. Doing this requires making a "diff" + // even though that's never used. We use that just to get the correct types. + configMap := schemaMap(p.Schema) + diff, err := configMap.Diff(nil, c) + if err != nil { + return err + } + configData, err = configMap.Data(nil, diff) + if err != nil { + return err + } + } + + // Build the context and call the function + ctx := p.StopContext() + ctx = context.WithValue(ctx, ProvConnDataKey, connData) + ctx = context.WithValue(ctx, ProvConfigDataKey, configData) + ctx = context.WithValue(ctx, ProvOutputKey, o) + ctx = context.WithValue(ctx, ProvRawStateKey, s) + return p.ApplyFunc(ctx) +} diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/resource.go b/vendor/github.com/hashicorp/terraform/helper/schema/resource.go index 9087c69..c810558 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/resource.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/resource.go @@ -3,6 +3,7 @@ package schema import ( "errors" "fmt" + "log" "strconv" "github.com/hashicorp/terraform/terraform" @@ -94,6 +95,15 @@ type Resource struct { // This is a private interface for now, for use by DataSourceResourceShim, // and not for general use. (But maybe later...) deprecationMessage string + + // Timeouts allow users to specify specific time durations in which an + // operation should time out, to allow them to extend an action to suit their + // usage. For example, a user may specify a large Creation timeout for their + // AWS RDS Instance due to it's size, or restoring from a snapshot. + // Resource implementors must enable Timeout support by adding the allowed + // actions (Create, Read, Update, Delete, Default) to the Resource struct, and + // accessing them in the matching methods. + Timeouts *ResourceTimeout } // See Resource documentation. @@ -125,6 +135,18 @@ func (r *Resource) Apply( return s, err } + // Instance Diff shoould have the timeout info, need to copy it over to the + // ResourceData meta + rt := ResourceTimeout{} + if _, ok := d.Meta[TimeoutKey]; ok { + if err := rt.DiffDecode(d); err != nil { + log.Printf("[ERR] Error decoding ResourceTimeout: %s", err) + } + } else { + log.Printf("[DEBUG] No meta timeoutkey found in Apply()") + } + data.timeouts = &rt + if s == nil { // The Terraform API dictates that this should never happen, but // it doesn't hurt to be safe in this case. @@ -150,6 +172,8 @@ func (r *Resource) Apply( // Reset the data to be stateless since we just destroyed data, err = schemaMap(r.Schema).Data(nil, d) + // data was reset, need to re-apply the parsed timeouts + data.timeouts = &rt if err != nil { return nil, err } @@ -176,7 +200,28 @@ func (r *Resource) Apply( func (r *Resource) Diff( s *terraform.InstanceState, c *terraform.ResourceConfig) (*terraform.InstanceDiff, error) { - return schemaMap(r.Schema).Diff(s, c) + + t := &ResourceTimeout{} + err := t.ConfigDecode(r, c) + + if err != nil { + return nil, fmt.Errorf("[ERR] Error decoding timeout: %s", err) + } + + instanceDiff, err := schemaMap(r.Schema).Diff(s, c) + if err != nil { + return instanceDiff, err + } + + if instanceDiff != nil { + if err := t.DiffEncode(instanceDiff); err != nil { + log.Printf("[ERR] Error encoding timeout to instance diff: %s", err) + } + } else { + log.Printf("[DEBUG] Instance Diff is nil in Diff()") + } + + return instanceDiff, err } // Validate validates the resource configuration against the schema. @@ -226,10 +271,19 @@ func (r *Resource) Refresh( return nil, nil } + rt := ResourceTimeout{} + if _, ok := s.Meta[TimeoutKey]; ok { + if err := rt.StateDecode(s); err != nil { + log.Printf("[ERR] Error decoding ResourceTimeout: %s", err) + } + } + if r.Exists != nil { // Make a copy of data so that if it is modified it doesn't // affect our Read later. data, err := schemaMap(r.Schema).Data(s, nil) + data.timeouts = &rt + if err != nil { return s, err } @@ -252,6 +306,7 @@ func (r *Resource) Refresh( } data, err := schemaMap(r.Schema).Data(s, nil) + data.timeouts = &rt if err != nil { return s, err } @@ -353,7 +408,7 @@ func (r *Resource) Data(s *terraform.InstanceState) *ResourceData { } // Set the schema version to latest by default - result.meta = map[string]string{ + result.meta = map[string]interface{}{ "schema_version": strconv.Itoa(r.SchemaVersion), } @@ -378,7 +433,22 @@ func (r *Resource) isTopLevel() bool { // Determines if a given InstanceState needs to be migrated by checking the // stored version number with the current SchemaVersion func (r *Resource) checkSchemaVersion(is *terraform.InstanceState) (bool, int) { - stateSchemaVersion, _ := strconv.Atoi(is.Meta["schema_version"]) + // Get the raw interface{} value for the schema version. If it doesn't + // exist or is nil then set it to zero. + raw := is.Meta["schema_version"] + if raw == nil { + raw = "0" + } + + // Try to convert it to a string. If it isn't a string then we pretend + // that it isn't set at all. It should never not be a string unless it + // was manually tampered with. + rawString, ok := raw.(string) + if !ok { + rawString = "0" + } + + stateSchemaVersion, _ := strconv.Atoi(rawString) return stateSchemaVersion < r.SchemaVersion, stateSchemaVersion } @@ -386,7 +456,7 @@ func (r *Resource) recordCurrentSchemaVersion( state *terraform.InstanceState) *terraform.InstanceState { if state != nil && r.SchemaVersion > 0 { if state.Meta == nil { - state.Meta = make(map[string]string) + state.Meta = make(map[string]interface{}) } state.Meta["schema_version"] = strconv.Itoa(r.SchemaVersion) } diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/resource_data.go b/vendor/github.com/hashicorp/terraform/helper/schema/resource_data.go index b040b63..b2bc8f6 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/resource_data.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/resource_data.go @@ -5,6 +5,7 @@ import ( "reflect" "strings" "sync" + "time" "github.com/hashicorp/terraform/terraform" ) @@ -19,11 +20,12 @@ import ( // The most relevant methods to take a look at are Get, Set, and Partial. type ResourceData struct { // Settable (internally) - schema map[string]*Schema - config *terraform.ResourceConfig - state *terraform.InstanceState - diff *terraform.InstanceDiff - meta map[string]string + schema map[string]*Schema + config *terraform.ResourceConfig + state *terraform.InstanceState + diff *terraform.InstanceDiff + meta map[string]interface{} + timeouts *ResourceTimeout // Don't set multiReader *MultiLevelFieldReader @@ -250,6 +252,12 @@ func (d *ResourceData) State() *terraform.InstanceState { return nil } + if d.timeouts != nil { + if err := d.timeouts.StateEncode(&result); err != nil { + log.Printf("[ERR] Error encoding Timeout meta to Instance State: %s", err) + } + } + // Look for a magic key in the schema that determines we skip the // integrity check of fields existing in the schema, allowing dynamic // keys to be created. @@ -331,6 +339,35 @@ func (d *ResourceData) State() *terraform.InstanceState { return &result } +// Timeout returns the data for the given timeout key +// Returns a duration of 20 minutes for any key not found, or not found and no default. +func (d *ResourceData) Timeout(key string) time.Duration { + key = strings.ToLower(key) + + var timeout *time.Duration + switch key { + case TimeoutCreate: + timeout = d.timeouts.Create + case TimeoutRead: + timeout = d.timeouts.Read + case TimeoutUpdate: + timeout = d.timeouts.Update + case TimeoutDelete: + timeout = d.timeouts.Delete + } + + if timeout != nil { + return *timeout + } + + if d.timeouts.Default != nil { + return *d.timeouts.Default + } + + // Return system default of 20 minutes + return 20 * time.Minute +} + func (d *ResourceData) init() { // Initialize the field that will store our new state var copyState terraform.InstanceState diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/resource_timeout.go b/vendor/github.com/hashicorp/terraform/helper/schema/resource_timeout.go new file mode 100644 index 0000000..445819f --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/helper/schema/resource_timeout.go @@ -0,0 +1,237 @@ +package schema + +import ( + "fmt" + "log" + "time" + + "github.com/hashicorp/terraform/terraform" + "github.com/mitchellh/copystructure" +) + +const TimeoutKey = "e2bfb730-ecaa-11e6-8f88-34363bc7c4c0" +const TimeoutsConfigKey = "timeouts" + +const ( + TimeoutCreate = "create" + TimeoutRead = "read" + TimeoutUpdate = "update" + TimeoutDelete = "delete" + TimeoutDefault = "default" +) + +func timeoutKeys() []string { + return []string{ + TimeoutCreate, + TimeoutRead, + TimeoutUpdate, + TimeoutDelete, + TimeoutDefault, + } +} + +// could be time.Duration, int64 or float64 +func DefaultTimeout(tx interface{}) *time.Duration { + var td time.Duration + switch raw := tx.(type) { + case time.Duration: + return &raw + case int64: + td = time.Duration(raw) + case float64: + td = time.Duration(int64(raw)) + default: + log.Printf("[WARN] Unknown type in DefaultTimeout: %#v", tx) + } + return &td +} + +type ResourceTimeout struct { + Create, Read, Update, Delete, Default *time.Duration +} + +// ConfigDecode takes a schema and the configuration (available in Diff) and +// validates, parses the timeouts into `t` +func (t *ResourceTimeout) ConfigDecode(s *Resource, c *terraform.ResourceConfig) error { + if s.Timeouts != nil { + raw, err := copystructure.Copy(s.Timeouts) + if err != nil { + log.Printf("[DEBUG] Error with deep copy: %s", err) + } + *t = *raw.(*ResourceTimeout) + } + + if raw, ok := c.Config[TimeoutsConfigKey]; ok { + if configTimeouts, ok := raw.([]map[string]interface{}); ok { + for _, timeoutValues := range configTimeouts { + // loop through each Timeout given in the configuration and validate they + // the Timeout defined in the resource + for timeKey, timeValue := range timeoutValues { + // validate that we're dealing with the normal CRUD actions + var found bool + for _, key := range timeoutKeys() { + if timeKey == key { + found = true + break + } + } + + if !found { + return fmt.Errorf("Unsupported Timeout configuration key found (%s)", timeKey) + } + + // Get timeout + rt, err := time.ParseDuration(timeValue.(string)) + if err != nil { + return fmt.Errorf("Error parsing Timeout for (%s): %s", timeKey, err) + } + + var timeout *time.Duration + switch timeKey { + case TimeoutCreate: + timeout = t.Create + case TimeoutUpdate: + timeout = t.Update + case TimeoutRead: + timeout = t.Read + case TimeoutDelete: + timeout = t.Delete + case TimeoutDefault: + timeout = t.Default + } + + // If the resource has not delcared this in the definition, then error + // with an unsupported message + if timeout == nil { + return unsupportedTimeoutKeyError(timeKey) + } + + *timeout = rt + } + } + } else { + log.Printf("[WARN] Invalid Timeout structure found, skipping timeouts") + } + } + + return nil +} + +func unsupportedTimeoutKeyError(key string) error { + return fmt.Errorf("Timeout Key (%s) is not supported", key) +} + +// DiffEncode, StateEncode, and MetaDecode are analogous to the Go stdlib JSONEncoder +// interface: they encode/decode a timeouts struct from an instance diff, which is +// where the timeout data is stored after a diff to pass into Apply. +// +// StateEncode encodes the timeout into the ResourceData's InstanceState for +// saving to state +// +func (t *ResourceTimeout) DiffEncode(id *terraform.InstanceDiff) error { + return t.metaEncode(id) +} + +func (t *ResourceTimeout) StateEncode(is *terraform.InstanceState) error { + return t.metaEncode(is) +} + +// metaEncode encodes the ResourceTimeout into a map[string]interface{} format +// and stores it in the Meta field of the interface it's given. +// Assumes the interface is either *terraform.InstanceState or +// *terraform.InstanceDiff, returns an error otherwise +func (t *ResourceTimeout) metaEncode(ids interface{}) error { + m := make(map[string]interface{}) + + if t.Create != nil { + m[TimeoutCreate] = t.Create.Nanoseconds() + } + if t.Read != nil { + m[TimeoutRead] = t.Read.Nanoseconds() + } + if t.Update != nil { + m[TimeoutUpdate] = t.Update.Nanoseconds() + } + if t.Delete != nil { + m[TimeoutDelete] = t.Delete.Nanoseconds() + } + if t.Default != nil { + m[TimeoutDefault] = t.Default.Nanoseconds() + // for any key above that is nil, if default is specified, we need to + // populate it with the default + for _, k := range timeoutKeys() { + if _, ok := m[k]; !ok { + m[k] = t.Default.Nanoseconds() + } + } + } + + // only add the Timeout to the Meta if we have values + if len(m) > 0 { + switch instance := ids.(type) { + case *terraform.InstanceDiff: + if instance.Meta == nil { + instance.Meta = make(map[string]interface{}) + } + instance.Meta[TimeoutKey] = m + case *terraform.InstanceState: + if instance.Meta == nil { + instance.Meta = make(map[string]interface{}) + } + instance.Meta[TimeoutKey] = m + default: + return fmt.Errorf("Error matching type for Diff Encode") + } + } + + return nil +} + +func (t *ResourceTimeout) StateDecode(id *terraform.InstanceState) error { + return t.metaDecode(id) +} +func (t *ResourceTimeout) DiffDecode(is *terraform.InstanceDiff) error { + return t.metaDecode(is) +} + +func (t *ResourceTimeout) metaDecode(ids interface{}) error { + var rawMeta interface{} + var ok bool + switch rawInstance := ids.(type) { + case *terraform.InstanceDiff: + rawMeta, ok = rawInstance.Meta[TimeoutKey] + if !ok { + return nil + } + case *terraform.InstanceState: + rawMeta, ok = rawInstance.Meta[TimeoutKey] + if !ok { + return nil + } + default: + return fmt.Errorf("Unknown or unsupported type in metaDecode: %#v", ids) + } + + times := rawMeta.(map[string]interface{}) + if len(times) == 0 { + return nil + } + + if v, ok := times[TimeoutCreate]; ok { + t.Create = DefaultTimeout(v) + } + if v, ok := times[TimeoutRead]; ok { + t.Read = DefaultTimeout(v) + } + if v, ok := times[TimeoutUpdate]; ok { + t.Update = DefaultTimeout(v) + } + if v, ok := times[TimeoutDelete]; ok { + t.Delete = DefaultTimeout(v) + } + if v, ok := times[TimeoutDefault]; ok { + t.Default = DefaultTimeout(v) + } + + return nil +} diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/schema.go b/vendor/github.com/hashicorp/terraform/helper/schema/schema.go index 07bdae6..e3a7b1a 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/schema.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/schema.go @@ -62,10 +62,20 @@ type Schema struct { DiffSuppressFunc SchemaDiffSuppressFunc // If this is non-nil, then this will be a default value that is used - // when this item is not set in the configuration/state. + // when this item is not set in the configuration. // - // DefaultFunc can be specified if you want a dynamic default value. - // Only one of Default or DefaultFunc can be set. + // DefaultFunc can be specified to compute a dynamic default. + // Only one of Default or DefaultFunc can be set. If DefaultFunc is + // used then its return value should be stable to avoid generating + // confusing/perpetual diffs. + // + // Changing either Default or the return value of DefaultFunc can be + // a breaking change, especially if the attribute in question has + // ForceNew set. If a default needs to change to align with changing + // assumptions in an upstream API then it may be necessary to also use + // the MigrateState function on the resource to change the state to match, + // or have the Read function adjust the state value to align with the + // new default. // // If Required is true above, then Default cannot be set. DefaultFunc // can be set with Required. If the DefaultFunc returns nil, then there @@ -118,9 +128,16 @@ type Schema struct { // TypeSet or TypeList. Specific use cases would be if a TypeSet is being // used to wrap a complex structure, however less than one instance would // cause instability. - Elem interface{} - MaxItems int - MinItems int + // + // PromoteSingle, if true, will allow single elements to be standalone + // and promote them to a list. For example "foo" would be promoted to + // ["foo"] automatically. This is primarily for legacy reasons and the + // ambiguity is not recommended for new usage. Promotion is only allowed + // for primitive element types. + Elem interface{} + MaxItems int + MinItems int + PromoteSingle bool // The following fields are only valid for a TypeSet type. // @@ -166,7 +183,7 @@ type Schema struct { // Sensitive ensures that the attribute's value does not get displayed in // logs or regular output. It should be used for passwords or other - // secret fields. Futrure versions of Terraform may encrypt these + // secret fields. Future versions of Terraform may encrypt these // values. Sensitive bool } @@ -470,7 +487,9 @@ func (m schemaMap) Input( // Skip things that don't require config, if that is even valid // for a provider schema. - if !v.Required && !v.Optional { + // Required XOR Optional must always be true to validate, so we only + // need to check one. + if v.Optional { continue } @@ -495,7 +514,7 @@ func (m schemaMap) Input( var value interface{} switch v.Type { - case TypeBool, TypeInt, TypeFloat, TypeSet: + case TypeBool, TypeInt, TypeFloat, TypeSet, TypeList: continue case TypeString: value, err = m.inputString(input, k, v) @@ -634,6 +653,19 @@ func (m schemaMap) InternalValidate(topSchemaMap schemaMap) error { return nil } +func (m schemaMap) markAsRemoved(k string, schema *Schema, diff *terraform.InstanceDiff) { + existingDiff, ok := diff.Attributes[k] + if ok { + existingDiff.NewRemoved = true + diff.Attributes[k] = schema.finalizeDiff(existingDiff) + return + } + + diff.Attributes[k] = schema.finalizeDiff(&terraform.ResourceAttrDiff{ + NewRemoved: true, + }) +} + func (m schemaMap) diff( k string, schema *Schema, @@ -757,6 +789,7 @@ func (m schemaMap) diffList( switch t := schema.Elem.(type) { case *Resource: + countDiff, cOk := diff.GetAttribute(k + ".#") // This is a complex resource for i := 0; i < maxLen; i++ { for k2, schema := range t.Schema { @@ -765,6 +798,15 @@ func (m schemaMap) diffList( if err != nil { return err } + + // If parent list is being removed + // remove all subfields which were missed by the diff func + // We process these separately because type-specific diff functions + // lack the context (hierarchy of fields) + subKeyIsCount := strings.HasSuffix(subK, ".#") + if cOk && countDiff.New == "0" && !subKeyIsCount { + m.markAsRemoved(subK, schema, diff) + } } } case *Schema: @@ -889,6 +931,7 @@ func (m schemaMap) diffSet( diff *terraform.InstanceDiff, d *ResourceData, all bool) error { + o, n, _, computedSet := d.diffChange(k) if computedSet { n = nil @@ -973,6 +1016,7 @@ func (m schemaMap) diffSet( for _, code := range list { switch t := schema.Elem.(type) { case *Resource: + countDiff, cOk := diff.GetAttribute(k + ".#") // This is a complex resource for k2, schema := range t.Schema { subK := fmt.Sprintf("%s.%s.%s", k, code, k2) @@ -980,7 +1024,17 @@ func (m schemaMap) diffSet( if err != nil { return err } + + // If parent set is being removed + // remove all subfields which were missed by the diff func + // We process these separately because type-specific diff functions + // lack the context (hierarchy of fields) + subKeyIsCount := strings.HasSuffix(subK, ".#") + if cOk && countDiff.New == "0" && !subKeyIsCount { + m.markAsRemoved(subK, schema, diff) + } } + case *Schema: // Copy the schema so that we can set Computed/ForceNew from // the parent schema (the TypeSet). @@ -1140,6 +1194,14 @@ func (m schemaMap) validateList( // We use reflection to verify the slice because you can't // case to []interface{} unless the slice is exactly that type. rawV := reflect.ValueOf(raw) + + // If we support promotion and the raw value isn't a slice, wrap + // it in []interface{} and check again. + if schema.PromoteSingle && rawV.Kind() != reflect.Slice { + raw = []interface{}{raw} + rawV = reflect.ValueOf(raw) + } + if rawV.Kind() != reflect.Slice { return nil, []error{fmt.Errorf( "%s: should be a list", k)} @@ -1167,6 +1229,13 @@ func (m schemaMap) validateList( for i, raw := range raws { key := fmt.Sprintf("%s.%d", k, i) + // Reify the key value from the ResourceConfig. + // If the list was computed we have all raw values, but some of these + // may be known in the config, and aren't individually marked as Computed. + if r, ok := c.Get(key); ok { + raw = r + } + var ws2 []string var es2 []error switch t := schema.Elem.(type) { @@ -1212,8 +1281,15 @@ func (m schemaMap) validateMap( return nil, []error{fmt.Errorf("%s: should be a map", k)} } - // If it is not a slice, it is valid + // If it is not a slice, validate directly if rawV.Kind() != reflect.Slice { + mapIface := rawV.Interface() + if _, errs := validateMapValues(k, mapIface.(map[string]interface{}), schema); len(errs) > 0 { + return nil, errs + } + if schema.ValidateFunc != nil { + return schema.ValidateFunc(mapIface, k) + } return nil, nil } @@ -1229,6 +1305,10 @@ func (m schemaMap) validateMap( return nil, []error{fmt.Errorf( "%s: should be a map", k)} } + mapIface := v.Interface() + if _, errs := validateMapValues(k, mapIface.(map[string]interface{}), schema); len(errs) > 0 { + return nil, errs + } } if schema.ValidateFunc != nil { @@ -1245,6 +1325,67 @@ func (m schemaMap) validateMap( return nil, nil } +func validateMapValues(k string, m map[string]interface{}, schema *Schema) ([]string, []error) { + for key, raw := range m { + valueType, err := getValueType(k, schema) + if err != nil { + return nil, []error{err} + } + + switch valueType { + case TypeBool: + var n bool + if err := mapstructure.WeakDecode(raw, &n); err != nil { + return nil, []error{fmt.Errorf("%s (%s): %s", k, key, err)} + } + case TypeInt: + var n int + if err := mapstructure.WeakDecode(raw, &n); err != nil { + return nil, []error{fmt.Errorf("%s (%s): %s", k, key, err)} + } + case TypeFloat: + var n float64 + if err := mapstructure.WeakDecode(raw, &n); err != nil { + return nil, []error{fmt.Errorf("%s (%s): %s", k, key, err)} + } + case TypeString: + var n string + if err := mapstructure.WeakDecode(raw, &n); err != nil { + return nil, []error{fmt.Errorf("%s (%s): %s", k, key, err)} + } + default: + panic(fmt.Sprintf("Unknown validation type: %#v", schema.Type)) + } + } + return nil, nil +} + +func getValueType(k string, schema *Schema) (ValueType, error) { + if schema.Elem == nil { + return TypeString, nil + } + if vt, ok := schema.Elem.(ValueType); ok { + return vt, nil + } + + if s, ok := schema.Elem.(*Schema); ok { + if s.Elem == nil { + return TypeString, nil + } + if vt, ok := s.Elem.(ValueType); ok { + return vt, nil + } + } + + if _, ok := schema.Elem.(*Resource); ok { + // TODO: We don't actually support this (yet) + // but silently pass the validation, until we decide + // how to handle nested structures in maps + return TypeString, nil + } + return 0, fmt.Errorf("%s: unexpected map value type: %#v", k, schema.Elem) +} + func (m schemaMap) validateObject( k string, schema map[string]*Schema, @@ -1277,6 +1418,9 @@ func (m schemaMap) validateObject( if m, ok := raw.(map[string]interface{}); ok { for subk, _ := range m { if _, ok := schema[subk]; !ok { + if subk == TimeoutsConfigKey { + continue + } es = append(es, fmt.Errorf( "%s: invalid or unknown key: %s", k, subk)) } @@ -1319,28 +1463,28 @@ func (m schemaMap) validatePrimitive( // Verify that we can parse this as the correct type var n bool if err := mapstructure.WeakDecode(raw, &n); err != nil { - return nil, []error{err} + return nil, []error{fmt.Errorf("%s: %s", k, err)} } decoded = n case TypeInt: // Verify that we can parse this as an int var n int if err := mapstructure.WeakDecode(raw, &n); err != nil { - return nil, []error{err} + return nil, []error{fmt.Errorf("%s: %s", k, err)} } decoded = n case TypeFloat: // Verify that we can parse this as an int var n float64 if err := mapstructure.WeakDecode(raw, &n); err != nil { - return nil, []error{err} + return nil, []error{fmt.Errorf("%s: %s", k, err)} } decoded = n case TypeString: // Verify that we can parse this as a string var n string if err := mapstructure.WeakDecode(raw, &n); err != nil { - return nil, []error{err} + return nil, []error{fmt.Errorf("%s: %s", k, err)} } decoded = n default: diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/testing.go b/vendor/github.com/hashicorp/terraform/helper/schema/testing.go new file mode 100644 index 0000000..9765bdb --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/helper/schema/testing.go @@ -0,0 +1,30 @@ +package schema + +import ( + "testing" + + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/terraform" +) + +// TestResourceDataRaw creates a ResourceData from a raw configuration map. +func TestResourceDataRaw( + t *testing.T, schema map[string]*Schema, raw map[string]interface{}) *ResourceData { + c, err := config.NewRawConfig(raw) + if err != nil { + t.Fatalf("err: %s", err) + } + + sm := schemaMap(schema) + diff, err := sm.Diff(nil, terraform.NewResourceConfig(c)) + if err != nil { + t.Fatalf("err: %s", err) + } + + result, err := sm.Data(nil, diff) + if err != nil { + t.Fatalf("err: %s", err) + } + + return result +} diff --git a/vendor/github.com/hashicorp/terraform/helper/schema/valuetype_string.go b/vendor/github.com/hashicorp/terraform/helper/schema/valuetype_string.go index 08f0084..1610cec 100644 --- a/vendor/github.com/hashicorp/terraform/helper/schema/valuetype_string.go +++ b/vendor/github.com/hashicorp/terraform/helper/schema/valuetype_string.go @@ -1,4 +1,4 @@ -// Code generated by "stringer -type=ValueType valuetype.go"; DO NOT EDIT +// Code generated by "stringer -type=ValueType valuetype.go"; DO NOT EDIT. package schema diff --git a/vendor/github.com/hashicorp/terraform/plugin/resource_provisioner.go b/vendor/github.com/hashicorp/terraform/plugin/resource_provisioner.go index 9823095..8fce9d8 100644 --- a/vendor/github.com/hashicorp/terraform/plugin/resource_provisioner.go +++ b/vendor/github.com/hashicorp/terraform/plugin/resource_provisioner.go @@ -77,6 +77,19 @@ func (p *ResourceProvisioner) Apply( return err } +func (p *ResourceProvisioner) Stop() error { + var resp ResourceProvisionerStopResponse + err := p.Client.Call("Plugin.Stop", new(interface{}), &resp) + if err != nil { + return err + } + if resp.Error != nil { + err = resp.Error + } + + return err +} + func (p *ResourceProvisioner) Close() error { return p.Client.Close() } @@ -100,6 +113,10 @@ type ResourceProvisionerApplyResponse struct { Error *plugin.BasicError } +type ResourceProvisionerStopResponse struct { + Error *plugin.BasicError +} + // ResourceProvisionerServer is a net/rpc compatible structure for serving // a ResourceProvisioner. This should not be used directly. type ResourceProvisionerServer struct { @@ -143,3 +160,14 @@ func (s *ResourceProvisionerServer) Validate( } return nil } + +func (s *ResourceProvisionerServer) Stop( + _ interface{}, + reply *ResourceProvisionerStopResponse) error { + err := s.Provisioner.Stop() + *reply = ResourceProvisionerStopResponse{ + Error: plugin.NewBasicError(err), + } + + return nil +} diff --git a/vendor/github.com/hashicorp/terraform/plugin/serve.go b/vendor/github.com/hashicorp/terraform/plugin/serve.go index 932728c..2028a61 100644 --- a/vendor/github.com/hashicorp/terraform/plugin/serve.go +++ b/vendor/github.com/hashicorp/terraform/plugin/serve.go @@ -19,7 +19,7 @@ var Handshake = plugin.HandshakeConfig{ // one or the other that makes it so that they can't safely communicate. // This could be adding a new interface value, it could be how // helper/schema computes diffs, etc. - ProtocolVersion: 2, + ProtocolVersion: 4, // The magic cookie values should NEVER be changed. MagicCookieKey: "TF_PLUGIN_MAGIC_COOKIE", diff --git a/vendor/github.com/hashicorp/terraform/terraform/context.go b/vendor/github.com/hashicorp/terraform/terraform/context.go index 2ebeed0..15528be 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/context.go +++ b/vendor/github.com/hashicorp/terraform/terraform/context.go @@ -1,6 +1,7 @@ package terraform import ( + "context" "fmt" "log" "sort" @@ -48,6 +49,7 @@ var ( // ContextOpts are the user-configurable options to create a context with // NewContext. type ContextOpts struct { + Meta *ContextMeta Destroy bool Diff *Diff Hooks []Hook @@ -64,6 +66,14 @@ type ContextOpts struct { UIInput UIInput } +// ContextMeta is metadata about the running context. This is information +// that this package or structure cannot determine on its own but exposes +// into Terraform in various ways. This must be provided by the Context +// initializer. +type ContextMeta struct { + Env string // Env is the state environment +} + // Context represents all the context that Terraform needs in order to // perform operations on infrastructure. This structure is built using // NewContext. See the documentation for that. @@ -79,6 +89,7 @@ type Context struct { diff *Diff diffLock sync.RWMutex hooks []Hook + meta *ContextMeta module *module.Tree sh *stopHook shadow bool @@ -91,8 +102,10 @@ type Context struct { l sync.Mutex // Lock acquired during any task parallelSem Semaphore providerInputConfig map[string]map[string]interface{} - runCh <-chan struct{} - stopCh chan struct{} + runLock sync.Mutex + runCond *sync.Cond + runContext context.Context + runContextCancel context.CancelFunc shadowErr error } @@ -175,6 +188,7 @@ func NewContext(opts *ContextOpts) (*Context, error) { destroy: opts.Destroy, diff: diff, hooks: hooks, + meta: opts.Meta, module: opts.Module, shadow: opts.Shadow, state: state, @@ -204,6 +218,7 @@ func (c *Context) Graph(typ GraphType, opts *ContextGraphOpts) (*Graph, error) { opts = &ContextGraphOpts{Validate: true} } + log.Printf("[INFO] terraform: building graph: %s", typ) switch typ { case GraphTypeApply: return (&ApplyGraphBuilder{ @@ -212,18 +227,40 @@ func (c *Context) Graph(typ GraphType, opts *ContextGraphOpts) (*Graph, error) { State: c.state, Providers: c.components.ResourceProviders(), Provisioners: c.components.ResourceProvisioners(), + Targets: c.targets, Destroy: c.destroy, Validate: opts.Validate, }).Build(RootModulePath) + case GraphTypeInput: + // The input graph is just a slightly modified plan graph + fallthrough + case GraphTypeValidate: + // The validate graph is just a slightly modified plan graph + fallthrough case GraphTypePlan: - return (&PlanGraphBuilder{ + // Create the plan graph builder + p := &PlanGraphBuilder{ Module: c.module, State: c.state, Providers: c.components.ResourceProviders(), Targets: c.targets, Validate: opts.Validate, - }).Build(RootModulePath) + } + + // Some special cases for other graph types shared with plan currently + var b GraphBuilder = p + switch typ { + case GraphTypeInput: + b = InputGraphBuilder(p) + case GraphTypeValidate: + // We need to set the provisioners so those can be validated + p.Provisioners = c.components.ResourceProvisioners() + + b = ValidateGraphBuilder(p) + } + + return b.Build(RootModulePath) case GraphTypePlanDestroy: return (&DestroyPlanGraphBuilder{ @@ -233,29 +270,19 @@ func (c *Context) Graph(typ GraphType, opts *ContextGraphOpts) (*Graph, error) { Validate: opts.Validate, }).Build(RootModulePath) - case GraphTypeLegacy: - return c.graphBuilder(opts).Build(RootModulePath) + case GraphTypeRefresh: + return (&RefreshGraphBuilder{ + Module: c.module, + State: c.state, + Providers: c.components.ResourceProviders(), + Targets: c.targets, + Validate: opts.Validate, + }).Build(RootModulePath) } return nil, fmt.Errorf("unknown graph type: %s", typ) } -// GraphBuilder returns the GraphBuilder that will be used to create -// the graphs for this context. -func (c *Context) graphBuilder(g *ContextGraphOpts) GraphBuilder { - return &BuiltinGraphBuilder{ - Root: c.module, - Diff: c.diff, - Providers: c.components.ResourceProviders(), - Provisioners: c.components.ResourceProvisioners(), - State: c.state, - Targets: c.targets, - Destroy: c.destroy, - Validate: g.Validate, - Verbose: g.Verbose, - } -} - // ShadowError returns any errors caught during a shadow operation. // // A shadow operation is an operation run in parallel to a real operation @@ -283,6 +310,13 @@ func (c *Context) ShadowError() error { return c.shadowErr } +// State returns a copy of the current state associated with this context. +// +// This cannot safely be called in parallel with any other Context function. +func (c *Context) State() *State { + return c.state.DeepCopy() +} + // Interpolater returns an Interpolater built on a copy of the state // that can be used to test interpolation values. func (c *Context) Interpolater() *Interpolater { @@ -290,6 +324,7 @@ func (c *Context) Interpolater() *Interpolater { var stateLock sync.RWMutex return &Interpolater{ Operation: walkApply, + Meta: c.meta, Module: c.module, State: c.state.DeepCopy(), StateLock: &stateLock, @@ -302,8 +337,7 @@ func (c *Context) Interpolater() *Interpolater { // This modifies the configuration in-place, so asking for Input twice // may result in different UI output showing different current values. func (c *Context) Input(mode InputMode) error { - v := c.acquireRun("input") - defer c.releaseRun(v) + defer c.acquireRun("input")() if mode&InputModeVar != 0 { // Walk the variables first for the root module. We walk them in @@ -402,7 +436,7 @@ func (c *Context) Input(mode InputMode) error { if mode&InputModeProvider != 0 { // Build the graph - graph, err := c.Graph(GraphTypeLegacy, nil) + graph, err := c.Graph(GraphTypeInput, nil) if err != nil { return err } @@ -422,21 +456,13 @@ func (c *Context) Input(mode InputMode) error { // In addition to returning the resulting state, this context is updated // with the latest state. func (c *Context) Apply() (*State, error) { - v := c.acquireRun("apply") - defer c.releaseRun(v) + defer c.acquireRun("apply")() // Copy our own state c.state = c.state.DeepCopy() - // Enable the new graph by default - X_legacyGraph := experiment.Enabled(experiment.X_legacyGraph) - // Build the graph. - graphType := GraphTypeLegacy - if !X_legacyGraph { - graphType = GraphTypeApply - } - graph, err := c.Graph(graphType, nil) + graph, err := c.Graph(GraphTypeApply, nil) if err != nil { return nil, err } @@ -467,8 +493,7 @@ func (c *Context) Apply() (*State, error) { // Plan also updates the diff of this context to be the diff generated // by the plan, so Apply can be called after. func (c *Context) Plan() (*Plan, error) { - v := c.acquireRun("plan") - defer c.releaseRun(v) + defer c.acquireRun("plan")() p := &Plan{ Module: c.module, @@ -504,17 +529,10 @@ func (c *Context) Plan() (*Plan, error) { c.diff.init() c.diffLock.Unlock() - // Used throughout below - X_legacyGraph := experiment.Enabled(experiment.X_legacyGraph) - // Build the graph. - graphType := GraphTypeLegacy - if !X_legacyGraph { - if c.destroy { - graphType = GraphTypePlanDestroy - } else { - graphType = GraphTypePlan - } + graphType := GraphTypePlan + if c.destroy { + graphType = GraphTypePlanDestroy } graph, err := c.Graph(graphType, nil) if err != nil { @@ -539,15 +557,17 @@ func (c *Context) Plan() (*Plan, error) { p.Diff.DeepCopy() } - // We don't do the reverification during the new destroy plan because - // it will use a different apply process. - if X_legacyGraph { - // Now that we have a diff, we can build the exact graph that Apply will use - // and catch any possible cycles during the Plan phase. - if _, err := c.Graph(GraphTypeLegacy, nil); err != nil { - return nil, err + /* + // We don't do the reverification during the new destroy plan because + // it will use a different apply process. + if X_legacyGraph { + // Now that we have a diff, we can build the exact graph that Apply will use + // and catch any possible cycles during the Plan phase. + if _, err := c.Graph(GraphTypeLegacy, nil); err != nil { + return nil, err + } } - } + */ var errs error if len(walker.ValidationErrors) > 0 { @@ -563,14 +583,13 @@ func (c *Context) Plan() (*Plan, error) { // Even in the case an error is returned, the state will be returned and // will potentially be partially updated. func (c *Context) Refresh() (*State, error) { - v := c.acquireRun("refresh") - defer c.releaseRun(v) + defer c.acquireRun("refresh")() // Copy our own state c.state = c.state.DeepCopy() - // Build the graph - graph, err := c.Graph(GraphTypeLegacy, nil) + // Build the graph. + graph, err := c.Graph(GraphTypeRefresh, nil) if err != nil { return nil, err } @@ -590,30 +609,34 @@ func (c *Context) Refresh() (*State, error) { // // Stop will block until the task completes. func (c *Context) Stop() { + log.Printf("[WARN] terraform: Stop called, initiating interrupt sequence") + c.l.Lock() - ch := c.runCh + defer c.l.Unlock() - // If we aren't running, then just return - if ch == nil { - c.l.Unlock() - return - } + // If we're running, then stop + if c.runContextCancel != nil { + log.Printf("[WARN] terraform: run context exists, stopping") + + // Tell the hook we want to stop + c.sh.Stop() - // Tell the hook we want to stop - c.sh.Stop() + // Stop the context + c.runContextCancel() + c.runContextCancel = nil + } - // Close the stop channel - close(c.stopCh) + // Grab the condition var before we exit + if cond := c.runCond; cond != nil { + cond.Wait() + } - // Wait for us to stop - c.l.Unlock() - <-ch + log.Printf("[WARN] terraform: stop complete") } // Validate validates the configuration and returns any warnings or errors. func (c *Context) Validate() ([]string, []error) { - v := c.acquireRun("validate") - defer c.releaseRun(v) + defer c.acquireRun("validate")() var errs error @@ -641,7 +664,7 @@ func (c *Context) Validate() ([]string, []error) { // We also validate the graph generated here, but this graph doesn't // necessarily match the graph that Plan will generate, so we'll validate the // graph again later after Planning. - graph, err := c.Graph(GraphTypeLegacy, nil) + graph, err := c.Graph(GraphTypeValidate, nil) if err != nil { return nil, []error{err} } @@ -654,6 +677,12 @@ func (c *Context) Validate() ([]string, []error) { // Return the result rerrs := multierror.Append(errs, walker.ValidationErrors...) + + sort.Strings(walker.ValidationWarnings) + sort.Slice(rerrs.Errors, func(i, j int) bool { + return rerrs.Errors[i].Error() < rerrs.Errors[j].Error() + }) + return walker.ValidationWarnings, rerrs.Errors } @@ -674,26 +703,25 @@ func (c *Context) SetVariable(k string, v interface{}) { c.variables[k] = v } -func (c *Context) acquireRun(phase string) chan<- struct{} { +func (c *Context) acquireRun(phase string) func() { + // With the run lock held, grab the context lock to make changes + // to the run context. c.l.Lock() defer c.l.Unlock() - dbug.SetPhase(phase) - - // Wait for no channel to exist - for c.runCh != nil { - c.l.Unlock() - ch := c.runCh - <-ch - c.l.Lock() + // Wait until we're no longer running + for c.runCond != nil { + c.runCond.Wait() } - // Create the new channel - ch := make(chan struct{}) - c.runCh = ch + // Build our lock + c.runCond = sync.NewCond(&c.l) + + // Setup debugging + dbug.SetPhase(phase) - // Reset the stop channel so we can watch that - c.stopCh = make(chan struct{}) + // Create a new run context + c.runContext, c.runContextCancel = context.WithCancel(context.Background()) // Reset the stop hook so we're not stopped c.sh.Reset() @@ -701,10 +729,11 @@ func (c *Context) acquireRun(phase string) chan<- struct{} { // Reset the shadow errors c.shadowErr = nil - return ch + return c.releaseRun } -func (c *Context) releaseRun(ch chan<- struct{}) { +func (c *Context) releaseRun() { + // Grab the context lock so that we can make modifications to fields c.l.Lock() defer c.l.Unlock() @@ -713,9 +742,19 @@ func (c *Context) releaseRun(ch chan<- struct{}) { // phase dbug.SetPhase("INVALID") - close(ch) - c.runCh = nil - c.stopCh = nil + // End our run. We check if runContext is non-nil because it can be + // set to nil if it was cancelled via Stop() + if c.runContextCancel != nil { + c.runContextCancel() + } + + // Unlock all waiting our condition + cond := c.runCond + c.runCond = nil + cond.Broadcast() + + // Unset the context + c.runContext = nil } func (c *Context) walk( @@ -729,37 +768,39 @@ func (c *Context) walk( shadow = nil } + // Just log this so we can see it in a debug log + if !c.shadow { + log.Printf("[WARN] terraform: shadow graph disabled") + shadow = nil + } + // If we have a shadow graph, walk that as well var shadowCtx *Context var shadowCloser Shadow - if c.shadow && shadow != nil { + if shadow != nil { // Build the shadow context. In the process, override the real context // with the one that is wrapped so that the shadow context can verify // the results of the real. realCtx, shadowCtx, shadowCloser = newShadowContext(c) } - // Just log this so we can see it in a debug log - if !c.shadow { - log.Printf("[WARN] terraform: shadow graph disabled") - } - log.Printf("[DEBUG] Starting graph walk: %s", operation.String()) walker := &ContextGraphWalker{ - Context: realCtx, - Operation: operation, + Context: realCtx, + Operation: operation, + StopContext: c.runContext, } // Watch for a stop so we can call the provider Stop() API. - doneCh := make(chan struct{}) - go c.watchStop(walker, c.stopCh, doneCh) + watchStop, watchWait := c.watchStop(walker) // Walk the real graph, this will block until it completes realErr := graph.Walk(walker) - // Close the done channel so the watcher stops - close(doneCh) + // Close the channel so the watcher stops, and wait for it to return. + close(watchStop) + <-watchWait // If we have a shadow graph and we interrupted the real graph, then // we just close the shadow and never verify it. It is non-trivial to @@ -848,33 +889,74 @@ func (c *Context) walk( return walker, realErr } -func (c *Context) watchStop(walker *ContextGraphWalker, stopCh, doneCh <-chan struct{}) { - // Wait for a stop or completion - select { - case <-stopCh: - // Stop was triggered. Fall out of the select - case <-doneCh: - // Done, just exit completely - return - } +// watchStop immediately returns a `stop` and a `wait` chan after dispatching +// the watchStop goroutine. This will watch the runContext for cancellation and +// stop the providers accordingly. When the watch is no longer needed, the +// `stop` chan should be closed before waiting on the `wait` chan. +// The `wait` chan is important, because without synchronizing with the end of +// the watchStop goroutine, the runContext may also be closed during the select +// incorrectly causing providers to be stopped. Even if the graph walk is done +// at that point, stopping a provider permanently cancels its StopContext which +// can cause later actions to fail. +func (c *Context) watchStop(walker *ContextGraphWalker) (chan struct{}, <-chan struct{}) { + stop := make(chan struct{}) + wait := make(chan struct{}) + + // get the runContext cancellation channel now, because releaseRun will + // write to the runContext field. + done := c.runContext.Done() + + go func() { + defer close(wait) + // Wait for a stop or completion + select { + case <-done: + // done means the context was canceled, so we need to try and stop + // providers. + case <-stop: + // our own stop channel was closed. + return + } - // If we're here, we're stopped, trigger the call. + // If we're here, we're stopped, trigger the call. - // Copy the providers so that a misbehaved blocking Stop doesn't - // completely hang Terraform. - walker.providerLock.Lock() - ps := make([]ResourceProvider, 0, len(walker.providerCache)) - for _, p := range walker.providerCache { - ps = append(ps, p) - } - defer walker.providerLock.Unlock() + { + // Copy the providers so that a misbehaved blocking Stop doesn't + // completely hang Terraform. + walker.providerLock.Lock() + ps := make([]ResourceProvider, 0, len(walker.providerCache)) + for _, p := range walker.providerCache { + ps = append(ps, p) + } + defer walker.providerLock.Unlock() - for _, p := range ps { - // We ignore the error for now since there isn't any reasonable - // action to take if there is an error here, since the stop is still - // advisory: Terraform will exit once the graph node completes. - p.Stop() - } + for _, p := range ps { + // We ignore the error for now since there isn't any reasonable + // action to take if there is an error here, since the stop is still + // advisory: Terraform will exit once the graph node completes. + p.Stop() + } + } + + { + // Call stop on all the provisioners + walker.provisionerLock.Lock() + ps := make([]ResourceProvisioner, 0, len(walker.provisionerCache)) + for _, p := range walker.provisionerCache { + ps = append(ps, p) + } + defer walker.provisionerLock.Unlock() + + for _, p := range ps { + // We ignore the error for now since there isn't any reasonable + // action to take if there is an error here, since the stop is still + // advisory: Terraform will exit once the graph node completes. + p.Stop() + } + } + }() + + return stop, wait } // parseVariableAsHCL parses the value of a single variable as would have been specified diff --git a/vendor/github.com/hashicorp/terraform/terraform/context_graph_type.go b/vendor/github.com/hashicorp/terraform/terraform/context_graph_type.go index a204969..084f010 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/context_graph_type.go +++ b/vendor/github.com/hashicorp/terraform/terraform/context_graph_type.go @@ -10,9 +10,12 @@ type GraphType byte const ( GraphTypeInvalid GraphType = 0 GraphTypeLegacy GraphType = iota + GraphTypeRefresh GraphTypePlan GraphTypePlanDestroy GraphTypeApply + GraphTypeInput + GraphTypeValidate ) // GraphTypeMap is a mapping of human-readable string to GraphType. This @@ -20,7 +23,10 @@ const ( // graph types. var GraphTypeMap = map[string]GraphType{ "apply": GraphTypeApply, + "input": GraphTypeInput, "plan": GraphTypePlan, "plan-destroy": GraphTypePlanDestroy, + "refresh": GraphTypeRefresh, "legacy": GraphTypeLegacy, + "validate": GraphTypeValidate, } diff --git a/vendor/github.com/hashicorp/terraform/terraform/context_import.go b/vendor/github.com/hashicorp/terraform/terraform/context_import.go index afc9a43..f1d5776 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/context_import.go +++ b/vendor/github.com/hashicorp/terraform/terraform/context_import.go @@ -40,8 +40,7 @@ type ImportTarget struct { // imported. func (c *Context) Import(opts *ImportOpts) (*State, error) { // Hold a lock since we can modify our own state here - v := c.acquireRun("import") - defer c.releaseRun(v) + defer c.acquireRun("import")() // Copy our own state c.state = c.state.DeepCopy() diff --git a/vendor/github.com/hashicorp/terraform/terraform/debug.go b/vendor/github.com/hashicorp/terraform/terraform/debug.go index 168bbd5..265339f 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/debug.go +++ b/vendor/github.com/hashicorp/terraform/terraform/debug.go @@ -413,7 +413,7 @@ func (*DebugHook) PreProvision(ii *InstanceInfo, s string) (HookAction, error) { return HookActionContinue, nil } -func (*DebugHook) PostProvision(ii *InstanceInfo, s string) (HookAction, error) { +func (*DebugHook) PostProvision(ii *InstanceInfo, s string, err error) (HookAction, error) { if dbug == nil { return HookActionContinue, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/diff.go b/vendor/github.com/hashicorp/terraform/terraform/diff.go index c50d3ce..a9fae6c 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/diff.go +++ b/vendor/github.com/hashicorp/terraform/terraform/diff.go @@ -25,6 +25,9 @@ const ( DiffDestroyCreate ) +// multiVal matches the index key to a flatmapped set, list or map +var multiVal = regexp.MustCompile(`\.(#|%)$`) + // Diff trackes the changes that are necessary to apply a configuration // to an existing infrastructure. type Diff struct { @@ -364,6 +367,12 @@ type InstanceDiff struct { Destroy bool DestroyDeposed bool DestroyTainted bool + + // Meta is a simple K/V map that is stored in a diff and persisted to + // plans but otherwise is completely ignored by Terraform core. It is + // mean to be used for additional data a resource may want to pass through. + // The value here must only contain Go primitives and collections. + Meta map[string]interface{} } func (d *InstanceDiff) Lock() { d.mu.Lock() } @@ -638,7 +647,45 @@ func (d *InstanceDiff) Same(d2 *InstanceDiff) (bool, string) { newNew := d2.RequiresNew() if oldNew && !newNew { oldNew = false - for _, rd := range d.Attributes { + + // This section builds a list of ignorable attributes for requiresNew + // by removing off any elements of collections going to zero elements. + // For collections going to zero, they may not exist at all in the + // new diff (and hence RequiresNew == false). + ignoreAttrs := make(map[string]struct{}) + for k, diffOld := range d.Attributes { + if !strings.HasSuffix(k, ".%") && !strings.HasSuffix(k, ".#") { + continue + } + + // This case is in here as a protection measure. The bug that this + // code originally fixed (GH-11349) didn't have to deal with computed + // so I'm not 100% sure what the correct behavior is. Best to leave + // the old behavior. + if diffOld.NewComputed { + continue + } + + // We're looking for the case a map goes to exactly 0. + if diffOld.New != "0" { + continue + } + + // Found it! Ignore all of these. The prefix here is stripping + // off the "%" so it is just "k." + prefix := k[:len(k)-1] + for k2, _ := range d.Attributes { + if strings.HasPrefix(k2, prefix) { + ignoreAttrs[k2] = struct{}{} + } + } + } + + for k, rd := range d.Attributes { + if _, ok := ignoreAttrs[k]; ok { + continue + } + // If the field is requires new and NOT computed, then what // we have is a diff mismatch for sure. We set that the old // diff does REQUIRE a ForceNew. @@ -764,7 +811,6 @@ func (d *InstanceDiff) Same(d2 *InstanceDiff) (bool, string) { } // search for the suffix of the base of a [computed] map, list or set. - multiVal := regexp.MustCompile(`\.(#|~#|%)$`) match := multiVal.FindStringSubmatch(k) if diffOld.NewComputed && len(match) == 2 { diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_apply.go b/vendor/github.com/hashicorp/terraform/terraform/eval_apply.go index f8a42ed..2f6a497 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_apply.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_apply.go @@ -52,16 +52,6 @@ func (n *EvalApply) Eval(ctx EvalContext) (interface{}, error) { *n.CreateNew = state.ID == "" && !diff.GetDestroy() || diff.RequiresNew() } - { - // Call pre-apply hook - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PreApply(n.Info, state, diff) - }) - if err != nil { - return nil, err - } - } - // With the completed diff, apply! log.Printf("[DEBUG] apply: %s: executing Apply", n.Info.Id) state, err := provider.Apply(n.Info, state, diff) @@ -104,6 +94,37 @@ func (n *EvalApply) Eval(ctx EvalContext) (interface{}, error) { return nil, nil } +// EvalApplyPre is an EvalNode implementation that does the pre-Apply work +type EvalApplyPre struct { + Info *InstanceInfo + State **InstanceState + Diff **InstanceDiff +} + +// TODO: test +func (n *EvalApplyPre) Eval(ctx EvalContext) (interface{}, error) { + state := *n.State + diff := *n.Diff + + // If the state is nil, make it non-nil + if state == nil { + state = new(InstanceState) + } + state.init() + + { + // Call post-apply hook + err := ctx.Hook(func(h Hook) (HookAction, error) { + return h.PreApply(n.Info, state, diff) + }) + if err != nil { + return nil, err + } + } + + return nil, nil +} + // EvalApplyPost is an EvalNode implementation that does the post-Apply work type EvalApplyPost struct { Info *InstanceInfo @@ -140,25 +161,33 @@ type EvalApplyProvisioners struct { InterpResource *Resource CreateNew *bool Error *error + + // When is the type of provisioner to run at this point + When config.ProvisionerWhen } // TODO: test func (n *EvalApplyProvisioners) Eval(ctx EvalContext) (interface{}, error) { state := *n.State - if !*n.CreateNew { + if n.CreateNew != nil && !*n.CreateNew { // If we're not creating a new resource, then don't run provisioners return nil, nil } - if len(n.Resource.Provisioners) == 0 { + provs := n.filterProvisioners() + if len(provs) == 0 { // We have no provisioners, so don't do anything return nil, nil } + // taint tells us whether to enable tainting. + taint := n.When == config.ProvisionerWhenCreate + if n.Error != nil && *n.Error != nil { - // We're already errored creating, so mark as tainted and continue - state.Tainted = true + if taint { + state.Tainted = true + } // We're already tainted, so just return out return nil, nil @@ -176,10 +205,11 @@ func (n *EvalApplyProvisioners) Eval(ctx EvalContext) (interface{}, error) { // If there are no errors, then we append it to our output error // if we have one, otherwise we just output it. - err := n.apply(ctx) + err := n.apply(ctx, provs) if err != nil { - // Provisioning failed, so mark the resource as tainted - state.Tainted = true + if taint { + state.Tainted = true + } if n.Error != nil { *n.Error = multierror.Append(*n.Error, err) @@ -201,7 +231,29 @@ func (n *EvalApplyProvisioners) Eval(ctx EvalContext) (interface{}, error) { return nil, nil } -func (n *EvalApplyProvisioners) apply(ctx EvalContext) error { +// filterProvisioners filters the provisioners on the resource to only +// the provisioners specified by the "when" option. +func (n *EvalApplyProvisioners) filterProvisioners() []*config.Provisioner { + // Fast path the zero case + if n.Resource == nil { + return nil + } + + if len(n.Resource.Provisioners) == 0 { + return nil + } + + result := make([]*config.Provisioner, 0, len(n.Resource.Provisioners)) + for _, p := range n.Resource.Provisioners { + if p.When == n.When { + result = append(result, p) + } + } + + return result +} + +func (n *EvalApplyProvisioners) apply(ctx EvalContext, provs []*config.Provisioner) error { state := *n.State // Store the original connection info, restore later @@ -210,7 +262,7 @@ func (n *EvalApplyProvisioners) apply(ctx EvalContext) error { state.Ephemeral.ConnInfo = origConnInfo }() - for _, prov := range n.Resource.Provisioners { + for _, prov := range provs { // Get the provisioner provisioner := ctx.Provisioner(prov.Type) @@ -275,19 +327,31 @@ func (n *EvalApplyProvisioners) apply(ctx EvalContext) error { // Invoke the Provisioner output := CallbackUIOutput{OutputFn: outputFn} - if err := provisioner.Apply(&output, state, provConfig); err != nil { - return err - } + applyErr := provisioner.Apply(&output, state, provConfig) - { - // Call post hook - err := ctx.Hook(func(h Hook) (HookAction, error) { - return h.PostProvision(n.Info, prov.Type) - }) - if err != nil { - return err + // Call post hook + hookErr := ctx.Hook(func(h Hook) (HookAction, error) { + return h.PostProvision(n.Info, prov.Type, applyErr) + }) + + // Handle the error before we deal with the hook + if applyErr != nil { + // Determine failure behavior + switch prov.OnFailure { + case config.ProvisionerOnFailureContinue: + log.Printf( + "[INFO] apply: %s [%s]: error during provision, continue requested", + n.Info.Id, prov.Type) + + case config.ProvisionerOnFailureFail: + return applyErr } } + + // Deal with the hook + if hookErr != nil { + return hookErr + } } return nil diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_context.go b/vendor/github.com/hashicorp/terraform/terraform/eval_context.go index f286751..a1f815b 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_context.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_context.go @@ -8,6 +8,10 @@ import ( // EvalContext is the interface that is given to eval nodes to execute. type EvalContext interface { + // Stopped returns a channel that is closed when evaluation is stopped + // via Terraform.Context.Stop() + Stopped() <-chan struct{} + // Path is the current module path. Path() []string diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_context_builtin.go b/vendor/github.com/hashicorp/terraform/terraform/eval_context_builtin.go index 032f79f..3dcfb22 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_context_builtin.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_context_builtin.go @@ -1,6 +1,7 @@ package terraform import ( + "context" "fmt" "log" "strings" @@ -12,6 +13,9 @@ import ( // BuiltinEvalContext is an EvalContext implementation that is used by // Terraform by default. type BuiltinEvalContext struct { + // StopContext is the context used to track whether we're complete + StopContext context.Context + // PathValue is the Path that this context is operating within. PathValue []string @@ -43,6 +47,15 @@ type BuiltinEvalContext struct { once sync.Once } +func (ctx *BuiltinEvalContext) Stopped() <-chan struct{} { + // This can happen during tests. During tests, we just block forever. + if ctx.StopContext == nil { + return nil + } + + return ctx.StopContext.Done() +} + func (ctx *BuiltinEvalContext) Hook(fn func(Hook) (HookAction, error)) error { for _, h := range ctx.Hooks { action, err := fn(h) diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_context_mock.go b/vendor/github.com/hashicorp/terraform/terraform/eval_context_mock.go index 4f5c23b..4f90d5b 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_context_mock.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_context_mock.go @@ -9,6 +9,9 @@ import ( // MockEvalContext is a mock version of EvalContext that can be used // for tests. type MockEvalContext struct { + StoppedCalled bool + StoppedValue <-chan struct{} + HookCalled bool HookHook Hook HookError error @@ -85,6 +88,11 @@ type MockEvalContext struct { StateLock *sync.RWMutex } +func (c *MockEvalContext) Stopped() <-chan struct{} { + c.StoppedCalled = true + return c.StoppedValue +} + func (c *MockEvalContext) Hook(fn func(Hook) (HookAction, error)) error { c.HookCalled = true if c.HookHook != nil { diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_diff.go b/vendor/github.com/hashicorp/terraform/terraform/eval_diff.go index 717d951..6f09526 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_diff.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_diff.go @@ -152,6 +152,7 @@ func (n *EvalDiff) Eval(ctx EvalContext) (interface{}, error) { }) } + // filter out ignored resources if err := n.processIgnoreChanges(diff); err != nil { return nil, err } @@ -190,72 +191,81 @@ func (n *EvalDiff) processIgnoreChanges(diff *InstanceDiff) error { return nil } - changeType := diff.ChangeType() - // If we're just creating the resource, we shouldn't alter the // Diff at all - if changeType == DiffCreate { + if diff.ChangeType() == DiffCreate { return nil } // If the resource has been tainted then we don't process ignore changes // since we MUST recreate the entire resource. - if diff.DestroyTainted { + if diff.GetDestroyTainted() { return nil } + attrs := diff.CopyAttributes() + + // get the complete set of keys we want to ignore ignorableAttrKeys := make(map[string]bool) for _, ignoredKey := range ignoreChanges { - for k := range diff.CopyAttributes() { + for k := range attrs { if ignoredKey == "*" || strings.HasPrefix(k, ignoredKey) { ignorableAttrKeys[k] = true } } } - // If we are replacing the resource, then we expect there to be a bunch of - // extraneous attribute diffs we need to filter out for the other - // non-requires-new attributes going from "" -> "configval" or "" -> - // "". Filtering these out allows us to see if we might be able to - // skip this diff altogether. - if changeType == DiffDestroyCreate { - for k, v := range diff.CopyAttributes() { - if v.Empty() || v.NewComputed { - ignorableAttrKeys[k] = true - } - } - - // Here we emulate the implementation of diff.RequiresNew() with one small - // tweak, we ignore the "id" attribute diff that gets added by EvalDiff, - // since that was added in reaction to RequiresNew being true. - requiresNewAfterIgnores := false - for k, v := range diff.CopyAttributes() { + // If the resource was being destroyed, check to see if we can ignore the + // reason for it being destroyed. + if diff.GetDestroy() { + for k, v := range attrs { if k == "id" { + // id will always be changed if we intended to replace this instance continue } - if _, ok := ignorableAttrKeys[k]; ok { + if v.Empty() || v.NewComputed { continue } - if v.RequiresNew == true { - requiresNewAfterIgnores = true + + // If any RequiresNew attribute isn't ignored, we need to keep the diff + // as-is to be able to replace the resource. + if v.RequiresNew && !ignorableAttrKeys[k] { + return nil } } - // If we still require resource replacement after ignores, we - // can't touch the diff, as all of the attributes will be - // required to process the replacement. - if requiresNewAfterIgnores { - return nil + // Now that we know that we aren't replacing the instance, we can filter + // out all the empty and computed attributes. There may be a bunch of + // extraneous attribute diffs for the other non-requires-new attributes + // going from "" -> "configval" or "" -> "". + // We must make sure any flatmapped containers are filterred (or not) as a + // whole. + containers := groupContainers(diff) + keep := map[string]bool{} + for _, v := range containers { + if v.keepDiff() { + // At least one key has changes, so list all the sibling keys + // to keep in the diff. + for k := range v { + keep[k] = true + } + } } - // Here we undo the two reactions to RequireNew in EvalDiff - the "id" - // attribute diff and the Destroy boolean field - log.Printf("[DEBUG] Removing 'id' diff and setting Destroy to false " + - "because after ignore_changes, this diff no longer requires replacement") - diff.DelAttribute("id") - diff.SetDestroy(false) + for k, v := range attrs { + if (v.Empty() || v.NewComputed) && !keep[k] { + ignorableAttrKeys[k] = true + } + } } + // Here we undo the two reactions to RequireNew in EvalDiff - the "id" + // attribute diff and the Destroy boolean field + log.Printf("[DEBUG] Removing 'id' diff and setting Destroy to false " + + "because after ignore_changes, this diff no longer requires replacement") + diff.DelAttribute("id") + diff.SetDestroy(false) + // If we didn't hit any of our early exit conditions, we can filter the diff. for k := range ignorableAttrKeys { log.Printf("[DEBUG] [EvalIgnoreChanges] %s - Ignoring diff attribute: %s", @@ -266,6 +276,46 @@ func (n *EvalDiff) processIgnoreChanges(diff *InstanceDiff) error { return nil } +// a group of key-*ResourceAttrDiff pairs from the same flatmapped container +type flatAttrDiff map[string]*ResourceAttrDiff + +// we need to keep all keys if any of them have a diff +func (f flatAttrDiff) keepDiff() bool { + for _, v := range f { + if !v.Empty() && !v.NewComputed { + return true + } + } + return false +} + +// sets, lists and maps need to be compared for diff inclusion as a whole, so +// group the flatmapped keys together for easier comparison. +func groupContainers(d *InstanceDiff) map[string]flatAttrDiff { + isIndex := multiVal.MatchString + containers := map[string]flatAttrDiff{} + attrs := d.CopyAttributes() + // we need to loop once to find the index key + for k := range attrs { + if isIndex(k) { + // add the key, always including the final dot to fully qualify it + containers[k[:len(k)-1]] = flatAttrDiff{} + } + } + + // loop again to find all the sub keys + for prefix, values := range containers { + for k, attrDiff := range attrs { + // we include the index value as well, since it could be part of the diff + if strings.HasPrefix(k, prefix) { + values[k] = attrDiff + } + } + } + + return containers +} + // EvalDiffDestroy is an EvalNode implementation that returns a plain // destroy diff. type EvalDiffDestroy struct { diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_provider.go b/vendor/github.com/hashicorp/terraform/terraform/eval_provider.go index 61efcc2..092fd18 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_provider.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_provider.go @@ -30,6 +30,11 @@ func (n *EvalBuildProviderConfig) Eval(ctx EvalContext) (interface{}, error) { // If we have a configuration set, then merge that in if input := ctx.ProviderInput(n.Provider); input != nil { + // "input" is a map of the subset of config values that were known + // during the input walk, set by EvalInputProvider. Note that + // in particular it does *not* include attributes that had + // computed values at input time; those appear *only* in + // "cfg" here. rc, err := config.NewRawConfig(input) if err != nil { return nil, err @@ -136,7 +141,21 @@ func (n *EvalInputProvider) Eval(ctx EvalContext) (interface{}, error) { // Set the input that we received so that child modules don't attempt // to ask for input again. if config != nil && len(config.Config) > 0 { - ctx.SetProviderInput(n.Name, config.Config) + // This repository of provider input results on the context doesn't + // retain config.ComputedKeys, so we need to filter those out here + // in order that later users of this data won't try to use the unknown + // value placeholder as if it were a literal value. This map is just + // of known values we've been able to complete so far; dynamic stuff + // will be merged in by EvalBuildProviderConfig on subsequent + // (post-input) walks. + confMap := config.Config + if config.ComputedKeys != nil { + for _, key := range config.ComputedKeys { + delete(confMap, key) + } + } + + ctx.SetProviderInput(n.Name, confMap) } else { ctx.SetProviderInput(n.Name, map[string]interface{}{}) } diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_sequence.go b/vendor/github.com/hashicorp/terraform/terraform/eval_sequence.go index 6c3c6a6..82d8178 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_sequence.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_sequence.go @@ -7,6 +7,10 @@ type EvalSequence struct { func (n *EvalSequence) Eval(ctx EvalContext) (interface{}, error) { for _, n := range n.Nodes { + if n == nil { + continue + } + if _, err := EvalRaw(n, ctx); err != nil { return nil, err } diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_validate.go b/vendor/github.com/hashicorp/terraform/terraform/eval_validate.go index 9ae221a..478aa64 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_validate.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_validate.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/hashicorp/terraform/config" + "github.com/mitchellh/mapstructure" ) // EvalValidateError is the error structure returned if there were @@ -42,6 +43,7 @@ func (n *EvalValidateCount) Eval(ctx EvalContext) (interface{}, error) { c[n.Resource.RawCount.Key] = "1" count = 1 } + err = nil if count < 0 { errs = append(errs, fmt.Errorf( @@ -84,12 +86,31 @@ func (n *EvalValidateProvider) Eval(ctx EvalContext) (interface{}, error) { type EvalValidateProvisioner struct { Provisioner *ResourceProvisioner Config **ResourceConfig + ConnConfig **ResourceConfig } func (n *EvalValidateProvisioner) Eval(ctx EvalContext) (interface{}, error) { provisioner := *n.Provisioner config := *n.Config - warns, errs := provisioner.Validate(config) + var warns []string + var errs []error + + { + // Validate the provisioner's own config first + w, e := provisioner.Validate(config) + warns = append(warns, w...) + errs = append(errs, e...) + } + + { + // Now validate the connection config, which might either be from + // the provisioner block itself or inherited from the resource's + // shared connection info. + w, e := n.validateConnConfig(*n.ConnConfig) + warns = append(warns, w...) + errs = append(errs, e...) + } + if len(warns) == 0 && len(errs) == 0 { return nil, nil } @@ -100,6 +121,64 @@ func (n *EvalValidateProvisioner) Eval(ctx EvalContext) (interface{}, error) { } } +func (n *EvalValidateProvisioner) validateConnConfig(connConfig *ResourceConfig) (warns []string, errs []error) { + // We can't comprehensively validate the connection config since its + // final structure is decided by the communicator and we can't instantiate + // that until we have a complete instance state. However, we *can* catch + // configuration keys that are not valid for *any* communicator, catching + // typos early rather than waiting until we actually try to run one of + // the resource's provisioners. + + type connConfigSuperset struct { + // All attribute types are interface{} here because at this point we + // may still have unresolved interpolation expressions, which will + // appear as strings regardless of the final goal type. + + Type interface{} `mapstructure:"type"` + User interface{} `mapstructure:"user"` + Password interface{} `mapstructure:"password"` + Host interface{} `mapstructure:"host"` + Port interface{} `mapstructure:"port"` + Timeout interface{} `mapstructure:"timeout"` + ScriptPath interface{} `mapstructure:"script_path"` + + // For type=ssh only (enforced in ssh communicator) + PrivateKey interface{} `mapstructure:"private_key"` + Agent interface{} `mapstructure:"agent"` + BastionHost interface{} `mapstructure:"bastion_host"` + BastionPort interface{} `mapstructure:"bastion_port"` + BastionUser interface{} `mapstructure:"bastion_user"` + BastionPassword interface{} `mapstructure:"bastion_password"` + BastionPrivateKey interface{} `mapstructure:"bastion_private_key"` + + // For type=winrm only (enforced in winrm communicator) + HTTPS interface{} `mapstructure:"https"` + Insecure interface{} `mapstructure:"insecure"` + CACert interface{} `mapstructure:"cacert"` + } + + var metadata mapstructure.Metadata + decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ + Metadata: &metadata, + Result: &connConfigSuperset{}, // result is disregarded; we only care about unused keys + }) + if err != nil { + // should never happen + errs = append(errs, err) + return + } + + if err := decoder.Decode(connConfig.Config); err != nil { + errs = append(errs, err) + return + } + + for _, attrName := range metadata.Unused { + errs = append(errs, fmt.Errorf("unknown 'connection' argument %q", attrName)) + } + return +} + // EvalValidateResource is an EvalNode implementation that validates // the configuration of a resource. type EvalValidateResource struct { diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_validate_selfref.go b/vendor/github.com/hashicorp/terraform/terraform/eval_validate_selfref.go new file mode 100644 index 0000000..ae4436a --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_validate_selfref.go @@ -0,0 +1,74 @@ +package terraform + +import ( + "fmt" + + "github.com/hashicorp/terraform/config" +) + +// EvalValidateResourceSelfRef is an EvalNode implementation that validates that +// a configuration doesn't contain a reference to the resource itself. +// +// This must be done prior to interpolating configuration in order to avoid +// any infinite loop scenarios. +type EvalValidateResourceSelfRef struct { + Addr **ResourceAddress + Config **config.RawConfig +} + +func (n *EvalValidateResourceSelfRef) Eval(ctx EvalContext) (interface{}, error) { + addr := *n.Addr + conf := *n.Config + + // Go through the variables and find self references + var errs []error + for k, raw := range conf.Variables { + rv, ok := raw.(*config.ResourceVariable) + if !ok { + continue + } + + // Build an address from the variable + varAddr := &ResourceAddress{ + Path: addr.Path, + Mode: rv.Mode, + Type: rv.Type, + Name: rv.Name, + Index: rv.Index, + InstanceType: TypePrimary, + } + + // If the variable access is a multi-access (*), then we just + // match the index so that we'll match our own addr if everything + // else matches. + if rv.Multi && rv.Index == -1 { + varAddr.Index = addr.Index + } + + // This is a weird thing where ResourceAddres has index "-1" when + // index isn't set at all. This means index "0" for resource access. + // So, if we have this scenario, just set our varAddr to -1 so it + // matches. + if addr.Index == -1 && varAddr.Index == 0 { + varAddr.Index = -1 + } + + // If the addresses match, then this is a self reference + if varAddr.Equals(addr) && varAddr.Index == addr.Index { + errs = append(errs, fmt.Errorf( + "%s: self reference not allowed: %q", + addr, k)) + } + } + + // If no errors, no errors! + if len(errs) == 0 { + return nil, nil + } + + // Wrap the errors in the proper wrapper so we can handle validation + // formatting properly upstream. + return nil, &EvalValidateError{ + Errors: errs, + } +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/eval_variable.go b/vendor/github.com/hashicorp/terraform/terraform/eval_variable.go index 47bd2ea..b39a4d1 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/eval_variable.go +++ b/vendor/github.com/hashicorp/terraform/terraform/eval_variable.go @@ -114,7 +114,6 @@ type EvalVariableBlock struct { VariableValues map[string]interface{} } -// TODO: test func (n *EvalVariableBlock) Eval(ctx EvalContext) (interface{}, error) { // Clear out the existing mapping for k, _ := range n.VariableValues { @@ -174,9 +173,15 @@ func (n *EvalVariableBlock) setUnknownVariableValueForPath(path string) error { // Otherwise find the correct point in the tree and then set to unknown var current interface{} = n.VariableValues[pathComponents[0]] for i := 1; i < len(pathComponents); i++ { - switch current.(type) { - case []interface{}, []map[string]interface{}: - tCurrent := current.([]interface{}) + switch tCurrent := current.(type) { + case []interface{}: + index, err := strconv.Atoi(pathComponents[i]) + if err != nil { + return fmt.Errorf("Cannot convert %s to slice index in path %s", + pathComponents[i], path) + } + current = tCurrent[index] + case []map[string]interface{}: index, err := strconv.Atoi(pathComponents[i]) if err != nil { return fmt.Errorf("Cannot convert %s to slice index in path %s", @@ -184,7 +189,6 @@ func (n *EvalVariableBlock) setUnknownVariableValueForPath(path string) error { } current = tCurrent[index] case map[string]interface{}: - tCurrent := current.(map[string]interface{}) if val, hasVal := tCurrent[pathComponents[i]]; hasVal { current = val continue diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph.go b/vendor/github.com/hashicorp/terraform/terraform/graph.go index 6025849..48ce6a3 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph.go @@ -5,7 +5,6 @@ import ( "log" "runtime/debug" "strings" - "sync" "github.com/hashicorp/terraform/dag" ) @@ -17,8 +16,7 @@ const RootModuleName = "root" var RootModulePath = []string{RootModuleName} // Graph represents the graph that Terraform uses to represent resources -// and their dependencies. Each graph represents only one module, but it -// can contain further modules, which themselves have their own graph. +// and their dependencies. type Graph struct { // Graph is the actual DAG. This is embedded so you can call the DAG // methods directly. @@ -29,179 +27,16 @@ type Graph struct { // RootModuleName Path []string - // annotations are the annotations that are added to vertices. Annotations - // are arbitrary metadata taht is used for various logic. Annotations - // should have unique keys that are referenced via constants. - annotations map[dag.Vertex]map[string]interface{} - - // dependableMap is a lookaside table for fast lookups for connecting - // dependencies by their GraphNodeDependable value to avoid O(n^3)-like - // situations and turn them into O(1) with respect to the number of new - // edges. - dependableMap map[string]dag.Vertex - // debugName is a name for reference in the debug output. This is usually // to indicate what topmost builder was, and if this graph is a shadow or // not. debugName string - - once sync.Once } func (g *Graph) DirectedGraph() dag.Grapher { return &g.AcyclicGraph } -// Annotations returns the annotations that are configured for the -// given vertex. The map is guaranteed to be non-nil but may be empty. -// -// The returned map may be modified to modify the annotations of the -// vertex. -func (g *Graph) Annotations(v dag.Vertex) map[string]interface{} { - g.once.Do(g.init) - - // If this vertex isn't in the graph, then just return an empty map - if !g.HasVertex(v) { - return map[string]interface{}{} - } - - // Get the map, if it doesn't exist yet then initialize it - m, ok := g.annotations[v] - if !ok { - m = make(map[string]interface{}) - g.annotations[v] = m - } - - return m -} - -// Add is the same as dag.Graph.Add. -func (g *Graph) Add(v dag.Vertex) dag.Vertex { - g.once.Do(g.init) - - // Call upwards to add it to the actual graph - g.Graph.Add(v) - - // If this is a depend-able node, then store the lookaside info - if dv, ok := v.(GraphNodeDependable); ok { - for _, n := range dv.DependableName() { - g.dependableMap[n] = v - } - } - - // If this initializes annotations, then do that - if av, ok := v.(GraphNodeAnnotationInit); ok { - as := g.Annotations(v) - for k, v := range av.AnnotationInit() { - as[k] = v - } - } - - return v -} - -// Remove is the same as dag.Graph.Remove -func (g *Graph) Remove(v dag.Vertex) dag.Vertex { - g.once.Do(g.init) - - // If this is a depend-able node, then remove the lookaside info - if dv, ok := v.(GraphNodeDependable); ok { - for _, n := range dv.DependableName() { - delete(g.dependableMap, n) - } - } - - // Remove the annotations - delete(g.annotations, v) - - // Call upwards to remove it from the actual graph - return g.Graph.Remove(v) -} - -// Replace is the same as dag.Graph.Replace -func (g *Graph) Replace(o, n dag.Vertex) bool { - g.once.Do(g.init) - - // Go through and update our lookaside to point to the new vertex - for k, v := range g.dependableMap { - if v == o { - if _, ok := n.(GraphNodeDependable); ok { - g.dependableMap[k] = n - } else { - delete(g.dependableMap, k) - } - } - } - - // Move the annotation if it exists - if m, ok := g.annotations[o]; ok { - g.annotations[n] = m - delete(g.annotations, o) - } - - return g.Graph.Replace(o, n) -} - -// ConnectDependent connects a GraphNodeDependent to all of its -// GraphNodeDependables. It returns the list of dependents it was -// unable to connect to. -func (g *Graph) ConnectDependent(raw dag.Vertex) []string { - v, ok := raw.(GraphNodeDependent) - if !ok { - return nil - } - - return g.ConnectTo(v, v.DependentOn()) -} - -// ConnectDependents goes through the graph, connecting all the -// GraphNodeDependents to GraphNodeDependables. This is safe to call -// multiple times. -// -// To get details on whether dependencies could be found/made, the more -// specific ConnectDependent should be used. -func (g *Graph) ConnectDependents() { - for _, v := range g.Vertices() { - if dv, ok := v.(GraphNodeDependent); ok { - g.ConnectDependent(dv) - } - } -} - -// ConnectFrom creates an edge by finding the source from a DependableName -// and connecting it to the specific vertex. -func (g *Graph) ConnectFrom(source string, target dag.Vertex) { - g.once.Do(g.init) - - if source := g.dependableMap[source]; source != nil { - g.Connect(dag.BasicEdge(source, target)) - } -} - -// ConnectTo connects a vertex to a raw string of targets that are the -// result of DependableName, and returns the list of targets that are missing. -func (g *Graph) ConnectTo(v dag.Vertex, targets []string) []string { - g.once.Do(g.init) - - var missing []string - for _, t := range targets { - if dest := g.dependableMap[t]; dest != nil { - g.Connect(dag.BasicEdge(v, dest)) - } else { - missing = append(missing, t) - } - } - - return missing -} - -// Dependable finds the vertices in the graph that have the given dependable -// names and returns them. -func (g *Graph) Dependable(n string) dag.Vertex { - // TODO: do we need this? - return nil -} - // Walk walks the graph with the given walker for callbacks. The graph // will be walked with full parallelism, so the walker should expect // to be called in concurrently. @@ -209,16 +44,6 @@ func (g *Graph) Walk(walker GraphWalker) error { return g.walk(walker) } -func (g *Graph) init() { - if g.annotations == nil { - g.annotations = make(map[dag.Vertex]map[string]interface{}) - } - - if g.dependableMap == nil { - g.dependableMap = make(map[string]dag.Vertex) - } -} - func (g *Graph) walk(walker GraphWalker) error { // The callbacks for enter/exiting a graph ctx := walker.EnterPath(g.Path) @@ -345,30 +170,3 @@ func (g *Graph) walk(walker GraphWalker) error { return g.AcyclicGraph.Walk(walkFn) } - -// GraphNodeAnnotationInit is an interface that allows a node to -// initialize it's annotations. -// -// AnnotationInit will be called _once_ when the node is added to a -// graph for the first time and is expected to return it's initial -// annotations. -type GraphNodeAnnotationInit interface { - AnnotationInit() map[string]interface{} -} - -// GraphNodeDependable is an interface which says that a node can be -// depended on (an edge can be placed between this node and another) according -// to the well-known name returned by DependableName. -// -// DependableName can return multiple names it is known by. -type GraphNodeDependable interface { - DependableName() []string -} - -// GraphNodeDependent is an interface which says that a node depends -// on another GraphNodeDependable by some name. By implementing this -// interface, Graph.ConnectDependents() can be called multiple times -// safely and efficiently. -type GraphNodeDependent interface { - DependentOn() []string -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_builder.go b/vendor/github.com/hashicorp/terraform/terraform/graph_builder.go index fb850df..6374bb9 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_builder.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_builder.go @@ -4,8 +4,6 @@ import ( "fmt" "log" "strings" - - "github.com/hashicorp/terraform/config/module" ) // GraphBuilder is an interface that can be implemented and used with @@ -77,160 +75,3 @@ func (b *BasicGraphBuilder) Build(path []string) (*Graph, error) { return g, nil } - -// BuiltinGraphBuilder is responsible for building the complete graph that -// Terraform uses for execution. It is an opinionated builder that defines -// the step order required to build a complete graph as is used and expected -// by Terraform. -// -// If you require a custom graph, you'll have to build it up manually -// on your own by building a new GraphBuilder implementation. -type BuiltinGraphBuilder struct { - // Root is the root module of the graph to build. - Root *module.Tree - - // Diff is the diff. The proper module diffs will be looked up. - Diff *Diff - - // State is the global state. The proper module states will be looked - // up by graph path. - State *State - - // Providers is the list of providers supported. - Providers []string - - // Provisioners is the list of provisioners supported. - Provisioners []string - - // Targets is the user-specified list of resources to target. - Targets []string - - // Destroy is set to true when we're in a `terraform destroy` or a - // `terraform plan -destroy` - Destroy bool - - // Determines whether the GraphBuilder should perform graph validation before - // returning the Graph. Generally you want this to be done, except when you'd - // like to inspect a problematic graph. - Validate bool - - // Verbose is set to true when the graph should be built "worst case", - // skipping any prune steps. This is used for early cycle detection during - // Validate and for manual inspection via `terraform graph -verbose`. - Verbose bool -} - -// Build builds the graph according to the steps returned by Steps. -func (b *BuiltinGraphBuilder) Build(path []string) (*Graph, error) { - basic := &BasicGraphBuilder{ - Steps: b.Steps(path), - Validate: b.Validate, - Name: "BuiltinGraphBuilder", - } - - return basic.Build(path) -} - -// Steps returns the ordered list of GraphTransformers that must be executed -// to build a complete graph. -func (b *BuiltinGraphBuilder) Steps(path []string) []GraphTransformer { - steps := []GraphTransformer{ - // Create all our resources from the configuration and state - &ConfigTransformerOld{Module: b.Root}, - &OrphanTransformer{ - State: b.State, - Module: b.Root, - }, - - // Output-related transformations - &AddOutputOrphanTransformer{State: b.State}, - - // Provider-related transformations - &MissingProviderTransformer{Providers: b.Providers}, - &ProviderTransformer{}, - &DisableProviderTransformerOld{}, - - // Provisioner-related transformations - &MissingProvisionerTransformer{Provisioners: b.Provisioners}, - &ProvisionerTransformer{}, - - // Run our vertex-level transforms - &VertexTransformer{ - Transforms: []GraphVertexTransformer{ - // Expand any statically expanded nodes, such as module graphs - &ExpandTransform{ - Builder: b, - }, - }, - }, - - // Flatten stuff - &FlattenTransformer{}, - - // Make sure all the connections that are proxies are connected through - &ProxyTransformer{}, - } - - // If we're on the root path, then we do a bunch of other stuff. - // We don't do the following for modules. - if len(path) <= 1 { - steps = append(steps, - // Optionally reduces the graph to a user-specified list of targets and - // their dependencies. - &TargetsTransformer{Targets: b.Targets, Destroy: b.Destroy}, - - // Create orphan output nodes - &OrphanOutputTransformer{Module: b.Root, State: b.State}, - - // Prune the providers. This must happen only once because flattened - // modules might depend on empty providers. - &PruneProviderTransformer{}, - - // Create the destruction nodes - &DestroyTransformer{FullDestroy: b.Destroy}, - b.conditional(&conditionalOpts{ - If: func() bool { return !b.Destroy }, - Then: &CreateBeforeDestroyTransformer{}, - }), - b.conditional(&conditionalOpts{ - If: func() bool { return !b.Verbose }, - Then: &PruneDestroyTransformer{Diff: b.Diff, State: b.State}, - }), - - // Remove the noop nodes - &PruneNoopTransformer{Diff: b.Diff, State: b.State}, - - // Insert nodes to close opened plugin connections - &CloseProviderTransformer{}, - &CloseProvisionerTransformer{}, - - // Perform the transitive reduction to make our graph a bit - // more sane if possible (it usually is possible). - &TransitiveReductionTransformer{}, - ) - } - - // Make sure we have a single root - steps = append(steps, &RootTransformer{}) - - // Remove nils - for i, s := range steps { - if s == nil { - steps = append(steps[:i], steps[i+1:]...) - } - } - - return steps -} - -type conditionalOpts struct { - If func() bool - Then GraphTransformer -} - -func (b *BuiltinGraphBuilder) conditional(o *conditionalOpts) GraphTransformer { - if o.If != nil && o.Then != nil && o.If() { - return o.Then - } - return nil -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_apply.go b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_apply.go index 75de537..6124258 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_apply.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_apply.go @@ -28,6 +28,12 @@ type ApplyGraphBuilder struct { // Provisioners is the list of provisioners supported. Provisioners []string + // Targets are resources to target. This is only required to make sure + // unnecessary outputs aren't included in the apply graph. The plan + // builder successfully handles targeting resources. In the future, + // outputs should go into the diff so that this is unnecessary. + Targets []string + // DisableReduce, if true, will not reduce the graph. Great for testing. DisableReduce bool @@ -96,13 +102,8 @@ func (b *ApplyGraphBuilder) Steps() []GraphTransformer { ), // Provisioner-related transformations - GraphTransformIf( - func() bool { return !b.Destroy }, - GraphTransformMulti( - &MissingProvisionerTransformer{Provisioners: b.Provisioners}, - &ProvisionerTransformer{}, - ), - ), + &MissingProvisionerTransformer{Provisioners: b.Provisioners}, + &ProvisionerTransformer{}, // Add root variables &RootVariableTransformer{Module: b.Module}, @@ -119,6 +120,9 @@ func (b *ApplyGraphBuilder) Steps() []GraphTransformer { // Add the node to fix the state count boundaries &CountBoundaryTransformer{}, + // Target + &TargetsTransformer{Targets: b.Targets}, + // Single root &RootTransformer{}, } diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_import.go b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_import.go index 46bd977..7fa76de 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_import.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_import.go @@ -47,7 +47,7 @@ func (b *ImportGraphBuilder) Steps() []GraphTransformer { steps := []GraphTransformer{ // Create all our resources from the configuration and state - &ConfigTransformerOld{Module: mod}, + &ConfigTransformer{Module: mod}, // Add the import steps &ImportStateTransformer{Targets: b.ImportTargets}, @@ -55,8 +55,8 @@ func (b *ImportGraphBuilder) Steps() []GraphTransformer { // Provider-related transformations &MissingProviderTransformer{Providers: b.Providers, Concrete: concreteProvider}, &ProviderTransformer{}, - &DisableProviderTransformerOld{}, - &PruneProviderTransformer{}, + &DisableProviderTransformer{}, + &ParentProviderTransformer{}, &AttachProviderConfigTransformer{Module: mod}, // This validates that the providers only depend on variables diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_input.go b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_input.go new file mode 100644 index 0000000..0df48cd --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_input.go @@ -0,0 +1,27 @@ +package terraform + +import ( + "github.com/hashicorp/terraform/dag" +) + +// InputGraphBuilder creates the graph for the input operation. +// +// Unlike other graph builders, this is a function since it currently modifies +// and is based on the PlanGraphBuilder. The PlanGraphBuilder passed in will be +// modified and should not be used for any other operations. +func InputGraphBuilder(p *PlanGraphBuilder) GraphBuilder { + // We're going to customize the concrete functions + p.CustomConcrete = true + + // Set the provider to the normal provider. This will ask for input. + p.ConcreteProvider = func(a *NodeAbstractProvider) dag.Vertex { + return &NodeApplyableProvider{ + NodeAbstractProvider: a, + } + } + + // We purposely don't set any more concrete fields since the remainder + // should be no-ops. + + return p +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_plan.go b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_plan.go index 35961ee..275cb32 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_plan.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_plan.go @@ -1,6 +1,8 @@ package terraform import ( + "sync" + "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/dag" ) @@ -26,6 +28,9 @@ type PlanGraphBuilder struct { // Providers is the list of providers supported. Providers []string + // Provisioners is the list of provisioners supported. + Provisioners []string + // Targets are resources to target Targets []string @@ -34,6 +39,16 @@ type PlanGraphBuilder struct { // Validate will do structural validation of the graph. Validate bool + + // CustomConcrete can be set to customize the node types created + // for various parts of the plan. This is useful in order to customize + // the plan behavior. + CustomConcrete bool + ConcreteProvider ConcreteProviderNodeFunc + ConcreteResource ConcreteResourceNodeFunc + ConcreteResourceOrphan ConcreteResourceNodeFunc + + once sync.Once } // See GraphBuilder @@ -47,29 +62,12 @@ func (b *PlanGraphBuilder) Build(path []string) (*Graph, error) { // See GraphBuilder func (b *PlanGraphBuilder) Steps() []GraphTransformer { - // Custom factory for creating providers. - concreteProvider := func(a *NodeAbstractProvider) dag.Vertex { - return &NodeApplyableProvider{ - NodeAbstractProvider: a, - } - } - - concreteResource := func(a *NodeAbstractResource) dag.Vertex { - return &NodePlannableResource{ - NodeAbstractResource: a, - } - } - - concreteResourceOrphan := func(a *NodeAbstractResource) dag.Vertex { - return &NodePlannableResourceOrphan{ - NodeAbstractResource: a, - } - } + b.once.Do(b.init) steps := []GraphTransformer{ // Creates all the resources represented in the config &ConfigTransformer{ - Concrete: concreteResource, + Concrete: b.ConcreteResource, Module: b.Module, }, @@ -78,7 +76,7 @@ func (b *PlanGraphBuilder) Steps() []GraphTransformer { // Add orphan resources &OrphanResourceTransformer{ - Concrete: concreteResourceOrphan, + Concrete: b.ConcreteResourceOrphan, State: b.State, Module: b.Module, }, @@ -93,12 +91,21 @@ func (b *PlanGraphBuilder) Steps() []GraphTransformer { &RootVariableTransformer{Module: b.Module}, // Create all the providers - &MissingProviderTransformer{Providers: b.Providers, Concrete: concreteProvider}, + &MissingProviderTransformer{Providers: b.Providers, Concrete: b.ConcreteProvider}, &ProviderTransformer{}, &DisableProviderTransformer{}, &ParentProviderTransformer{}, &AttachProviderConfigTransformer{Module: b.Module}, + // Provisioner-related transformations. Only add these if requested. + GraphTransformIf( + func() bool { return b.Provisioners != nil }, + GraphTransformMulti( + &MissingProvisionerTransformer{Provisioners: b.Provisioners}, + &ProvisionerTransformer{}, + ), + ), + // Add module variables &ModuleVariableTransformer{Module: b.Module}, @@ -121,3 +128,30 @@ func (b *PlanGraphBuilder) Steps() []GraphTransformer { return steps } + +func (b *PlanGraphBuilder) init() { + // Do nothing if the user requests customizing the fields + if b.CustomConcrete { + return + } + + b.ConcreteProvider = func(a *NodeAbstractProvider) dag.Vertex { + return &NodeApplyableProvider{ + NodeAbstractProvider: a, + } + } + + b.ConcreteResource = func(a *NodeAbstractResource) dag.Vertex { + return &NodePlannableResource{ + NodeAbstractCountResource: &NodeAbstractCountResource{ + NodeAbstractResource: a, + }, + } + } + + b.ConcreteResourceOrphan = func(a *NodeAbstractResource) dag.Vertex { + return &NodePlannableResourceOrphan{ + NodeAbstractResource: a, + } + } +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_refresh.go b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_refresh.go new file mode 100644 index 0000000..8fed21d --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_refresh.go @@ -0,0 +1,129 @@ +package terraform + +import ( + "github.com/hashicorp/terraform/config" + "github.com/hashicorp/terraform/config/module" + "github.com/hashicorp/terraform/dag" +) + +// RefreshGraphBuilder implements GraphBuilder and is responsible for building +// a graph for refreshing (updating the Terraform state). +// +// The primary difference between this graph and others: +// +// * Based on the state since it represents the only resources that +// need to be refreshed. +// +// * Ignores lifecycle options since no lifecycle events occur here. This +// simplifies the graph significantly since complex transforms such as +// create-before-destroy can be completely ignored. +// +type RefreshGraphBuilder struct { + // Module is the root module for the graph to build. + Module *module.Tree + + // State is the current state + State *State + + // Providers is the list of providers supported. + Providers []string + + // Targets are resources to target + Targets []string + + // DisableReduce, if true, will not reduce the graph. Great for testing. + DisableReduce bool + + // Validate will do structural validation of the graph. + Validate bool +} + +// See GraphBuilder +func (b *RefreshGraphBuilder) Build(path []string) (*Graph, error) { + return (&BasicGraphBuilder{ + Steps: b.Steps(), + Validate: b.Validate, + Name: "RefreshGraphBuilder", + }).Build(path) +} + +// See GraphBuilder +func (b *RefreshGraphBuilder) Steps() []GraphTransformer { + // Custom factory for creating providers. + concreteProvider := func(a *NodeAbstractProvider) dag.Vertex { + return &NodeApplyableProvider{ + NodeAbstractProvider: a, + } + } + + concreteResource := func(a *NodeAbstractResource) dag.Vertex { + return &NodeRefreshableResource{ + NodeAbstractResource: a, + } + } + + concreteDataResource := func(a *NodeAbstractResource) dag.Vertex { + return &NodeRefreshableDataResource{ + NodeAbstractCountResource: &NodeAbstractCountResource{ + NodeAbstractResource: a, + }, + } + } + + steps := []GraphTransformer{ + // Creates all the resources represented in the state + &StateTransformer{ + Concrete: concreteResource, + State: b.State, + }, + + // Creates all the data resources that aren't in the state + &ConfigTransformer{ + Concrete: concreteDataResource, + Module: b.Module, + Unique: true, + ModeFilter: true, + Mode: config.DataResourceMode, + }, + + // Attach the state + &AttachStateTransformer{State: b.State}, + + // Attach the configuration to any resources + &AttachResourceConfigTransformer{Module: b.Module}, + + // Add root variables + &RootVariableTransformer{Module: b.Module}, + + // Create all the providers + &MissingProviderTransformer{Providers: b.Providers, Concrete: concreteProvider}, + &ProviderTransformer{}, + &DisableProviderTransformer{}, + &ParentProviderTransformer{}, + &AttachProviderConfigTransformer{Module: b.Module}, + + // Add the outputs + &OutputTransformer{Module: b.Module}, + + // Add module variables + &ModuleVariableTransformer{Module: b.Module}, + + // Connect so that the references are ready for targeting. We'll + // have to connect again later for providers and so on. + &ReferenceTransformer{}, + + // Target + &TargetsTransformer{Targets: b.Targets}, + + // Single root + &RootTransformer{}, + } + + if !b.DisableReduce { + // Perform the transitive reduction to make our graph a bit + // more sane if possible (it usually is possible). + steps = append(steps, &TransitiveReductionTransformer{}) + } + + return steps +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_builder_validate.go b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_validate.go new file mode 100644 index 0000000..645ec7b --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_builder_validate.go @@ -0,0 +1,36 @@ +package terraform + +import ( + "github.com/hashicorp/terraform/dag" +) + +// ValidateGraphBuilder creates the graph for the validate operation. +// +// ValidateGraphBuilder is based on the PlanGraphBuilder. We do this so that +// we only have to validate what we'd normally plan anyways. The +// PlanGraphBuilder given will be modified so it shouldn't be used for anything +// else after calling this function. +func ValidateGraphBuilder(p *PlanGraphBuilder) GraphBuilder { + // We're going to customize the concrete functions + p.CustomConcrete = true + + // Set the provider to the normal provider. This will ask for input. + p.ConcreteProvider = func(a *NodeAbstractProvider) dag.Vertex { + return &NodeApplyableProvider{ + NodeAbstractProvider: a, + } + } + + p.ConcreteResource = func(a *NodeAbstractResource) dag.Vertex { + return &NodeValidatableResource{ + NodeAbstractCountResource: &NodeAbstractCountResource{ + NodeAbstractResource: a, + }, + } + } + + // We purposely don't set any other concrete types since they don't + // require validation. + + return p +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_config_node.go b/vendor/github.com/hashicorp/terraform/terraform/graph_config_node.go deleted file mode 100644 index 57d565c..0000000 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_config_node.go +++ /dev/null @@ -1,37 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform/dag" -) - -// graphNodeConfig is an interface that all graph nodes for the -// configuration graph need to implement in order to build the variable -// dependencies properly. -type graphNodeConfig interface { - dag.NamedVertex - - // All graph nodes should be dependent on other things, and able to - // be depended on. - GraphNodeDependable - GraphNodeDependent - - // ConfigType returns the type of thing in the configuration that - // this node represents, such as a resource, module, etc. - ConfigType() GraphNodeConfigType -} - -// GraphNodeAddressable is an interface that all graph nodes for the -// configuration graph need to implement in order to be be addressed / targeted -// properly. -type GraphNodeAddressable interface { - ResourceAddress() *ResourceAddress -} - -// GraphNodeTargetable is an interface for graph nodes to implement when they -// need to be told about incoming targets. This is useful for nodes that need -// to respect targets as they dynamically expand. Note that the list of targets -// provided will contain every target provided, and each implementing graph -// node must filter this list to targets considered relevant. -type GraphNodeTargetable interface { - SetTargets([]ResourceAddress) -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_module.go b/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_module.go deleted file mode 100644 index 8a6b522..0000000 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_module.go +++ /dev/null @@ -1,215 +0,0 @@ -package terraform - -import ( - "fmt" - "strings" - - "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/config/module" - "github.com/hashicorp/terraform/dag" -) - -// GraphNodeConfigModule represents a module within the configuration graph. -type GraphNodeConfigModule struct { - Path []string - Module *config.Module - Tree *module.Tree -} - -func (n *GraphNodeConfigModule) ConfigType() GraphNodeConfigType { - return GraphNodeConfigTypeModule -} - -func (n *GraphNodeConfigModule) DependableName() []string { - config := n.Tree.Config() - - result := make([]string, 1, len(config.Outputs)+1) - result[0] = n.Name() - for _, o := range config.Outputs { - result = append(result, fmt.Sprintf("%s.output.%s", n.Name(), o.Name)) - } - - return result -} - -func (n *GraphNodeConfigModule) DependentOn() []string { - vars := n.Module.RawConfig.Variables - result := make([]string, 0, len(vars)) - for _, v := range vars { - if vn := varNameForVar(v); vn != "" { - result = append(result, vn) - } - } - - return result -} - -func (n *GraphNodeConfigModule) Name() string { - return fmt.Sprintf("module.%s", n.Module.Name) -} - -// GraphNodeExpandable -func (n *GraphNodeConfigModule) Expand(b GraphBuilder) (GraphNodeSubgraph, error) { - // Build the graph first - graph, err := b.Build(n.Path) - if err != nil { - return nil, err - } - - { - // Add the destroy marker to the graph - t := &ModuleDestroyTransformerOld{} - if err := t.Transform(graph); err != nil { - return nil, err - } - } - - // Build the actual subgraph node - return &graphNodeModuleExpanded{ - Original: n, - Graph: graph, - Variables: make(map[string]interface{}), - }, nil -} - -// GraphNodeExpandable -func (n *GraphNodeConfigModule) ProvidedBy() []string { - // Build up the list of providers by simply going over our configuration - // to find the providers that are configured there as well as the - // providers that the resources use. - config := n.Tree.Config() - providers := make(map[string]struct{}) - for _, p := range config.ProviderConfigs { - providers[p.Name] = struct{}{} - } - for _, r := range config.Resources { - providers[resourceProvider(r.Type, r.Provider)] = struct{}{} - } - - // Turn the map into a string. This makes sure that the list is - // de-dupped since we could be going over potentially many resources. - result := make([]string, 0, len(providers)) - for p, _ := range providers { - result = append(result, p) - } - - return result -} - -// graphNodeModuleExpanded represents a module where the graph has -// been expanded. It stores the graph of the module as well as a reference -// to the map of variables. -type graphNodeModuleExpanded struct { - Original *GraphNodeConfigModule - Graph *Graph - - // Variables is a map of the input variables. This reference should - // be shared with ModuleInputTransformer in order to create a connection - // where the variables are set properly. - Variables map[string]interface{} -} - -func (n *graphNodeModuleExpanded) Name() string { - return fmt.Sprintf("%s (expanded)", dag.VertexName(n.Original)) -} - -func (n *graphNodeModuleExpanded) ConfigType() GraphNodeConfigType { - return GraphNodeConfigTypeModule -} - -// GraphNodeDependable -func (n *graphNodeModuleExpanded) DependableName() []string { - return n.Original.DependableName() -} - -// GraphNodeDependent -func (n *graphNodeModuleExpanded) DependentOn() []string { - return n.Original.DependentOn() -} - -// GraphNodeDotter impl. -func (n *graphNodeModuleExpanded) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": dag.VertexName(n.Original), - "shape": "component", - }, - } -} - -// GraphNodeEvalable impl. -func (n *graphNodeModuleExpanded) EvalTree() EvalNode { - var resourceConfig *ResourceConfig - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalInterpolate{ - Config: n.Original.Module.RawConfig, - Output: &resourceConfig, - }, - - &EvalVariableBlock{ - Config: &resourceConfig, - VariableValues: n.Variables, - }, - }, - } -} - -// GraphNodeFlattenable impl. -func (n *graphNodeModuleExpanded) FlattenGraph() *Graph { - graph := n.Subgraph().(*Graph) - input := n.Original.Module.RawConfig - - // Go over each vertex and do some modifications to the graph for - // flattening. We have to skip some nodes (graphNodeModuleSkippable) - // as well as setup the variable values. - for _, v := range graph.Vertices() { - // If this is a variable, then look it up in the raw configuration. - // If it exists in the raw configuration, set the value of it. - if vn, ok := v.(*GraphNodeConfigVariable); ok && input != nil { - key := vn.VariableName() - if v, ok := input.Raw[key]; ok { - config, err := config.NewRawConfig(map[string]interface{}{ - key: v, - }) - if err != nil { - // This shouldn't happen because it is already in - // a RawConfig above meaning it worked once before. - panic(err) - } - - // Set the variable value so it is interpolated properly. - // Also set the module so we set the value on it properly. - vn.Module = graph.Path[len(graph.Path)-1] - vn.Value = config - } - } - } - - return graph -} - -// GraphNodeSubgraph impl. -func (n *graphNodeModuleExpanded) Subgraph() dag.Grapher { - return n.Graph -} - -func modulePrefixStr(p []string) string { - parts := make([]string, 0, len(p)*2) - for _, p := range p[1:] { - parts = append(parts, "module", p) - } - - return strings.Join(parts, ".") -} - -func modulePrefixList(result []string, prefix string) []string { - if prefix != "" { - for i, v := range result { - result[i] = fmt.Sprintf("%s.%s", prefix, v) - } - } - - return result -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_output.go b/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_output.go deleted file mode 100644 index 0704a0c..0000000 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_output.go +++ /dev/null @@ -1,106 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/dag" -) - -// GraphNodeConfigOutput represents an output configured within the -// configuration. -type GraphNodeConfigOutput struct { - Output *config.Output -} - -func (n *GraphNodeConfigOutput) Name() string { - return fmt.Sprintf("output.%s", n.Output.Name) -} - -func (n *GraphNodeConfigOutput) ConfigType() GraphNodeConfigType { - return GraphNodeConfigTypeOutput -} - -func (n *GraphNodeConfigOutput) OutputName() string { - return n.Output.Name -} - -func (n *GraphNodeConfigOutput) DependableName() []string { - return []string{n.Name()} -} - -func (n *GraphNodeConfigOutput) DependentOn() []string { - vars := n.Output.RawConfig.Variables - result := make([]string, 0, len(vars)) - for _, v := range vars { - if vn := varNameForVar(v); vn != "" { - result = append(result, vn) - } - } - - return result -} - -// GraphNodeEvalable impl. -func (n *GraphNodeConfigOutput) EvalTree() EvalNode { - return &EvalOpFilter{ - Ops: []walkOperation{walkRefresh, walkPlan, walkApply, - walkDestroy, walkInput, walkValidate}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalWriteOutput{ - Name: n.Output.Name, - Sensitive: n.Output.Sensitive, - Value: n.Output.RawConfig, - }, - }, - }, - } -} - -// GraphNodeProxy impl. -func (n *GraphNodeConfigOutput) Proxy() bool { - return true -} - -// GraphNodeDestroyEdgeInclude impl. -func (n *GraphNodeConfigOutput) DestroyEdgeInclude(dag.Vertex) bool { - return false -} - -// GraphNodeFlattenable impl. -func (n *GraphNodeConfigOutput) Flatten(p []string) (dag.Vertex, error) { - return &GraphNodeConfigOutputFlat{ - GraphNodeConfigOutput: n, - PathValue: p, - }, nil -} - -// Same as GraphNodeConfigOutput, but for flattening -type GraphNodeConfigOutputFlat struct { - *GraphNodeConfigOutput - - PathValue []string -} - -func (n *GraphNodeConfigOutputFlat) Name() string { - return fmt.Sprintf( - "%s.%s", modulePrefixStr(n.PathValue), n.GraphNodeConfigOutput.Name()) -} - -func (n *GraphNodeConfigOutputFlat) Path() []string { - return n.PathValue -} - -func (n *GraphNodeConfigOutputFlat) DependableName() []string { - return modulePrefixList( - n.GraphNodeConfigOutput.DependableName(), - modulePrefixStr(n.PathValue)) -} - -func (n *GraphNodeConfigOutputFlat) DependentOn() []string { - prefix := modulePrefixStr(n.PathValue) - return modulePrefixList( - n.GraphNodeConfigOutput.DependentOn(), - prefix) -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_provider.go b/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_provider.go deleted file mode 100644 index 59fbfcb..0000000 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_provider.go +++ /dev/null @@ -1,133 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/dag" -) - -// GraphNodeConfigProvider represents a configured provider within the -// configuration graph. These are only immediately in the graph when an -// explicit `provider` configuration block is in the configuration. -type GraphNodeConfigProvider struct { - Provider *config.ProviderConfig -} - -func (n *GraphNodeConfigProvider) Name() string { - return fmt.Sprintf("provider.%s", n.ProviderName()) -} - -func (n *GraphNodeConfigProvider) ConfigType() GraphNodeConfigType { - return GraphNodeConfigTypeProvider -} - -func (n *GraphNodeConfigProvider) DependableName() []string { - return []string{n.Name()} -} - -func (n *GraphNodeConfigProvider) DependentOn() []string { - vars := n.Provider.RawConfig.Variables - result := make([]string, 0, len(vars)) - for _, v := range vars { - if vn := varNameForVar(v); vn != "" { - result = append(result, vn) - } - } - - return result -} - -// GraphNodeEvalable impl. -func (n *GraphNodeConfigProvider) EvalTree() EvalNode { - return ProviderEvalTree(n.ProviderName(), n.Provider.RawConfig) -} - -// GraphNodeProvider implementation -func (n *GraphNodeConfigProvider) ProviderName() string { - if n.Provider.Alias == "" { - return n.Provider.Name - } else { - return fmt.Sprintf("%s.%s", n.Provider.Name, n.Provider.Alias) - } -} - -// GraphNodeProvider implementation -func (n *GraphNodeConfigProvider) ProviderConfig() *config.RawConfig { - return n.Provider.RawConfig -} - -// GraphNodeDotter impl. -func (n *GraphNodeConfigProvider) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": n.Name(), - "shape": "diamond", - }, - } -} - -// GraphNodeDotterOrigin impl. -func (n *GraphNodeConfigProvider) DotOrigin() bool { - return true -} - -// GraphNodeFlattenable impl. -func (n *GraphNodeConfigProvider) Flatten(p []string) (dag.Vertex, error) { - return &GraphNodeConfigProviderFlat{ - GraphNodeConfigProvider: n, - PathValue: p, - }, nil -} - -// Same as GraphNodeConfigProvider, but for flattening -type GraphNodeConfigProviderFlat struct { - *GraphNodeConfigProvider - - PathValue []string -} - -func (n *GraphNodeConfigProviderFlat) Name() string { - return fmt.Sprintf( - "%s.%s", modulePrefixStr(n.PathValue), n.GraphNodeConfigProvider.Name()) -} - -func (n *GraphNodeConfigProviderFlat) Path() []string { - return n.PathValue -} - -func (n *GraphNodeConfigProviderFlat) DependableName() []string { - return modulePrefixList( - n.GraphNodeConfigProvider.DependableName(), - modulePrefixStr(n.PathValue)) -} - -func (n *GraphNodeConfigProviderFlat) DependentOn() []string { - prefixed := modulePrefixList( - n.GraphNodeConfigProvider.DependentOn(), - modulePrefixStr(n.PathValue)) - - result := make([]string, len(prefixed), len(prefixed)+1) - copy(result, prefixed) - - // If we're in a module, then depend on our parent's provider - if len(n.PathValue) > 1 { - prefix := modulePrefixStr(n.PathValue[:len(n.PathValue)-1]) - if prefix != "" { - prefix += "." - } - - result = append(result, fmt.Sprintf( - "%s%s", - prefix, n.GraphNodeConfigProvider.Name())) - } - - return result -} - -func (n *GraphNodeConfigProviderFlat) ProviderName() string { - return fmt.Sprintf( - "%s.%s", modulePrefixStr(n.PathValue), - n.GraphNodeConfigProvider.ProviderName()) -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_resource.go b/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_resource.go deleted file mode 100644 index cecedb6..0000000 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_resource.go +++ /dev/null @@ -1,539 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - "strings" - - "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/dag" -) - -// GraphNodeCountDependent is implemented by resources for giving only -// the dependencies they have from the "count" field. -type GraphNodeCountDependent interface { - CountDependentOn() []string -} - -// GraphNodeConfigResource represents a resource within the config graph. -type GraphNodeConfigResource struct { - Resource *config.Resource - - // If set to true, this resource represents a resource - // that will be destroyed in some way. - Destroy bool - - // Used during DynamicExpand to target indexes - Targets []ResourceAddress - - Path []string -} - -func (n *GraphNodeConfigResource) Copy() *GraphNodeConfigResource { - ncr := &GraphNodeConfigResource{ - Resource: n.Resource.Copy(), - Destroy: n.Destroy, - Targets: make([]ResourceAddress, 0, len(n.Targets)), - Path: make([]string, 0, len(n.Path)), - } - for _, t := range n.Targets { - ncr.Targets = append(ncr.Targets, *t.Copy()) - } - for _, p := range n.Path { - ncr.Path = append(ncr.Path, p) - } - return ncr -} - -func (n *GraphNodeConfigResource) ConfigType() GraphNodeConfigType { - return GraphNodeConfigTypeResource -} - -func (n *GraphNodeConfigResource) DependableName() []string { - return []string{n.Resource.Id()} -} - -// GraphNodeCountDependent impl. -func (n *GraphNodeConfigResource) CountDependentOn() []string { - result := make([]string, 0, len(n.Resource.RawCount.Variables)) - for _, v := range n.Resource.RawCount.Variables { - if vn := varNameForVar(v); vn != "" { - result = append(result, vn) - } - } - - return result -} - -// GraphNodeDependent impl. -func (n *GraphNodeConfigResource) DependentOn() []string { - result := make([]string, len(n.Resource.DependsOn), - (len(n.Resource.RawCount.Variables)+ - len(n.Resource.RawConfig.Variables)+ - len(n.Resource.DependsOn))*2) - copy(result, n.Resource.DependsOn) - - for _, v := range n.Resource.RawCount.Variables { - if vn := varNameForVar(v); vn != "" { - result = append(result, vn) - } - } - for _, v := range n.Resource.RawConfig.Variables { - if vn := varNameForVar(v); vn != "" { - result = append(result, vn) - } - } - for _, p := range n.Resource.Provisioners { - for _, v := range p.ConnInfo.Variables { - if vn := varNameForVar(v); vn != "" && vn != n.Resource.Id() { - result = append(result, vn) - } - } - for _, v := range p.RawConfig.Variables { - if vn := varNameForVar(v); vn != "" && vn != n.Resource.Id() { - result = append(result, vn) - } - } - } - - return result -} - -// VarWalk calls a callback for all the variables that this resource -// depends on. -func (n *GraphNodeConfigResource) VarWalk(fn func(config.InterpolatedVariable)) { - for _, v := range n.Resource.RawCount.Variables { - fn(v) - } - for _, v := range n.Resource.RawConfig.Variables { - fn(v) - } - for _, p := range n.Resource.Provisioners { - for _, v := range p.ConnInfo.Variables { - fn(v) - } - for _, v := range p.RawConfig.Variables { - fn(v) - } - } -} - -func (n *GraphNodeConfigResource) Name() string { - result := n.Resource.Id() - if n.Destroy { - result += " (destroy)" - } - return result -} - -// GraphNodeDotter impl. -func (n *GraphNodeConfigResource) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - if n.Destroy && !opts.Verbose { - return nil - } - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": n.Name(), - "shape": "box", - }, - } -} - -// GraphNodeFlattenable impl. -func (n *GraphNodeConfigResource) Flatten(p []string) (dag.Vertex, error) { - return &GraphNodeConfigResourceFlat{ - GraphNodeConfigResource: n, - PathValue: p, - }, nil -} - -// GraphNodeDynamicExpandable impl. -func (n *GraphNodeConfigResource) DynamicExpand(ctx EvalContext) (*Graph, error) { - state, lock := ctx.State() - lock.RLock() - defer lock.RUnlock() - - // Start creating the steps - steps := make([]GraphTransformer, 0, 5) - - // Expand counts. - steps = append(steps, &ResourceCountTransformerOld{ - Resource: n.Resource, - Destroy: n.Destroy, - Targets: n.Targets, - }) - - // Additional destroy modifications. - if n.Destroy { - // If we're destroying a primary or tainted resource, we want to - // expand orphans, which have all the same semantics in a destroy - // as a primary or tainted resource. - steps = append(steps, &OrphanTransformer{ - Resource: n.Resource, - State: state, - View: n.Resource.Id(), - }) - - steps = append(steps, &DeposedTransformer{ - State: state, - View: n.Resource.Id(), - }) - } - - // We always want to apply targeting - steps = append(steps, &TargetsTransformer{ - ParsedTargets: n.Targets, - Destroy: n.Destroy, - }) - - // Always end with the root being added - steps = append(steps, &RootTransformer{}) - - // Build the graph - b := &BasicGraphBuilder{ - Steps: steps, - Validate: true, - Name: "GraphNodeConfigResource", - } - return b.Build(ctx.Path()) -} - -// GraphNodeAddressable impl. -func (n *GraphNodeConfigResource) ResourceAddress() *ResourceAddress { - return &ResourceAddress{ - Path: n.Path[1:], - Index: -1, - InstanceType: TypePrimary, - Name: n.Resource.Name, - Type: n.Resource.Type, - Mode: n.Resource.Mode, - } -} - -// GraphNodeTargetable impl. -func (n *GraphNodeConfigResource) SetTargets(targets []ResourceAddress) { - n.Targets = targets -} - -// GraphNodeEvalable impl. -func (n *GraphNodeConfigResource) EvalTree() EvalNode { - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalInterpolate{Config: n.Resource.RawCount}, - &EvalCountCheckComputed{Resource: n.Resource}, - &EvalOpFilter{ - Ops: []walkOperation{walkValidate}, - Node: &EvalValidateCount{Resource: n.Resource}, - }, - &EvalCountFixZeroOneBoundary{Resource: n.Resource}, - }, - } -} - -// GraphNodeProviderConsumer -func (n *GraphNodeConfigResource) ProvidedBy() []string { - return []string{resourceProvider(n.Resource.Type, n.Resource.Provider)} -} - -// GraphNodeProvisionerConsumer -func (n *GraphNodeConfigResource) ProvisionedBy() []string { - result := make([]string, len(n.Resource.Provisioners)) - for i, p := range n.Resource.Provisioners { - result[i] = p.Type - } - - return result -} - -// GraphNodeDestroyable -func (n *GraphNodeConfigResource) DestroyNode() GraphNodeDestroy { - // If we're already a destroy node, then don't do anything - if n.Destroy { - return nil - } - - result := &graphNodeResourceDestroy{ - GraphNodeConfigResource: *n.Copy(), - Original: n, - } - result.Destroy = true - - return result -} - -// GraphNodeNoopPrunable -func (n *GraphNodeConfigResource) Noop(opts *NoopOpts) bool { - log.Printf("[DEBUG] Checking resource noop: %s", n.Name()) - // We don't have any noop optimizations for destroy nodes yet - if n.Destroy { - log.Printf("[DEBUG] Destroy node, not a noop") - return false - } - - // If there is no diff, then we aren't a noop since something needs to - // be done (such as a plan). We only check if we're a noop in a diff. - if opts.Diff == nil || opts.Diff.Empty() { - log.Printf("[DEBUG] No diff, not a noop") - return false - } - - // If the count has any interpolations, we can't prune this node since - // we need to be sure to evaluate the count so that splat variables work - // later (which need to know the full count). - if len(n.Resource.RawCount.Interpolations) > 0 { - log.Printf("[DEBUG] Count has interpolations, not a noop") - return false - } - - // If we have no module diff, we're certainly a noop. This is because - // it means there is a diff, and that the module we're in just isn't - // in it, meaning we're not doing anything. - if opts.ModDiff == nil || opts.ModDiff.Empty() { - log.Printf("[DEBUG] No mod diff, treating resource as a noop") - return true - } - - // Grab the ID which is the prefix (in the case count > 0 at some point) - prefix := n.Resource.Id() - - // Go through the diff and if there are any with our name on it, keep us - found := false - for k, _ := range opts.ModDiff.Resources { - if strings.HasPrefix(k, prefix) { - log.Printf("[DEBUG] Diff has %s, resource is not a noop", k) - found = true - break - } - } - - log.Printf("[DEBUG] Final noop value: %t", !found) - return !found -} - -// Same as GraphNodeConfigResource, but for flattening -type GraphNodeConfigResourceFlat struct { - *GraphNodeConfigResource - - PathValue []string -} - -func (n *GraphNodeConfigResourceFlat) Name() string { - return fmt.Sprintf( - "%s.%s", modulePrefixStr(n.PathValue), n.GraphNodeConfigResource.Name()) -} - -func (n *GraphNodeConfigResourceFlat) Path() []string { - return n.PathValue -} - -func (n *GraphNodeConfigResourceFlat) DependableName() []string { - return modulePrefixList( - n.GraphNodeConfigResource.DependableName(), - modulePrefixStr(n.PathValue)) -} - -func (n *GraphNodeConfigResourceFlat) DependentOn() []string { - prefix := modulePrefixStr(n.PathValue) - return modulePrefixList( - n.GraphNodeConfigResource.DependentOn(), - prefix) -} - -func (n *GraphNodeConfigResourceFlat) ProvidedBy() []string { - prefix := modulePrefixStr(n.PathValue) - return modulePrefixList( - n.GraphNodeConfigResource.ProvidedBy(), - prefix) -} - -func (n *GraphNodeConfigResourceFlat) ProvisionedBy() []string { - prefix := modulePrefixStr(n.PathValue) - return modulePrefixList( - n.GraphNodeConfigResource.ProvisionedBy(), - prefix) -} - -// GraphNodeDestroyable impl. -func (n *GraphNodeConfigResourceFlat) DestroyNode() GraphNodeDestroy { - // Get our parent destroy node. If we don't have any, just return - raw := n.GraphNodeConfigResource.DestroyNode() - if raw == nil { - return nil - } - - node, ok := raw.(*graphNodeResourceDestroy) - if !ok { - panic(fmt.Sprintf("unknown destroy node: %s %T", dag.VertexName(raw), raw)) - } - - // Otherwise, wrap it so that it gets the proper module treatment. - return &graphNodeResourceDestroyFlat{ - graphNodeResourceDestroy: node, - PathValue: n.PathValue, - FlatCreateNode: n, - } -} - -type graphNodeResourceDestroyFlat struct { - *graphNodeResourceDestroy - - PathValue []string - - // Needs to be able to properly yield back a flattened create node to prevent - FlatCreateNode *GraphNodeConfigResourceFlat -} - -func (n *graphNodeResourceDestroyFlat) Name() string { - return fmt.Sprintf( - "%s.%s", modulePrefixStr(n.PathValue), n.graphNodeResourceDestroy.Name()) -} - -func (n *graphNodeResourceDestroyFlat) Path() []string { - return n.PathValue -} - -func (n *graphNodeResourceDestroyFlat) CreateNode() dag.Vertex { - return n.FlatCreateNode -} - -func (n *graphNodeResourceDestroyFlat) ProvidedBy() []string { - prefix := modulePrefixStr(n.PathValue) - return modulePrefixList( - n.GraphNodeConfigResource.ProvidedBy(), - prefix) -} - -// graphNodeResourceDestroy represents the logical destruction of a -// resource. This node doesn't mean it will be destroyed for sure, but -// instead that if a destroy were to happen, it must happen at this point. -type graphNodeResourceDestroy struct { - GraphNodeConfigResource - Original *GraphNodeConfigResource -} - -func (n *graphNodeResourceDestroy) CreateBeforeDestroy() bool { - // CBD is enabled if the resource enables it - return n.Original.Resource.Lifecycle.CreateBeforeDestroy && n.Destroy -} - -func (n *graphNodeResourceDestroy) CreateNode() dag.Vertex { - return n.Original -} - -func (n *graphNodeResourceDestroy) DestroyInclude(d *ModuleDiff, s *ModuleState) bool { - if n.Destroy { - return n.destroyInclude(d, s) - } - - return true -} - -func (n *graphNodeResourceDestroy) destroyInclude( - d *ModuleDiff, s *ModuleState) bool { - // Get the count, and specifically the raw value of the count - // (with interpolations and all). If the count is NOT a static "1", - // then we keep the destroy node no matter what. - // - // The reasoning for this is complicated and not intuitively obvious, - // but I attempt to explain it below. - // - // The destroy transform works by generating the worst case graph, - // with worst case being the case that every resource already exists - // and needs to be destroy/created (force-new). There is a single important - // edge case where this actually results in a real-life cycle: if a - // create-before-destroy (CBD) resource depends on a non-CBD resource. - // Imagine a EC2 instance "foo" with CBD depending on a security - // group "bar" without CBD, and conceptualize the worst case destroy - // order: - // - // 1.) SG must be destroyed (non-CBD) - // 2.) SG must be created/updated - // 3.) EC2 instance must be created (CBD, requires the SG be made) - // 4.) EC2 instance must be destroyed (requires SG be destroyed) - // - // Except, #1 depends on #4, since the SG can't be destroyed while - // an EC2 instance is using it (AWS API requirements). As you can see, - // this is a real life cycle that can't be automatically reconciled - // except under two conditions: - // - // 1.) SG is also CBD. This doesn't work 100% of the time though - // since the non-CBD resource might not support CBD. To make matters - // worse, the entire transitive closure of dependencies must be - // CBD (if the SG depends on a VPC, you have the same problem). - // 2.) EC2 must not CBD. This can't happen automatically because CBD - // is used as a way to ensure zero (or minimal) downtime Terraform - // applies, and it isn't acceptable for TF to ignore this request, - // since it can result in unexpected downtime. - // - // Therefore, we compromise with this edge case here: if there is - // a static count of "1", we prune the diff to remove cycles during a - // graph optimization path if we don't see the resource in the diff. - // If the count is set to ANYTHING other than a static "1" (variable, - // computed attribute, static number greater than 1), then we keep the - // destroy, since it is required for dynamic graph expansion to find - // orphan count objects. - // - // This isn't ideal logic, but its strictly better without introducing - // new impossibilities. It breaks the cycle in practical cases, and the - // cycle comes back in no cases we've found to be practical, but just - // as the cycle would already exist without this anyways. - count := n.Original.Resource.RawCount - if raw := count.Raw[count.Key]; raw != "1" { - return true - } - - // Okay, we're dealing with a static count. There are a few ways - // to include this resource. - prefix := n.Original.Resource.Id() - - // If we're present in the diff proper, then keep it. We're looking - // only for resources in the diff that match our resource or a count-index - // of our resource that are marked for destroy. - if d != nil { - for k, v := range d.Resources { - match := k == prefix || strings.HasPrefix(k, prefix+".") - if match && v.GetDestroy() { - return true - } - } - } - - // If we're in the state as a primary in any form, then keep it. - // This does a prefix check so it will also catch orphans on count - // decreases to "1". - if s != nil { - for k, v := range s.Resources { - // Ignore exact matches - if k == prefix { - continue - } - - // Ignore anything that doesn't have a "." afterwards so that - // we only get our own resource and any counts on it. - if !strings.HasPrefix(k, prefix+".") { - continue - } - - // Ignore exact matches and the 0'th index. We only care - // about if there is a decrease in count. - if k == prefix+".0" { - continue - } - - if v.Primary != nil { - return true - } - } - - // If we're in the state as _both_ "foo" and "foo.0", then - // keep it, since we treat the latter as an orphan. - _, okOne := s.Resources[prefix] - _, okTwo := s.Resources[prefix+".0"] - if okOne && okTwo { - return true - } - } - - return false -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_type.go b/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_type.go deleted file mode 100644 index 42dd8dc..0000000 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_type.go +++ /dev/null @@ -1,16 +0,0 @@ -package terraform - -//go:generate stringer -type=GraphNodeConfigType graph_config_node_type.go - -// GraphNodeConfigType is an enum for the type of thing that a graph -// node represents from the configuration. -type GraphNodeConfigType int - -const ( - GraphNodeConfigTypeInvalid GraphNodeConfigType = 0 - GraphNodeConfigTypeResource GraphNodeConfigType = iota - GraphNodeConfigTypeProvider - GraphNodeConfigTypeModule - GraphNodeConfigTypeOutput - GraphNodeConfigTypeVariable -) diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_variable.go b/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_variable.go deleted file mode 100644 index ba62eb0..0000000 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_config_node_variable.go +++ /dev/null @@ -1,274 +0,0 @@ -package terraform - -import ( - "fmt" - "log" - - "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/config/module" - "github.com/hashicorp/terraform/dag" -) - -// GraphNodeConfigVariable represents a Variable in the config. -type GraphNodeConfigVariable struct { - Variable *config.Variable - - // Value, if non-nil, will be used to set the value of the variable - // during evaluation. If this is nil, evaluation will do nothing. - // - // Module is the name of the module to set the variables on. - Module string - Value *config.RawConfig - - ModuleTree *module.Tree - ModulePath []string -} - -func (n *GraphNodeConfigVariable) Name() string { - return fmt.Sprintf("var.%s", n.Variable.Name) -} - -func (n *GraphNodeConfigVariable) ConfigType() GraphNodeConfigType { - return GraphNodeConfigTypeVariable -} - -func (n *GraphNodeConfigVariable) DependableName() []string { - return []string{n.Name()} -} - -// RemoveIfNotTargeted implements RemovableIfNotTargeted. -// When targeting is active, variables that are not targeted should be removed -// from the graph, because otherwise module variables trying to interpolate -// their references can fail when they're missing the referent resource node. -func (n *GraphNodeConfigVariable) RemoveIfNotTargeted() bool { - return true -} - -func (n *GraphNodeConfigVariable) DependentOn() []string { - // If we don't have any value set, we don't depend on anything - if n.Value == nil { - return nil - } - - // Get what we depend on based on our value - vars := n.Value.Variables - result := make([]string, 0, len(vars)) - for _, v := range vars { - if vn := varNameForVar(v); vn != "" { - result = append(result, vn) - } - } - - return result -} - -func (n *GraphNodeConfigVariable) VariableName() string { - return n.Variable.Name -} - -// GraphNodeDestroyEdgeInclude impl. -func (n *GraphNodeConfigVariable) DestroyEdgeInclude(v dag.Vertex) bool { - // Only include this variable in a destroy edge if the source vertex - // "v" has a count dependency on this variable. - log.Printf("[DEBUG] DestroyEdgeInclude: Checking: %s", dag.VertexName(v)) - cv, ok := v.(GraphNodeCountDependent) - if !ok { - log.Printf("[DEBUG] DestroyEdgeInclude: Not GraphNodeCountDependent: %s", dag.VertexName(v)) - return false - } - - for _, d := range cv.CountDependentOn() { - for _, d2 := range n.DependableName() { - log.Printf("[DEBUG] DestroyEdgeInclude: d = %s : d2 = %s", d, d2) - if d == d2 { - return true - } - } - } - - return false -} - -// GraphNodeNoopPrunable -func (n *GraphNodeConfigVariable) Noop(opts *NoopOpts) bool { - log.Printf("[DEBUG] Checking variable noop: %s", n.Name()) - // If we have no diff, always keep this in the graph. We have to do - // this primarily for validation: we want to validate that variable - // interpolations are valid even if there are no resources that - // depend on them. - if opts.Diff == nil || opts.Diff.Empty() { - log.Printf("[DEBUG] No diff, not a noop") - return false - } - - // We have to find our our module diff since we do funky things with - // the flat node's implementation of Path() below. - modDiff := opts.Diff.ModuleByPath(n.ModulePath) - - // If we're destroying, we have no need of variables unless they are depended - // on by the count of a resource. - if modDiff != nil && modDiff.Destroy { - if n.hasDestroyEdgeInPath(opts, nil) { - log.Printf("[DEBUG] Variable has destroy edge from %s, not a noop", - dag.VertexName(opts.Vertex)) - return false - } - log.Printf("[DEBUG] Variable has no included destroy edges: noop!") - return true - } - - for _, v := range opts.Graph.UpEdges(opts.Vertex).List() { - // This is terrible, but I can't think of a better way to do this. - if dag.VertexName(v) == rootNodeName { - continue - } - - log.Printf("[DEBUG] Found up edge to %s, var is not noop", dag.VertexName(v)) - return false - } - - log.Printf("[DEBUG] No up edges, treating variable as a noop") - return true -} - -// hasDestroyEdgeInPath recursively walks for a destroy edge, ensuring that -// a variable both has no immediate destroy edges or any in its full module -// path, ensuring that links do not get severed in the middle. -func (n *GraphNodeConfigVariable) hasDestroyEdgeInPath(opts *NoopOpts, vertex dag.Vertex) bool { - if vertex == nil { - vertex = opts.Vertex - } - - log.Printf("[DEBUG] hasDestroyEdgeInPath: Looking for destroy edge: %s - %T", dag.VertexName(vertex), vertex) - for _, v := range opts.Graph.UpEdges(vertex).List() { - if len(opts.Graph.UpEdges(v).List()) > 1 { - if n.hasDestroyEdgeInPath(opts, v) == true { - return true - } - } - - // Here we borrow the implementation of DestroyEdgeInclude, whose logic - // and semantics are exactly what we want here. We add a check for the - // the root node, since we have to always depend on its existance. - if cv, ok := vertex.(*GraphNodeConfigVariableFlat); ok { - if dag.VertexName(v) == rootNodeName || cv.DestroyEdgeInclude(v) { - return true - } - } - } - return false -} - -// GraphNodeProxy impl. -func (n *GraphNodeConfigVariable) Proxy() bool { - return true -} - -// GraphNodeEvalable impl. -func (n *GraphNodeConfigVariable) EvalTree() EvalNode { - // If we have no value, do nothing - if n.Value == nil { - return &EvalNoop{} - } - - // Otherwise, interpolate the value of this variable and set it - // within the variables mapping. - var config *ResourceConfig - variables := make(map[string]interface{}) - return &EvalSequence{ - Nodes: []EvalNode{ - &EvalInterpolate{ - Config: n.Value, - Output: &config, - }, - - &EvalVariableBlock{ - Config: &config, - VariableValues: variables, - }, - - &EvalCoerceMapVariable{ - Variables: variables, - ModulePath: n.ModulePath, - ModuleTree: n.ModuleTree, - }, - - &EvalTypeCheckVariable{ - Variables: variables, - ModulePath: n.ModulePath, - ModuleTree: n.ModuleTree, - }, - - &EvalSetVariables{ - Module: &n.Module, - Variables: variables, - }, - }, - } -} - -// GraphNodeFlattenable impl. -func (n *GraphNodeConfigVariable) Flatten(p []string) (dag.Vertex, error) { - return &GraphNodeConfigVariableFlat{ - GraphNodeConfigVariable: n, - PathValue: p, - }, nil -} - -type GraphNodeConfigVariableFlat struct { - *GraphNodeConfigVariable - - PathValue []string -} - -func (n *GraphNodeConfigVariableFlat) Name() string { - return fmt.Sprintf( - "%s.%s", modulePrefixStr(n.PathValue), n.GraphNodeConfigVariable.Name()) -} - -func (n *GraphNodeConfigVariableFlat) DependableName() []string { - return []string{n.Name()} -} - -func (n *GraphNodeConfigVariableFlat) DependentOn() []string { - // We only wrap the dependencies and such if we have a path that is - // longer than 2 elements (root, child, more). This is because when - // flattened, variables can point outside the graph. - prefix := "" - if len(n.PathValue) > 2 { - prefix = modulePrefixStr(n.PathValue[:len(n.PathValue)-1]) - } - - return modulePrefixList( - n.GraphNodeConfigVariable.DependentOn(), - prefix) -} - -func (n *GraphNodeConfigVariableFlat) Path() []string { - if len(n.PathValue) > 2 { - return n.PathValue[:len(n.PathValue)-1] - } - - return nil -} - -func (n *GraphNodeConfigVariableFlat) Noop(opts *NoopOpts) bool { - // First look for provider nodes that depend on this variable downstream - modDiff := opts.Diff.ModuleByPath(n.ModulePath) - if modDiff != nil && modDiff.Destroy { - ds, err := opts.Graph.Descendents(n) - if err != nil { - log.Printf("[ERROR] Error looking up descendents of %s: %s", n.Name(), err) - } else { - for _, d := range ds.List() { - if _, ok := d.(GraphNodeProvider); ok { - log.Printf("[DEBUG] This variable is depended on by a provider, can't be a noop.") - return false - } - } - } - } - - // Then fall back to existing impl - return n.GraphNodeConfigVariable.Noop(opts) -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/graph_walk_context.go b/vendor/github.com/hashicorp/terraform/terraform/graph_walk_context.go index 459fcde..e63b460 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graph_walk_context.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graph_walk_context.go @@ -1,6 +1,7 @@ package terraform import ( + "context" "fmt" "log" "sync" @@ -15,8 +16,9 @@ type ContextGraphWalker struct { NullGraphWalker // Configurable values - Context *Context - Operation walkOperation + Context *Context + Operation walkOperation + StopContext context.Context // Outputs, do not set these. Do not read these while the graph // is being walked. @@ -65,6 +67,7 @@ func (w *ContextGraphWalker) EnterPath(path []string) EvalContext { w.interpolaterVarLock.Unlock() ctx := &BuiltinEvalContext{ + StopContext: w.StopContext, PathValue: path, Hooks: w.Context.hooks, InputValue: w.Context.uiInput, @@ -81,6 +84,7 @@ func (w *ContextGraphWalker) EnterPath(path []string) EvalContext { StateLock: &w.Context.stateLock, Interpolater: &Interpolater{ Operation: w.Operation, + Meta: w.Context.meta, Module: w.Context.module, State: w.Context.state, StateLock: &w.Context.stateLock, diff --git a/vendor/github.com/hashicorp/terraform/terraform/graphnodeconfigtype_string.go b/vendor/github.com/hashicorp/terraform/terraform/graphnodeconfigtype_string.go deleted file mode 100644 index 9ea0acb..0000000 --- a/vendor/github.com/hashicorp/terraform/terraform/graphnodeconfigtype_string.go +++ /dev/null @@ -1,16 +0,0 @@ -// Code generated by "stringer -type=GraphNodeConfigType graph_config_node_type.go"; DO NOT EDIT - -package terraform - -import "fmt" - -const _GraphNodeConfigType_name = "GraphNodeConfigTypeInvalidGraphNodeConfigTypeResourceGraphNodeConfigTypeProviderGraphNodeConfigTypeModuleGraphNodeConfigTypeOutputGraphNodeConfigTypeVariable" - -var _GraphNodeConfigType_index = [...]uint8{0, 26, 53, 80, 105, 130, 157} - -func (i GraphNodeConfigType) String() string { - if i < 0 || i >= GraphNodeConfigType(len(_GraphNodeConfigType_index)-1) { - return fmt.Sprintf("GraphNodeConfigType(%d)", i) - } - return _GraphNodeConfigType_name[_GraphNodeConfigType_index[i]:_GraphNodeConfigType_index[i+1]] -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/graphtype_string.go b/vendor/github.com/hashicorp/terraform/terraform/graphtype_string.go index 8e644ab..e97b485 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/graphtype_string.go +++ b/vendor/github.com/hashicorp/terraform/terraform/graphtype_string.go @@ -1,12 +1,12 @@ -// Code generated by "stringer -type=GraphType context_graph_type.go"; DO NOT EDIT +// Code generated by "stringer -type=GraphType context_graph_type.go"; DO NOT EDIT. package terraform import "fmt" -const _GraphType_name = "GraphTypeInvalidGraphTypeLegacyGraphTypePlanGraphTypePlanDestroyGraphTypeApply" +const _GraphType_name = "GraphTypeInvalidGraphTypeLegacyGraphTypeRefreshGraphTypePlanGraphTypePlanDestroyGraphTypeApplyGraphTypeInputGraphTypeValidate" -var _GraphType_index = [...]uint8{0, 16, 31, 44, 64, 78} +var _GraphType_index = [...]uint8{0, 16, 31, 47, 60, 80, 94, 108, 125} func (i GraphType) String() string { if i >= GraphType(len(_GraphType_index)-1) { diff --git a/vendor/github.com/hashicorp/terraform/terraform/hook.go b/vendor/github.com/hashicorp/terraform/terraform/hook.go index 81a6884..ab11e8e 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/hook.go +++ b/vendor/github.com/hashicorp/terraform/terraform/hook.go @@ -42,7 +42,7 @@ type Hook interface { PreProvisionResource(*InstanceInfo, *InstanceState) (HookAction, error) PostProvisionResource(*InstanceInfo, *InstanceState) (HookAction, error) PreProvision(*InstanceInfo, string) (HookAction, error) - PostProvision(*InstanceInfo, string) (HookAction, error) + PostProvision(*InstanceInfo, string, error) (HookAction, error) ProvisionOutput(*InstanceInfo, string, string) // PreRefresh and PostRefresh are called before and after a single @@ -92,7 +92,7 @@ func (*NilHook) PreProvision(*InstanceInfo, string) (HookAction, error) { return HookActionContinue, nil } -func (*NilHook) PostProvision(*InstanceInfo, string) (HookAction, error) { +func (*NilHook) PostProvision(*InstanceInfo, string, error) (HookAction, error) { return HookActionContinue, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/hook_mock.go b/vendor/github.com/hashicorp/terraform/terraform/hook_mock.go index b0bb94e..0e46400 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/hook_mock.go +++ b/vendor/github.com/hashicorp/terraform/terraform/hook_mock.go @@ -55,6 +55,7 @@ type MockHook struct { PostProvisionCalled bool PostProvisionInfo *InstanceInfo PostProvisionProvisionerId string + PostProvisionErrorArg error PostProvisionReturn HookAction PostProvisionError error @@ -170,13 +171,14 @@ func (h *MockHook) PreProvision(n *InstanceInfo, provId string) (HookAction, err return h.PreProvisionReturn, h.PreProvisionError } -func (h *MockHook) PostProvision(n *InstanceInfo, provId string) (HookAction, error) { +func (h *MockHook) PostProvision(n *InstanceInfo, provId string, err error) (HookAction, error) { h.Lock() defer h.Unlock() h.PostProvisionCalled = true h.PostProvisionInfo = n h.PostProvisionProvisionerId = provId + h.PostProvisionErrorArg = err return h.PostProvisionReturn, h.PostProvisionError } diff --git a/vendor/github.com/hashicorp/terraform/terraform/hook_stop.go b/vendor/github.com/hashicorp/terraform/terraform/hook_stop.go index 4c9bbb7..104d009 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/hook_stop.go +++ b/vendor/github.com/hashicorp/terraform/terraform/hook_stop.go @@ -38,7 +38,7 @@ func (h *stopHook) PreProvision(*InstanceInfo, string) (HookAction, error) { return h.hook() } -func (h *stopHook) PostProvision(*InstanceInfo, string) (HookAction, error) { +func (h *stopHook) PostProvision(*InstanceInfo, string, error) (HookAction, error) { return h.hook() } diff --git a/vendor/github.com/hashicorp/terraform/terraform/instancetype_string.go b/vendor/github.com/hashicorp/terraform/terraform/instancetype_string.go index f65414b..f69267c 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/instancetype_string.go +++ b/vendor/github.com/hashicorp/terraform/terraform/instancetype_string.go @@ -1,4 +1,4 @@ -// Code generated by "stringer -type=InstanceType instancetype.go"; DO NOT EDIT +// Code generated by "stringer -type=InstanceType instancetype.go"; DO NOT EDIT. package terraform diff --git a/vendor/github.com/hashicorp/terraform/terraform/interpolate.go b/vendor/github.com/hashicorp/terraform/terraform/interpolate.go index 4cbfab7..0c5acaa 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/interpolate.go +++ b/vendor/github.com/hashicorp/terraform/terraform/interpolate.go @@ -25,6 +25,7 @@ const ( // for interpolations such as `aws_instance.foo.bar`. type Interpolater struct { Operation walkOperation + Meta *ContextMeta Module *module.Tree State *State StateLock *sync.RWMutex @@ -87,6 +88,8 @@ func (i *Interpolater) Values( err = i.valueSelfVar(scope, n, v, result) case *config.SimpleVariable: err = i.valueSimpleVar(scope, n, v, result) + case *config.TerraformVariable: + err = i.valueTerraformVar(scope, n, v, result) case *config.UserVariable: err = i.valueUserVar(scope, n, v, result) default: @@ -259,7 +262,7 @@ func (i *Interpolater) valueResourceVar( // If it truly is missing, we'll catch it on a later walk. // This applies only to graph nodes that interpolate during the // config walk, e.g. providers. - if i.Operation == walkInput { + if i.Operation == walkInput || i.Operation == walkRefresh { result[n] = unknownVariable() return nil } @@ -309,6 +312,25 @@ func (i *Interpolater) valueSimpleVar( n) } +func (i *Interpolater) valueTerraformVar( + scope *InterpolationScope, + n string, + v *config.TerraformVariable, + result map[string]ast.Variable) error { + if v.Field != "env" { + return fmt.Errorf( + "%s: only supported key for 'terraform.X' interpolations is 'env'", n) + } + + if i.Meta == nil { + return fmt.Errorf( + "%s: internal error: nil Meta. Please report a bug.", n) + } + + result[n] = ast.Variable{Type: ast.TypeString, Value: i.Meta.Env} + return nil +} + func (i *Interpolater) valueUserVar( scope *InterpolationScope, n string, @@ -498,7 +520,7 @@ MISSING: // // For an input walk, computed values are okay to return because we're only // looking for missing variables to prompt the user for. - if i.Operation == walkRefresh || i.Operation == walkPlanDestroy || i.Operation == walkDestroy || i.Operation == walkInput { + if i.Operation == walkRefresh || i.Operation == walkPlanDestroy || i.Operation == walkInput { return &unknownVariable, nil } @@ -518,6 +540,13 @@ func (i *Interpolater) computeResourceMultiVariable( unknownVariable := unknownVariable() + // If we're only looking for input, we don't need to expand a + // multi-variable. This prevents us from encountering things that should be + // known but aren't because the state has yet to be refreshed. + if i.Operation == walkInput { + return &unknownVariable, nil + } + // Get the information about this resource variable, and verify // that it exists and such. module, cr, err := i.resourceVariableInfo(scope, v) @@ -698,6 +727,10 @@ func (i *Interpolater) resourceCountMax( // from the state. Plan and so on may not have any state yet so // we do a full interpolation. if i.Operation != walkApply { + if cr == nil { + return 0, nil + } + count, err := cr.Count() if err != nil { return 0, err diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_data_destroy.go b/vendor/github.com/hashicorp/terraform/terraform/node_data_destroy.go new file mode 100644 index 0000000..e32cea8 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/node_data_destroy.go @@ -0,0 +1,22 @@ +package terraform + +// NodeDestroyableDataResource represents a resource that is "plannable": +// it is ready to be planned in order to create a diff. +type NodeDestroyableDataResource struct { + *NodeAbstractResource +} + +// GraphNodeEvalable +func (n *NodeDestroyableDataResource) EvalTree() EvalNode { + addr := n.NodeAbstractResource.Addr + + // stateId is the ID to put into the state + stateId := addr.stateId() + + // Just destroy it. + var state *InstanceState + return &EvalWriteState{ + Name: stateId, + State: &state, // state is nil here + } +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_data_refresh.go b/vendor/github.com/hashicorp/terraform/terraform/node_data_refresh.go new file mode 100644 index 0000000..d504c89 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/node_data_refresh.go @@ -0,0 +1,198 @@ +package terraform + +import ( + "github.com/hashicorp/terraform/dag" +) + +// NodeRefreshableDataResource represents a resource that is "plannable": +// it is ready to be planned in order to create a diff. +type NodeRefreshableDataResource struct { + *NodeAbstractCountResource +} + +// GraphNodeDynamicExpandable +func (n *NodeRefreshableDataResource) DynamicExpand(ctx EvalContext) (*Graph, error) { + // Grab the state which we read + state, lock := ctx.State() + lock.RLock() + defer lock.RUnlock() + + // Expand the resource count which must be available by now from EvalTree + count, err := n.Config.Count() + if err != nil { + return nil, err + } + + // The concrete resource factory we'll use + concreteResource := func(a *NodeAbstractResource) dag.Vertex { + // Add the config and state since we don't do that via transforms + a.Config = n.Config + + return &NodeRefreshableDataResourceInstance{ + NodeAbstractResource: a, + } + } + + // Start creating the steps + steps := []GraphTransformer{ + // Expand the count. + &ResourceCountTransformer{ + Concrete: concreteResource, + Count: count, + Addr: n.ResourceAddr(), + }, + + // Attach the state + &AttachStateTransformer{State: state}, + + // Targeting + &TargetsTransformer{ParsedTargets: n.Targets}, + + // Connect references so ordering is correct + &ReferenceTransformer{}, + + // Make sure there is a single root + &RootTransformer{}, + } + + // Build the graph + b := &BasicGraphBuilder{ + Steps: steps, + Validate: true, + Name: "NodeRefreshableDataResource", + } + + return b.Build(ctx.Path()) +} + +// NodeRefreshableDataResourceInstance represents a _single_ resource instance +// that is refreshable. +type NodeRefreshableDataResourceInstance struct { + *NodeAbstractResource +} + +// GraphNodeEvalable +func (n *NodeRefreshableDataResourceInstance) EvalTree() EvalNode { + addr := n.NodeAbstractResource.Addr + + // stateId is the ID to put into the state + stateId := addr.stateId() + + // Build the instance info. More of this will be populated during eval + info := &InstanceInfo{ + Id: stateId, + Type: addr.Type, + } + + // Get the state if we have it, if not we build it + rs := n.ResourceState + if rs == nil { + rs = &ResourceState{} + } + + // If the config isn't empty we update the state + if n.Config != nil { + rs = &ResourceState{ + Type: n.Config.Type, + Provider: n.Config.Provider, + Dependencies: n.StateReferences(), + } + } + + // Build the resource for eval + resource := &Resource{ + Name: addr.Name, + Type: addr.Type, + CountIndex: addr.Index, + } + if resource.CountIndex < 0 { + resource.CountIndex = 0 + } + + // Declare a bunch of variables that are used for state during + // evaluation. Most of this are written to by-address below. + var config *ResourceConfig + var diff *InstanceDiff + var provider ResourceProvider + var state *InstanceState + + return &EvalSequence{ + Nodes: []EvalNode{ + // Always destroy the existing state first, since we must + // make sure that values from a previous read will not + // get interpolated if we end up needing to defer our + // loading until apply time. + &EvalWriteState{ + Name: stateId, + ResourceType: rs.Type, + Provider: rs.Provider, + Dependencies: rs.Dependencies, + State: &state, // state is nil here + }, + + &EvalInterpolate{ + Config: n.Config.RawConfig.Copy(), + Resource: resource, + Output: &config, + }, + + // The rest of this pass can proceed only if there are no + // computed values in our config. + // (If there are, we'll deal with this during the plan and + // apply phases.) + &EvalIf{ + If: func(ctx EvalContext) (bool, error) { + if config.ComputedKeys != nil && len(config.ComputedKeys) > 0 { + return true, EvalEarlyExitError{} + } + + // If the config explicitly has a depends_on for this + // data source, assume the intention is to prevent + // refreshing ahead of that dependency. + if len(n.Config.DependsOn) > 0 { + return true, EvalEarlyExitError{} + } + + return true, nil + }, + + Then: EvalNoop{}, + }, + + // The remainder of this pass is the same as running + // a "plan" pass immediately followed by an "apply" pass, + // populating the state early so it'll be available to + // provider configurations that need this data during + // refresh/plan. + &EvalGetProvider{ + Name: n.ProvidedBy()[0], + Output: &provider, + }, + + &EvalReadDataDiff{ + Info: info, + Config: &config, + Provider: &provider, + Output: &diff, + OutputState: &state, + }, + + &EvalReadDataApply{ + Info: info, + Diff: &diff, + Provider: &provider, + Output: &state, + }, + + &EvalWriteState{ + Name: stateId, + ResourceType: rs.Type, + Provider: rs.Provider, + Dependencies: rs.Dependencies, + State: &state, + }, + + &EvalUpdateStateHook{}, + }, + } +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_output.go b/vendor/github.com/hashicorp/terraform/terraform/node_output.go index 41962c2..e28e6f0 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_output.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_output.go @@ -28,6 +28,13 @@ func (n *NodeApplyableOutput) Path() []string { return n.PathValue } +// RemovableIfNotTargeted +func (n *NodeApplyableOutput) RemoveIfNotTargeted() bool { + // We need to add this so that this node will be removed if + // it isn't targeted or a dependency of a target. + return true +} + // GraphNodeReferenceable func (n *NodeApplyableOutput) ReferenceableName() []string { name := fmt.Sprintf("output.%s", n.Config.Name) diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_provider_abstract.go b/vendor/github.com/hashicorp/terraform/terraform/node_provider_abstract.go index f82c3f3..6cc8365 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_provider_abstract.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_provider_abstract.go @@ -38,6 +38,13 @@ func (n *NodeAbstractProvider) Path() []string { return n.PathValue } +// RemovableIfNotTargeted +func (n *NodeAbstractProvider) RemoveIfNotTargeted() bool { + // We need to add this so that this node will be removed if + // it isn't targeted or a dependency of a target. + return true +} + // GraphNodeReferencer func (n *NodeAbstractProvider) References() []string { if n.Config == nil { diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_provisioner.go b/vendor/github.com/hashicorp/terraform/terraform/node_provisioner.go new file mode 100644 index 0000000..bb117c1 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/node_provisioner.go @@ -0,0 +1,44 @@ +package terraform + +import ( + "fmt" + + "github.com/hashicorp/terraform/config" +) + +// NodeProvisioner represents a provider that has no associated operations. +// It registers all the common interfaces across operations for providers. +type NodeProvisioner struct { + NameValue string + PathValue []string + + // The fields below will be automatically set using the Attach + // interfaces if you're running those transforms, but also be explicitly + // set if you already have that information. + + Config *config.ProviderConfig +} + +func (n *NodeProvisioner) Name() string { + result := fmt.Sprintf("provisioner.%s", n.NameValue) + if len(n.PathValue) > 1 { + result = fmt.Sprintf("%s.%s", modulePrefixStr(n.PathValue), result) + } + + return result +} + +// GraphNodeSubPath +func (n *NodeProvisioner) Path() []string { + return n.PathValue +} + +// GraphNodeProvisioner +func (n *NodeProvisioner) ProvisionerName() string { + return n.NameValue +} + +// GraphNodeEvalable impl. +func (n *NodeProvisioner) EvalTree() EvalNode { + return &EvalInitProvisioner{Name: n.NameValue} +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_abstract.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_abstract.go index 22218e2..e4577e9 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_resource_abstract.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_abstract.go @@ -2,6 +2,7 @@ package terraform import ( "fmt" + "strings" "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/dag" @@ -52,7 +53,8 @@ func (n *NodeAbstractResource) ReferenceableName() []string { id = n.Config.Id() } else if n.Addr != nil { addrCopy := n.Addr.Copy() - addrCopy.Index = -1 + addrCopy.Path = nil // ReferenceTransformer handles paths + addrCopy.Index = -1 // We handle indexes below id = addrCopy.String() } else { // No way to determine our type.name, just return @@ -94,8 +96,10 @@ func (n *NodeAbstractResource) References() []string { result = append(result, ReferencesFromConfig(c.RawCount)...) result = append(result, ReferencesFromConfig(c.RawConfig)...) for _, p := range c.Provisioners { - result = append(result, ReferencesFromConfig(p.ConnInfo)...) - result = append(result, ReferencesFromConfig(p.RawConfig)...) + if p.When == config.ProvisionerWhenCreate { + result = append(result, ReferencesFromConfig(p.ConnInfo)...) + result = append(result, ReferencesFromConfig(p.RawConfig)...) + } } return result @@ -109,6 +113,63 @@ func (n *NodeAbstractResource) References() []string { return nil } +// StateReferences returns the dependencies to put into the state for +// this resource. +func (n *NodeAbstractResource) StateReferences() []string { + self := n.ReferenceableName() + + // Determine what our "prefix" is for checking for references to + // ourself. + addrCopy := n.Addr.Copy() + addrCopy.Index = -1 + selfPrefix := addrCopy.String() + "." + + depsRaw := n.References() + deps := make([]string, 0, len(depsRaw)) + for _, d := range depsRaw { + // Ignore any variable dependencies + if strings.HasPrefix(d, "var.") { + continue + } + + // If this has a backup ref, ignore those for now. The old state + // file never contained those and I'd rather store the rich types we + // add in the future. + if idx := strings.IndexRune(d, '/'); idx != -1 { + d = d[:idx] + } + + // If we're referencing ourself, then ignore it + found := false + for _, s := range self { + if d == s { + found = true + } + } + if found { + continue + } + + // If this is a reference to ourself and a specific index, we keep + // it. For example, if this resource is "foo.bar" and the reference + // is "foo.bar.0" then we keep it exact. Otherwise, we strip it. + if strings.HasSuffix(d, ".0") && !strings.HasPrefix(d, selfPrefix) { + d = d[:len(d)-2] + } + + // This is sad. The dependencies are currently in the format of + // "module.foo.bar" (the full field). This strips the field off. + if strings.HasPrefix(d, "module.") { + parts := strings.SplitN(d, ".", 3) + d = strings.Join(parts[0:2], ".") + } + + deps = append(deps, d) + } + + return deps +} + // GraphNodeProviderConsumer func (n *NodeAbstractResource) ProvidedBy() []string { // If we have a config we prefer that above all else diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_abstract_count.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_abstract_count.go new file mode 100644 index 0000000..573570d --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_abstract_count.go @@ -0,0 +1,50 @@ +package terraform + +// NodeAbstractCountResource should be embedded instead of NodeAbstractResource +// if the resource has a `count` value that needs to be expanded. +// +// The embedder should implement `DynamicExpand` to process the count. +type NodeAbstractCountResource struct { + *NodeAbstractResource + + // Validate, if true, will perform the validation for the count. + // This should only be turned on for the "validate" operation. + Validate bool +} + +// GraphNodeEvalable +func (n *NodeAbstractCountResource) EvalTree() EvalNode { + // We only check if the count is computed if we're not validating. + // If we're validating we allow computed counts since they just turn + // into more computed values. + var evalCountCheckComputed EvalNode + if !n.Validate { + evalCountCheckComputed = &EvalCountCheckComputed{Resource: n.Config} + } + + return &EvalSequence{ + Nodes: []EvalNode{ + // The EvalTree for a plannable resource primarily involves + // interpolating the count since it can contain variables + // we only just received access to. + // + // With the interpolated count, we can then DynamicExpand + // into the proper number of instances. + &EvalInterpolate{Config: n.Config.RawCount}, + + // Check if the count is computed + evalCountCheckComputed, + + // If validation is enabled, perform the validation + &EvalIf{ + If: func(ctx EvalContext) (bool, error) { + return n.Validate, nil + }, + + Then: &EvalValidateCount{Resource: n.Config}, + }, + + &EvalCountFixZeroOneBoundary{Resource: n.Config}, + }, + } +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_apply.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_apply.go index a166836..3599782 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_resource_apply.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_apply.go @@ -70,16 +70,8 @@ func (n *NodeApplyableResource) EvalTree() EvalNode { resource.CountIndex = 0 } - // Determine the dependencies for the state. We use some older - // code for this that we've used for a long time. - var stateDeps []string - { - oldN := &graphNodeExpandedResource{ - Resource: n.Config, - Index: addr.Index, - } - stateDeps = oldN.StateDependencies() - } + // Determine the dependencies for the state. + stateDeps := n.StateReferences() // Eval info is different depending on what kind of resource this is switch n.Config.Mode { @@ -298,6 +290,12 @@ func (n *NodeApplyableResource) evalTreeManagedResource( Name: stateId, Output: &state, }, + // Call pre-apply hook + &EvalApplyPre{ + Info: info, + State: &state, + Diff: &diffApply, + }, &EvalApply{ Info: info, State: &state, @@ -321,6 +319,7 @@ func (n *NodeApplyableResource) evalTreeManagedResource( InterpResource: resource, CreateNew: &createNew, Error: &err, + When: config.ProvisionerWhenCreate, }, &EvalIf{ If: func(ctx EvalContext) (bool, error) { diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_destroy.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_destroy.go index 6b4a48b..c2efd2c 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_resource_destroy.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_destroy.go @@ -46,9 +46,21 @@ func (n *NodeDestroyResource) ModifyCreateBeforeDestroy(v bool) error { // GraphNodeReferenceable, overriding NodeAbstractResource func (n *NodeDestroyResource) ReferenceableName() []string { + // We modify our referenceable name to have the suffix of ".destroy" + // since depending on the creation side doesn't necessarilly mean + // depending on destruction. + suffix := ".destroy" + + // If we're CBD, we also append "-cbd". This is because CBD will setup + // its own edges (in CBDEdgeTransformer). Depending on the "destroy" + // side generally doesn't mean depending on CBD as well. See GH-11349 + if n.CreateBeforeDestroy() { + suffix += "-cbd" + } + result := n.NodeAbstractResource.ReferenceableName() for i, v := range result { - result[i] = v + ".destroy" + result[i] = v + suffix } return result @@ -56,6 +68,21 @@ func (n *NodeDestroyResource) ReferenceableName() []string { // GraphNodeReferencer, overriding NodeAbstractResource func (n *NodeDestroyResource) References() []string { + // If we have a config, then we need to include destroy-time dependencies + if c := n.Config; c != nil { + var result []string + for _, p := range c.Provisioners { + // We include conn info and config for destroy time provisioners + // as dependencies that we have. + if p.When == config.ProvisionerWhenDestroy { + result = append(result, ReferencesFromConfig(p.ConnInfo)...) + result = append(result, ReferencesFromConfig(p.RawConfig)...) + } + } + + return result + } + return nil } @@ -107,6 +134,17 @@ func (n *NodeDestroyResource) EvalTree() EvalNode { uniqueExtra: "destroy", } + // Build the resource for eval + addr := n.Addr + resource := &Resource{ + Name: addr.Name, + Type: addr.Type, + CountIndex: addr.Index, + } + if resource.CountIndex < 0 { + resource.CountIndex = 0 + } + // Get our state rs := n.ResourceState if rs == nil { @@ -160,6 +198,48 @@ func (n *NodeDestroyResource) EvalTree() EvalNode { &EvalRequireState{ State: &state, }, + + // Call pre-apply hook + &EvalApplyPre{ + Info: info, + State: &state, + Diff: &diffApply, + }, + + // Run destroy provisioners if not tainted + &EvalIf{ + If: func(ctx EvalContext) (bool, error) { + if state != nil && state.Tainted { + return false, nil + } + + return true, nil + }, + + Then: &EvalApplyProvisioners{ + Info: info, + State: &state, + Resource: n.Config, + InterpResource: resource, + Error: &err, + When: config.ProvisionerWhenDestroy, + }, + }, + + // If we have a provisioning error, then we just call + // the post-apply hook now. + &EvalIf{ + If: func(ctx EvalContext) (bool, error) { + return err != nil, nil + }, + + Then: &EvalApplyPost{ + Info: info, + State: &state, + Error: &err, + }, + }, + // Make sure we handle data sources properly. &EvalIf{ If: func(ctx EvalContext) (bool, error) { diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan.go index c4694d4..52bbf88 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan.go @@ -7,34 +7,7 @@ import ( // NodePlannableResource represents a resource that is "plannable": // it is ready to be planned in order to create a diff. type NodePlannableResource struct { - *NodeAbstractResource - - // Set by GraphNodeTargetable and used during DynamicExpand to - // forward targets downwards. - targets []ResourceAddress -} - -// GraphNodeTargetable -func (n *NodePlannableResource) SetTargets(targets []ResourceAddress) { - n.targets = targets -} - -// GraphNodeEvalable -func (n *NodePlannableResource) EvalTree() EvalNode { - return &EvalSequence{ - Nodes: []EvalNode{ - // The EvalTree for a plannable resource primarily involves - // interpolating the count since it can contain variables - // we only just received access to. - // - // With the interpolated count, we can then DynamicExpand - // into the proper number of instances. - &EvalInterpolate{Config: n.Config.RawCount}, - - &EvalCountCheckComputed{Resource: n.Config}, - &EvalCountFixZeroOneBoundary{Resource: n.Config}, - }, - } + *NodeAbstractCountResource } // GraphNodeDynamicExpandable @@ -91,7 +64,7 @@ func (n *NodePlannableResource) DynamicExpand(ctx EvalContext) (*Graph, error) { &AttachStateTransformer{State: state}, // Targeting - &TargetsTransformer{ParsedTargets: n.targets}, + &TargetsTransformer{ParsedTargets: n.Targets}, // Connect references so ordering is correct &ReferenceTransformer{}, diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan_instance.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan_instance.go index 418d0f6..b529569 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan_instance.go +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_plan_instance.go @@ -37,13 +37,8 @@ func (n *NodePlannableResourceInstance) EvalTree() EvalNode { resource.CountIndex = 0 } - // Determine the dependencies for the state. We use some older - // code for this that we've used for a long time. - var stateDeps []string - { - oldN := &graphNodeExpandedResource{Resource: n.Config} - stateDeps = oldN.StateDependencies() - } + // Determine the dependencies for the state. + stateDeps := n.StateReferences() // Eval info is different depending on what kind of resource this is switch n.Config.Mode { diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_refresh.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_refresh.go new file mode 100644 index 0000000..3a44926 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_refresh.go @@ -0,0 +1,100 @@ +package terraform + +import ( + "fmt" + + "github.com/hashicorp/terraform/config" +) + +// NodeRefreshableResource represents a resource that is "applyable": +// it is ready to be applied and is represented by a diff. +type NodeRefreshableResource struct { + *NodeAbstractResource +} + +// GraphNodeDestroyer +func (n *NodeRefreshableResource) DestroyAddr() *ResourceAddress { + return n.Addr +} + +// GraphNodeEvalable +func (n *NodeRefreshableResource) EvalTree() EvalNode { + // Eval info is different depending on what kind of resource this is + switch mode := n.Addr.Mode; mode { + case config.ManagedResourceMode: + return n.evalTreeManagedResource() + + case config.DataResourceMode: + // Get the data source node. If we don't have a configuration + // then it is an orphan so we destroy it (remove it from the state). + var dn GraphNodeEvalable + if n.Config != nil { + dn = &NodeRefreshableDataResourceInstance{ + NodeAbstractResource: n.NodeAbstractResource, + } + } else { + dn = &NodeDestroyableDataResource{ + NodeAbstractResource: n.NodeAbstractResource, + } + } + + return dn.EvalTree() + default: + panic(fmt.Errorf("unsupported resource mode %s", mode)) + } +} + +func (n *NodeRefreshableResource) evalTreeManagedResource() EvalNode { + addr := n.NodeAbstractResource.Addr + + // stateId is the ID to put into the state + stateId := addr.stateId() + + // Build the instance info. More of this will be populated during eval + info := &InstanceInfo{ + Id: stateId, + Type: addr.Type, + } + + // Declare a bunch of variables that are used for state during + // evaluation. Most of this are written to by-address below. + var provider ResourceProvider + var state *InstanceState + + // This happened during initial development. All known cases were + // fixed and tested but as a sanity check let's assert here. + if n.ResourceState == nil { + err := fmt.Errorf( + "No resource state attached for addr: %s\n\n"+ + "This is a bug. Please report this to Terraform with your configuration\n"+ + "and state attached. Please be careful to scrub any sensitive information.", + addr) + return &EvalReturnError{Error: &err} + } + + return &EvalSequence{ + Nodes: []EvalNode{ + &EvalGetProvider{ + Name: n.ProvidedBy()[0], + Output: &provider, + }, + &EvalReadState{ + Name: stateId, + Output: &state, + }, + &EvalRefresh{ + Info: info, + Provider: &provider, + State: &state, + Output: &state, + }, + &EvalWriteState{ + Name: stateId, + ResourceType: n.ResourceState.Type, + Provider: n.ResourceState.Provider, + Dependencies: n.ResourceState.Dependencies, + State: &state, + }, + }, + } +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/node_resource_validate.go b/vendor/github.com/hashicorp/terraform/terraform/node_resource_validate.go new file mode 100644 index 0000000..f528f24 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/node_resource_validate.go @@ -0,0 +1,158 @@ +package terraform + +import ( + "github.com/hashicorp/terraform/dag" +) + +// NodeValidatableResource represents a resource that is used for validation +// only. +type NodeValidatableResource struct { + *NodeAbstractCountResource +} + +// GraphNodeEvalable +func (n *NodeValidatableResource) EvalTree() EvalNode { + // Ensure we're validating + c := n.NodeAbstractCountResource + c.Validate = true + return c.EvalTree() +} + +// GraphNodeDynamicExpandable +func (n *NodeValidatableResource) DynamicExpand(ctx EvalContext) (*Graph, error) { + // Grab the state which we read + state, lock := ctx.State() + lock.RLock() + defer lock.RUnlock() + + // Expand the resource count which must be available by now from EvalTree + count := 1 + if n.Config.RawCount.Value() != unknownValue() { + var err error + count, err = n.Config.Count() + if err != nil { + return nil, err + } + } + + // The concrete resource factory we'll use + concreteResource := func(a *NodeAbstractResource) dag.Vertex { + // Add the config and state since we don't do that via transforms + a.Config = n.Config + + return &NodeValidatableResourceInstance{ + NodeAbstractResource: a, + } + } + + // Start creating the steps + steps := []GraphTransformer{ + // Expand the count. + &ResourceCountTransformer{ + Concrete: concreteResource, + Count: count, + Addr: n.ResourceAddr(), + }, + + // Attach the state + &AttachStateTransformer{State: state}, + + // Targeting + &TargetsTransformer{ParsedTargets: n.Targets}, + + // Connect references so ordering is correct + &ReferenceTransformer{}, + + // Make sure there is a single root + &RootTransformer{}, + } + + // Build the graph + b := &BasicGraphBuilder{ + Steps: steps, + Validate: true, + Name: "NodeValidatableResource", + } + + return b.Build(ctx.Path()) +} + +// This represents a _single_ resource instance to validate. +type NodeValidatableResourceInstance struct { + *NodeAbstractResource +} + +// GraphNodeEvalable +func (n *NodeValidatableResourceInstance) EvalTree() EvalNode { + addr := n.NodeAbstractResource.Addr + + // Build the resource for eval + resource := &Resource{ + Name: addr.Name, + Type: addr.Type, + CountIndex: addr.Index, + } + if resource.CountIndex < 0 { + resource.CountIndex = 0 + } + + // Declare a bunch of variables that are used for state during + // evaluation. Most of this are written to by-address below. + var config *ResourceConfig + var provider ResourceProvider + + seq := &EvalSequence{ + Nodes: []EvalNode{ + &EvalValidateResourceSelfRef{ + Addr: &addr, + Config: &n.Config.RawConfig, + }, + &EvalGetProvider{ + Name: n.ProvidedBy()[0], + Output: &provider, + }, + &EvalInterpolate{ + Config: n.Config.RawConfig.Copy(), + Resource: resource, + Output: &config, + }, + &EvalValidateResource{ + Provider: &provider, + Config: &config, + ResourceName: n.Config.Name, + ResourceType: n.Config.Type, + ResourceMode: n.Config.Mode, + }, + }, + } + + // Validate all the provisioners + for _, p := range n.Config.Provisioners { + var provisioner ResourceProvisioner + var connConfig *ResourceConfig + seq.Nodes = append( + seq.Nodes, + &EvalGetProvisioner{ + Name: p.Type, + Output: &provisioner, + }, + &EvalInterpolate{ + Config: p.RawConfig.Copy(), + Resource: resource, + Output: &config, + }, + &EvalInterpolate{ + Config: p.ConnInfo.Copy(), + Resource: resource, + Output: &connConfig, + }, + &EvalValidateProvisioner{ + Provisioner: &provisioner, + Config: &config, + ConnConfig: &connConfig, + }, + ) + } + + return seq +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/plan.go b/vendor/github.com/hashicorp/terraform/terraform/plan.go index 75023a0..ea08845 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/plan.go +++ b/vendor/github.com/hashicorp/terraform/terraform/plan.go @@ -20,6 +20,10 @@ func init() { // Plan represents a single Terraform execution plan, which contains // all the information necessary to make an infrastructure change. +// +// A plan has to contain basically the entire state of the world +// necessary to make a change: the state, diff, config, backend config, etc. +// This is so that it can run alone without any other data. type Plan struct { Diff *Diff Module *module.Tree @@ -27,6 +31,9 @@ type Plan struct { Vars map[string]interface{} Targets []string + // Backend is the backend that this plan should use and store data with. + Backend *BackendState + once sync.Once } diff --git a/vendor/github.com/hashicorp/terraform/terraform/resource_address.go b/vendor/github.com/hashicorp/terraform/terraform/resource_address.go index aa35dbb..a8a0c95 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/resource_address.go +++ b/vendor/github.com/hashicorp/terraform/terraform/resource_address.go @@ -285,14 +285,17 @@ func tokenizeResourceAddress(s string) (map[string]string, error) { // "1" (optional, omission implies: "0") `(?:\[(?P\d+)\])?` + `\z`) + groupNames := re.SubexpNames() rawMatches := re.FindAllStringSubmatch(s, -1) if len(rawMatches) != 1 { return nil, fmt.Errorf("Problem parsing address: %q", s) } + matches := make(map[string]string) for i, m := range rawMatches[0] { matches[groupNames[i]] = m } + return matches, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/resource_provisioner.go b/vendor/github.com/hashicorp/terraform/terraform/resource_provisioner.go index 3327e30..361ec1e 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/resource_provisioner.go +++ b/vendor/github.com/hashicorp/terraform/terraform/resource_provisioner.go @@ -21,6 +21,26 @@ type ResourceProvisioner interface { // is provided since provisioners only run after a resource has been // newly created. Apply(UIOutput, *InstanceState, *ResourceConfig) error + + // Stop is called when the provisioner should halt any in-flight actions. + // + // This can be used to make a nicer Ctrl-C experience for Terraform. + // Even if this isn't implemented to do anything (just returns nil), + // Terraform will still cleanly stop after the currently executing + // graph node is complete. However, this API can be used to make more + // efficient halts. + // + // Stop doesn't have to and shouldn't block waiting for in-flight actions + // to complete. It should take any action it wants and return immediately + // acknowledging it has received the stop request. Terraform core will + // automatically not make any further API calls to the provider soon + // after Stop is called (technically exactly once the currently executing + // graph nodes are complete). + // + // The error returned, if non-nil, is assumed to mean that signaling the + // stop somehow failed and that the user should expect potentially waiting + // a longer period of time. + Stop() error } // ResourceProvisionerCloser is an interface that provisioners that can close diff --git a/vendor/github.com/hashicorp/terraform/terraform/resource_provisioner_mock.go b/vendor/github.com/hashicorp/terraform/terraform/resource_provisioner_mock.go index be04e98..f471a51 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/resource_provisioner_mock.go +++ b/vendor/github.com/hashicorp/terraform/terraform/resource_provisioner_mock.go @@ -21,6 +21,10 @@ type MockResourceProvisioner struct { ValidateFn func(c *ResourceConfig) ([]string, []error) ValidateReturnWarns []string ValidateReturnErrors []error + + StopCalled bool + StopFn func() error + StopReturnError error } func (p *MockResourceProvisioner) Validate(c *ResourceConfig) ([]string, []error) { @@ -40,14 +44,29 @@ func (p *MockResourceProvisioner) Apply( state *InstanceState, c *ResourceConfig) error { p.Lock() - defer p.Unlock() p.ApplyCalled = true p.ApplyOutput = output p.ApplyState = state p.ApplyConfig = c if p.ApplyFn != nil { - return p.ApplyFn(state, c) + fn := p.ApplyFn + p.Unlock() + return fn(state, c) } + + defer p.Unlock() return p.ApplyReturnError } + +func (p *MockResourceProvisioner) Stop() error { + p.Lock() + defer p.Unlock() + + p.StopCalled = true + if p.StopFn != nil { + return p.StopFn() + } + + return p.StopReturnError +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/semantics.go b/vendor/github.com/hashicorp/terraform/terraform/semantics.go index 6d99875..20f1d8a 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/semantics.go +++ b/vendor/github.com/hashicorp/terraform/terraform/semantics.go @@ -49,25 +49,6 @@ type SemanticChecker interface { Check(*dag.Graph, dag.Vertex) error } -// SemanticCheckModulesExist is an implementation of SemanticChecker that -// verifies that all the modules that are referenced in the graph exist. -type SemanticCheckModulesExist struct{} - -// TODO: test -func (*SemanticCheckModulesExist) Check(g *dag.Graph, v dag.Vertex) error { - mn, ok := v.(*GraphNodeConfigModule) - if !ok { - return nil - } - - if mn.Tree == nil { - return fmt.Errorf( - "module '%s' not found", mn.Module.Name) - } - - return nil -} - // smcUserVariables does all the semantic checks to verify that the // variables given satisfy the configuration itself. func smcUserVariables(c *config.Config, vs map[string]interface{}) []error { diff --git a/vendor/github.com/hashicorp/terraform/terraform/shadow_context.go b/vendor/github.com/hashicorp/terraform/terraform/shadow_context.go index 5e0e316..5588af2 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/shadow_context.go +++ b/vendor/github.com/hashicorp/terraform/terraform/shadow_context.go @@ -46,6 +46,7 @@ func newShadowContext(c *Context) (*Context, *Context, Shadow) { destroy: c.destroy, diff: c.diff.DeepCopy(), hooks: nil, + meta: c.meta, module: c.module, state: c.state.DeepCopy(), targets: targetRaw.([]string), @@ -77,6 +78,7 @@ func newShadowContext(c *Context) (*Context, *Context, Shadow) { diff: c.diff, // diffLock - no copy hooks: c.hooks, + meta: c.meta, module: c.module, sh: c.sh, state: c.state, @@ -88,7 +90,8 @@ func newShadowContext(c *Context) (*Context, *Context, Shadow) { // l - no copy parallelSem: c.parallelSem, providerInputConfig: c.providerInputConfig, - runCh: c.runCh, + runContext: c.runContext, + runContextCancel: c.runContextCancel, shadowErr: c.shadowErr, } diff --git a/vendor/github.com/hashicorp/terraform/terraform/shadow_resource_provisioner.go b/vendor/github.com/hashicorp/terraform/terraform/shadow_resource_provisioner.go index 6e405c0..60a4908 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/shadow_resource_provisioner.go +++ b/vendor/github.com/hashicorp/terraform/terraform/shadow_resource_provisioner.go @@ -112,6 +112,10 @@ func (p *shadowResourceProvisionerReal) Apply( return err } +func (p *shadowResourceProvisionerReal) Stop() error { + return p.ResourceProvisioner.Stop() +} + // shadowResourceProvisionerShadow is the shadow resource provisioner. Function // calls never affect real resources. This is paired with the "real" side // which must be called properly to enable recording. @@ -228,6 +232,13 @@ func (p *shadowResourceProvisionerShadow) Apply( return result.ResultErr } +func (p *shadowResourceProvisionerShadow) Stop() error { + // For the shadow, we always just return nil since a Stop indicates + // that we were interrupted and shadows are disabled during interrupts + // anyways. + return nil +} + // The structs for the various function calls are put below. These structs // are used to carry call information across the real/shadow boundaries. diff --git a/vendor/github.com/hashicorp/terraform/terraform/state.go b/vendor/github.com/hashicorp/terraform/terraform/state.go index 472fac0..905ec3d 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/state.go +++ b/vendor/github.com/hashicorp/terraform/terraform/state.go @@ -4,11 +4,13 @@ import ( "bufio" "bytes" "encoding/json" + "errors" "fmt" "io" "io/ioutil" "log" "reflect" + "regexp" "sort" "strconv" "strings" @@ -78,6 +80,11 @@ type State struct { // pull and push state files from a remote storage endpoint. Remote *RemoteState `json:"remote,omitempty"` + // Backend tracks the configuration for the backend in use with + // this state. This is used to track any changes in the backend + // configuration. + Backend *BackendState `json:"backend,omitempty"` + // Modules contains all the modules in a breadth-first order Modules []*ModuleState `json:"modules"` @@ -578,7 +585,7 @@ func (s *State) CompareAges(other *State) (StateAgeComparison, error) { } // SameLineage returns true only if the state given in argument belongs -// to the same "lineage" of states as the reciever. +// to the same "lineage" of states as the receiver. func (s *State) SameLineage(other *State) bool { s.Lock() defer s.Unlock() @@ -778,6 +785,43 @@ func (s *State) String() string { return strings.TrimSpace(buf.String()) } +// BackendState stores the configuration to connect to a remote backend. +type BackendState struct { + Type string `json:"type"` // Backend type + Config map[string]interface{} `json:"config"` // Backend raw config + + // Hash is the hash code to uniquely identify the original source + // configuration. We use this to detect when there is a change in + // configuration even when "type" isn't changed. + Hash uint64 `json:"hash"` +} + +// Empty returns true if BackendState has no state. +func (s *BackendState) Empty() bool { + return s == nil || s.Type == "" +} + +// Rehash returns a unique content hash for this backend's configuration +// as a uint64 value. +// The Hash stored in the backend state needs to match the config itself, but +// we need to compare the backend config after it has been combined with all +// options. +// This function must match the implementation used by config.Backend. +func (s *BackendState) Rehash() uint64 { + if s == nil { + return 0 + } + + cfg := config.Backend{ + Type: s.Type, + RawConfig: &config.RawConfig{ + Raw: s.Config, + }, + } + + return cfg.Rehash() +} + // RemoteState is used to track the information about a remote // state store that we push/pull state to. type RemoteState struct { @@ -1141,7 +1185,8 @@ func (m *ModuleState) String() string { for name, _ := range m.Resources { names = append(names, name) } - sort.Strings(names) + + sort.Sort(resourceNameSort(names)) for _, k := range names { rs := m.Resources[k] @@ -1181,6 +1226,7 @@ func (m *ModuleState) String() string { attrKeys = append(attrKeys, ak) } + sort.Strings(attrKeys) for _, ak := range attrKeys { @@ -1211,6 +1257,7 @@ func (m *ModuleState) String() string { for k, _ := range m.Outputs { ks = append(ks, k) } + sort.Strings(ks) for _, k := range ks { @@ -1518,8 +1565,9 @@ type InstanceState struct { // Meta is a simple K/V map that is persisted to the State but otherwise // ignored by Terraform core. It's meant to be used for accounting by - // external client code. - Meta map[string]string `json:"meta"` + // external client code. The value here must only contain Go primitives + // and collections. + Meta map[string]interface{} `json:"meta"` // Tainted is used to mark a resource for recreation. Tainted bool `json:"tainted"` @@ -1538,7 +1586,7 @@ func (s *InstanceState) init() { s.Attributes = make(map[string]string) } if s.Meta == nil { - s.Meta = make(map[string]string) + s.Meta = make(map[string]interface{}) } s.Ephemeral.init() } @@ -1609,13 +1657,11 @@ func (s *InstanceState) Equal(other *InstanceState) bool { if len(s.Meta) != len(other.Meta) { return false } - for k, v := range s.Meta { - otherV, ok := other.Meta[k] - if !ok { - return false - } - - if v != otherV { + if s.Meta != nil && other.Meta != nil { + // We only do the deep check if both are non-nil. If one is nil + // we treat it as equal since their lengths are both zero (check + // above). + if !reflect.DeepEqual(s.Meta, other.Meta) { return false } } @@ -1664,6 +1710,32 @@ func (s *InstanceState) MergeDiff(d *InstanceDiff) *InstanceState { } } + // Remove any now empty array, maps or sets because a parent structure + // won't include these entries in the count value. + isCount := regexp.MustCompile(`\.[%#]$`).MatchString + var deleted []string + + for k, v := range result.Attributes { + if isCount(k) && v == "0" { + delete(result.Attributes, k) + deleted = append(deleted, k) + } + } + + for _, k := range deleted { + // Sanity check for invalid structures. + // If we removed the primary count key, there should have been no + // other keys left with this prefix. + + // this must have a "#" or "%" which we need to remove + base := k[:len(k)-1] + for k, _ := range result.Attributes { + if strings.HasPrefix(k, base) { + panic(fmt.Sprintf("empty structure %q has entry %q", base, k)) + } + } + } + return result } @@ -1752,10 +1824,18 @@ func testForV0State(buf *bufio.Reader) error { return nil } +// ErrNoState is returned by ReadState when the io.Reader contains no data +var ErrNoState = errors.New("no state") + // ReadState reads a state structure out of a reader in the format that // was written by WriteState. func ReadState(src io.Reader) (*State, error) { buf := bufio.NewReader(src) + if _, err := buf.Peek(1); err != nil { + // the error is either io.EOF or "invalid argument", and both are from + // an empty state. + return nil, ErrNoState + } if err := testForV0State(buf); err != nil { return nil, err @@ -1976,6 +2056,48 @@ func WriteState(d *State, dst io.Writer) error { return nil } +// resourceNameSort implements the sort.Interface to sort name parts lexically for +// strings and numerically for integer indexes. +type resourceNameSort []string + +func (r resourceNameSort) Len() int { return len(r) } +func (r resourceNameSort) Swap(i, j int) { r[i], r[j] = r[j], r[i] } + +func (r resourceNameSort) Less(i, j int) bool { + iParts := strings.Split(r[i], ".") + jParts := strings.Split(r[j], ".") + + end := len(iParts) + if len(jParts) < end { + end = len(jParts) + } + + for idx := 0; idx < end; idx++ { + if iParts[idx] == jParts[idx] { + continue + } + + // sort on the first non-matching part + iInt, iIntErr := strconv.Atoi(iParts[idx]) + jInt, jIntErr := strconv.Atoi(jParts[idx]) + + switch { + case iIntErr == nil && jIntErr == nil: + // sort numerically if both parts are integers + return iInt < jInt + case iIntErr == nil: + // numbers sort before strings + return true + case jIntErr == nil: + return false + default: + return iParts[idx] < jParts[idx] + } + } + + return r[i] < r[j] +} + // moduleStateSort implements sort.Interface to sort module states type moduleStateSort []*ModuleState diff --git a/vendor/github.com/hashicorp/terraform/terraform/state_filter.go b/vendor/github.com/hashicorp/terraform/terraform/state_filter.go index 1b41a3b..2dcb11b 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/state_filter.go +++ b/vendor/github.com/hashicorp/terraform/terraform/state_filter.go @@ -34,7 +34,7 @@ func (f *StateFilter) Filter(fs ...string) ([]*StateFilterResult, error) { as[i] = a } - // If we werent given any filters, then we list all + // If we weren't given any filters, then we list all if len(fs) == 0 { as = append(as, &ResourceAddress{Index: -1}) } @@ -85,15 +85,22 @@ func (f *StateFilter) filterSingle(a *ResourceAddress) []*StateFilterResult { // the modules to find relevant resources. for _, m := range modules { for n, r := range m.Resources { - if f.relevant(a, r) { - // The name in the state contains valuable information. Parse. - key, err := ParseResourceStateKey(n) - if err != nil { - // If we get an error parsing, then just ignore it - // out of the state. - continue - } + // The name in the state contains valuable information. Parse. + key, err := ParseResourceStateKey(n) + if err != nil { + // If we get an error parsing, then just ignore it + // out of the state. + continue + } + // Older states and test fixtures often don't contain the + // type directly on the ResourceState. We add this so StateFilter + // is a bit more robust. + if r.Type == "" { + r.Type = key.Type + } + + if f.relevant(a, r) { if a.Name != "" && a.Name != key.Name { // Name doesn't match continue @@ -243,6 +250,13 @@ func (s StateFilterResultSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s StateFilterResultSlice) Less(i, j int) bool { a, b := s[i], s[j] + // if these address contain an index, we want to sort by index rather than name + addrA, errA := ParseResourceAddress(a.Address) + addrB, errB := ParseResourceAddress(b.Address) + if errA == nil && errB == nil && addrA.Name == addrB.Name && addrA.Index != addrB.Index { + return addrA.Index < addrB.Index + } + // If the addresses are different it is just lexographic sorting if a.Address != b.Address { return a.Address < b.Address diff --git a/vendor/github.com/hashicorp/terraform/terraform/state_upgrade_v1_to_v2.go b/vendor/github.com/hashicorp/terraform/terraform/state_upgrade_v1_to_v2.go index 0386153..aa13cce 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/state_upgrade_v1_to_v2.go +++ b/vendor/github.com/hashicorp/terraform/terraform/state_upgrade_v1_to_v2.go @@ -64,10 +64,19 @@ func (old *moduleStateV1) upgradeToV2() (*ModuleState, error) { return nil, nil } - path, err := copystructure.Copy(old.Path) + pathRaw, err := copystructure.Copy(old.Path) if err != nil { return nil, fmt.Errorf("Error upgrading ModuleState V1: %v", err) } + path, ok := pathRaw.([]string) + if !ok { + return nil, fmt.Errorf("Error upgrading ModuleState V1: path is not a list of strings") + } + if len(path) == 0 { + // We found some V1 states with a nil path. Assume root and catch + // duplicate path errors later (as part of Validate). + path = rootModulePath + } // Outputs needs upgrading to use the new structure outputs := make(map[string]*OutputState) @@ -94,7 +103,7 @@ func (old *moduleStateV1) upgradeToV2() (*ModuleState, error) { } return &ModuleState{ - Path: path.([]string), + Path: path, Outputs: outputs, Resources: resources, Dependencies: dependencies.([]string), @@ -150,16 +159,22 @@ func (old *instanceStateV1) upgradeToV2() (*InstanceState, error) { if err != nil { return nil, fmt.Errorf("Error upgrading InstanceState V1: %v", err) } + meta, err := copystructure.Copy(old.Meta) if err != nil { return nil, fmt.Errorf("Error upgrading InstanceState V1: %v", err) } + newMeta := make(map[string]interface{}) + for k, v := range meta.(map[string]string) { + newMeta[k] = v + } + return &InstanceState{ ID: old.ID, Attributes: attributes.(map[string]string), Ephemeral: *ephemeral, - Meta: meta.(map[string]string), + Meta: newMeta, }, nil } diff --git a/vendor/github.com/hashicorp/terraform/terraform/state_upgrade_v2_to_v3.go b/vendor/github.com/hashicorp/terraform/terraform/state_upgrade_v2_to_v3.go index 1fc458d..e52d35f 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/state_upgrade_v2_to_v3.go +++ b/vendor/github.com/hashicorp/terraform/terraform/state_upgrade_v2_to_v3.go @@ -18,7 +18,7 @@ func upgradeStateV2ToV3(old *State) (*State, error) { // Ensure the copied version is v2 before attempting to upgrade if new.Version != 2 { - return nil, fmt.Errorf("Cannot appply v2->v3 state upgrade to " + + return nil, fmt.Errorf("Cannot apply v2->v3 state upgrade to " + "a state which is not version 2.") } diff --git a/vendor/github.com/hashicorp/terraform/terraform/testing.go b/vendor/github.com/hashicorp/terraform/terraform/testing.go new file mode 100644 index 0000000..3f0418d --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/terraform/testing.go @@ -0,0 +1,19 @@ +package terraform + +import ( + "os" + "testing" +) + +// TestStateFile writes the given state to the path. +func TestStateFile(t *testing.T, path string, state *State) { + f, err := os.Create(path) + if err != nil { + t.Fatalf("err: %s", err) + } + defer f.Close() + + if err := WriteState(state, f); err != nil { + t.Fatalf("err: %s", err) + } +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_attach_state.go b/vendor/github.com/hashicorp/terraform/terraform/transform_attach_state.go index 623f843..564ff08 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_attach_state.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_attach_state.go @@ -49,7 +49,7 @@ func (t *AttachStateTransformer) Transform(g *Graph) error { for _, result := range results { if rs, ok := result.Value.(*ResourceState); ok { log.Printf( - "[DEBUG] Attaching resource state to %q: %s", + "[DEBUG] Attaching resource state to %q: %#v", dag.VertexName(v), rs) an.AttachResourceState(rs) found = true diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_config.go b/vendor/github.com/hashicorp/terraform/terraform/transform_config.go index c2dad20..61bce85 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_config.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_config.go @@ -4,7 +4,9 @@ import ( "errors" "fmt" "log" + "sync" + "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/dag" ) @@ -23,10 +25,25 @@ import ( type ConfigTransformer struct { Concrete ConcreteResourceNodeFunc + // Module is the module to add resources from. Module *module.Tree + + // Unique will only add resources that aren't already present in the graph. + Unique bool + + // Mode will only add resources that match the given mode + ModeFilter bool + Mode config.ResourceMode + + l sync.Mutex + uniqueMap map[string]struct{} } func (t *ConfigTransformer) Transform(g *Graph) error { + // Lock since we use some internal state + t.l.Lock() + defer t.l.Unlock() + // If no module is given, we don't do anything if t.Module == nil { return nil @@ -37,6 +54,18 @@ func (t *ConfigTransformer) Transform(g *Graph) error { return errors.New("module must be loaded for ConfigTransformer") } + // Reset the uniqueness map. If we're tracking uniques, then populate + // it with addresses. + t.uniqueMap = make(map[string]struct{}) + defer func() { t.uniqueMap = nil }() + if t.Unique { + for _, v := range g.Vertices() { + if rn, ok := v.(GraphNodeResource); ok { + t.uniqueMap[rn.ResourceAddr().String()] = struct{}{} + } + } + } + // Start the transformation process return t.transform(g, t.Module) } @@ -66,13 +95,13 @@ func (t *ConfigTransformer) transformSingle(g *Graph, m *module.Tree) error { log.Printf("[TRACE] ConfigTransformer: Starting for path: %v", m.Path()) // Get the configuration for this module - config := m.Config() + conf := m.Config() // Build the path we're at path := m.Path() // Write all the resources out - for _, r := range config.Resources { + for _, r := range conf.Resources { // Build the resource address addr, err := parseResourceAddressConfig(r) if err != nil { @@ -81,6 +110,16 @@ func (t *ConfigTransformer) transformSingle(g *Graph, m *module.Tree) error { } addr.Path = path + // If this is already in our uniqueness map, don't add it again + if _, ok := t.uniqueMap[addr.String()]; ok { + continue + } + + // Remove non-matching modes + if t.ModeFilter && addr.Mode != t.Mode { + continue + } + // Build the abstract node and the concrete one abstract := &NodeAbstractResource{Addr: addr} var node dag.Vertex = abstract diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_config_old.go b/vendor/github.com/hashicorp/terraform/terraform/transform_config_old.go index 5f98516..ec41258 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_config_old.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_config_old.go @@ -1,111 +1,11 @@ package terraform import ( - "errors" "fmt" - "github.com/hashicorp/go-multierror" "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/config/module" ) -// ConfigTransformerOld is a GraphTransformer that adds the configuration -// to the graph. The module used to configure this transformer must be -// the root module. We'll look up the child module by the Path in the -// Graph. -type ConfigTransformerOld struct { - Module *module.Tree -} - -func (t *ConfigTransformerOld) Transform(g *Graph) error { - // A module is required and also must be completely loaded. - if t.Module == nil { - return errors.New("module must not be nil") - } - if !t.Module.Loaded() { - return errors.New("module must be loaded") - } - - // Get the module we care about - module := t.Module.Child(g.Path[1:]) - if module == nil { - return nil - } - - // Get the configuration for this module - config := module.Config() - - // Create the node list we'll use for the graph - nodes := make([]graphNodeConfig, 0, - (len(config.Variables)+ - len(config.ProviderConfigs)+ - len(config.Modules)+ - len(config.Resources)+ - len(config.Outputs))*2) - - // Write all the variables out - for _, v := range config.Variables { - nodes = append(nodes, &GraphNodeConfigVariable{ - Variable: v, - ModuleTree: t.Module, - ModulePath: g.Path, - }) - } - - // Write all the provider configs out - for _, pc := range config.ProviderConfigs { - nodes = append(nodes, &GraphNodeConfigProvider{Provider: pc}) - } - - // Write all the resources out - for _, r := range config.Resources { - nodes = append(nodes, &GraphNodeConfigResource{ - Resource: r, - Path: g.Path, - }) - } - - // Write all the modules out - children := module.Children() - for _, m := range config.Modules { - path := make([]string, len(g.Path), len(g.Path)+1) - copy(path, g.Path) - path = append(path, m.Name) - - nodes = append(nodes, &GraphNodeConfigModule{ - Path: path, - Module: m, - Tree: children[m.Name], - }) - } - - // Write all the outputs out - for _, o := range config.Outputs { - nodes = append(nodes, &GraphNodeConfigOutput{Output: o}) - } - - // Err is where the final error value will go if there is one - var err error - - // Build the graph vertices - for _, n := range nodes { - g.Add(n) - } - - // Build up the dependencies. We have to do this outside of the above - // loop since the nodes need to be in place for us to build the deps. - for _, n := range nodes { - if missing := g.ConnectDependent(n); len(missing) > 0 { - for _, m := range missing { - err = multierror.Append(err, fmt.Errorf( - "%s: missing dependency: %s", n.Name(), m)) - } - } - } - - return err -} - // varNameForVar returns the VarName value for an interpolated variable. // This value is compared to the VarName() value for the nodes within the // graph to build the graph edges. diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_deposed.go b/vendor/github.com/hashicorp/terraform/terraform/transform_deposed.go index 456e8bf..2148cef 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_deposed.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_deposed.go @@ -127,6 +127,12 @@ func (n *graphNodeDeposedResource) EvalTree() EvalNode { State: &state, Output: &diff, }, + // Call pre-apply hook + &EvalApplyPre{ + Info: info, + State: &state, + Diff: &diff, + }, &EvalApply{ Info: info, State: &state, diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_destroy.go b/vendor/github.com/hashicorp/terraform/terraform/transform_destroy.go deleted file mode 100644 index 64e2958..0000000 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_destroy.go +++ /dev/null @@ -1,284 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/dag" -) - -// GraphNodeDestroyable is the interface that nodes that can be destroyed -// must implement. This is used to automatically handle the creation of -// destroy nodes in the graph and the dependency ordering of those destroys. -type GraphNodeDestroyable interface { - // DestroyNode returns the node used for the destroy with the given - // mode. If this returns nil, then a destroy node for that mode - // will not be added. - DestroyNode() GraphNodeDestroy -} - -// GraphNodeDestroy is the interface that must implemented by -// nodes that destroy. -type GraphNodeDestroy interface { - dag.Vertex - - // CreateBeforeDestroy is called to check whether this node - // should be created before it is destroyed. The CreateBeforeDestroy - // transformer uses this information to setup the graph. - CreateBeforeDestroy() bool - - // CreateNode returns the node used for the create side of this - // destroy. This must already exist within the graph. - CreateNode() dag.Vertex -} - -// GraphNodeDestroyPrunable is the interface that can be implemented to -// signal that this node can be pruned depending on state. -type GraphNodeDestroyPrunable interface { - // DestroyInclude is called to check if this node should be included - // with the given state. The state and diff must NOT be modified. - DestroyInclude(*ModuleDiff, *ModuleState) bool -} - -// GraphNodeEdgeInclude can be implemented to not include something -// as an edge within the destroy graph. This is usually done because it -// might cause unnecessary cycles. -type GraphNodeDestroyEdgeInclude interface { - DestroyEdgeInclude(dag.Vertex) bool -} - -// DestroyTransformer is a GraphTransformer that creates the destruction -// nodes for things that _might_ be destroyed. -type DestroyTransformer struct { - FullDestroy bool -} - -func (t *DestroyTransformer) Transform(g *Graph) error { - var connect, remove []dag.Edge - nodeToCn := make(map[dag.Vertex]dag.Vertex, len(g.Vertices())) - nodeToDn := make(map[dag.Vertex]dag.Vertex, len(g.Vertices())) - for _, v := range g.Vertices() { - // If it is not a destroyable, we don't care - cn, ok := v.(GraphNodeDestroyable) - if !ok { - continue - } - - // Grab the destroy side of the node and connect it through - n := cn.DestroyNode() - if n == nil { - continue - } - - // Store it - nodeToCn[n] = cn - nodeToDn[cn] = n - - // If the creation node is equal to the destroy node, then - // don't do any of the edge jump rope below. - if n.(interface{}) == cn.(interface{}) { - continue - } - - // Add it to the graph - g.Add(n) - - // Inherit all the edges from the old node - downEdges := g.DownEdges(v).List() - for _, edgeRaw := range downEdges { - // If this thing specifically requests to not be depended on - // by destroy nodes, then don't. - if i, ok := edgeRaw.(GraphNodeDestroyEdgeInclude); ok && - !i.DestroyEdgeInclude(v) { - continue - } - - g.Connect(dag.BasicEdge(n, edgeRaw.(dag.Vertex))) - } - - // Add a new edge to connect the node to be created to - // the destroy node. - connect = append(connect, dag.BasicEdge(v, n)) - } - - // Go through the nodes we added and determine if they depend - // on any nodes with a destroy node. If so, depend on that instead. - for n, _ := range nodeToCn { - for _, downRaw := range g.DownEdges(n).List() { - target := downRaw.(dag.Vertex) - cn2, ok := target.(GraphNodeDestroyable) - if !ok { - continue - } - - newTarget := nodeToDn[cn2] - if newTarget == nil { - continue - } - - // Make the new edge and transpose - connect = append(connect, dag.BasicEdge(newTarget, n)) - - // Remove the old edge - remove = append(remove, dag.BasicEdge(n, target)) - } - } - - // Atomatically add/remove the edges - for _, e := range connect { - g.Connect(e) - } - for _, e := range remove { - g.RemoveEdge(e) - } - - return nil -} - -// CreateBeforeDestroyTransformer is a GraphTransformer that modifies -// the destroys of some nodes so that the creation happens before the -// destroy. -type CreateBeforeDestroyTransformer struct{} - -func (t *CreateBeforeDestroyTransformer) Transform(g *Graph) error { - // We "stage" the edge connections/destroys in these slices so that - // while we're doing the edge transformations (transpositions) in - // the graph, we're not affecting future edge transpositions. These - // slices let us stage ALL the changes that WILL happen so that all - // of the transformations happen atomically. - var connect, destroy []dag.Edge - - for _, v := range g.Vertices() { - // We only care to use the destroy nodes - dn, ok := v.(GraphNodeDestroy) - if !ok { - continue - } - - // If the node doesn't need to create before destroy, then continue - if !dn.CreateBeforeDestroy() { - if noCreateBeforeDestroyAncestors(g, dn) { - continue - } - - // PURPOSELY HACKY FIX SINCE THIS TRANSFORM IS DEPRECATED. - // This is a hacky way to fix GH-10439. For a detailed description - // of the fix, see CBDEdgeTransformer, which is the equivalent - // transform used by the new graphs. - // - // This transform is deprecated because it is only used by the - // old graphs which are going to be removed. - var update *config.Resource - if dn, ok := v.(*graphNodeResourceDestroy); ok { - update = dn.Original.Resource - } - if dn, ok := v.(*graphNodeResourceDestroyFlat); ok { - update = dn.Original.Resource - } - if update != nil { - update.Lifecycle.CreateBeforeDestroy = true - } - } - - // Get the creation side of this node - cn := dn.CreateNode() - - // Take all the things which depend on the creation node and - // make them dependencies on the destruction. Clarifying this - // with an example: if you have a web server and a load balancer - // and the load balancer depends on the web server, then when we - // do a create before destroy, we want to make sure the steps are: - // - // 1.) Create new web server - // 2.) Update load balancer - // 3.) Delete old web server - // - // This ensures that. - for _, sourceRaw := range g.UpEdges(cn).List() { - source := sourceRaw.(dag.Vertex) - - // If the graph has a "root" node (one added by a RootTransformer and not - // just a resource that happens to have no ancestors), we don't want to - // add any edges to it, because then it ceases to be a root. - if _, ok := source.(graphNodeRoot); ok { - continue - } - - connect = append(connect, dag.BasicEdge(dn, source)) - } - - // Swap the edge so that the destroy depends on the creation - // happening... - connect = append(connect, dag.BasicEdge(dn, cn)) - destroy = append(destroy, dag.BasicEdge(cn, dn)) - } - - for _, edge := range connect { - g.Connect(edge) - } - for _, edge := range destroy { - g.RemoveEdge(edge) - } - - return nil -} - -// noCreateBeforeDestroyAncestors verifies that a vertex has no ancestors that -// are CreateBeforeDestroy. -// If this vertex has an ancestor with CreateBeforeDestroy, we will need to -// inherit that behavior and re-order the edges even if this node type doesn't -// directly implement CreateBeforeDestroy. -func noCreateBeforeDestroyAncestors(g *Graph, v dag.Vertex) bool { - s, _ := g.Ancestors(v) - if s == nil { - return true - } - for _, v := range s.List() { - dn, ok := v.(GraphNodeDestroy) - if !ok { - continue - } - - if dn.CreateBeforeDestroy() { - // some ancestor is CreateBeforeDestroy, so we need to follow suit - return false - } - } - return true -} - -// PruneDestroyTransformer is a GraphTransformer that removes the destroy -// nodes that aren't in the diff. -type PruneDestroyTransformer struct { - Diff *Diff - State *State -} - -func (t *PruneDestroyTransformer) Transform(g *Graph) error { - for _, v := range g.Vertices() { - // If it is not a destroyer, we don't care - dn, ok := v.(GraphNodeDestroyPrunable) - if !ok { - continue - } - - path := g.Path - if pn, ok := v.(GraphNodeSubPath); ok { - path = pn.Path() - } - - var modDiff *ModuleDiff - var modState *ModuleState - if t.Diff != nil { - modDiff = t.Diff.ModuleByPath(path) - } - if t.State != nil { - modState = t.State.ModuleByPath(path) - } - - // Remove it if we should - if !dn.DestroyInclude(modDiff, modState) { - g.Remove(v) - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_destroy_cbd.go b/vendor/github.com/hashicorp/terraform/terraform/transform_destroy_cbd.go index e1a525b..edfb460 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_destroy_cbd.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_destroy_cbd.go @@ -89,9 +89,20 @@ func (t *CBDEdgeTransformer) Transform(g *Graph) error { g.Connect(&DestroyEdge{S: de.Target(), T: de.Source()}) } + // If the address has an index, we strip that. Our depMap creation + // graph doesn't expand counts so we don't currently get _exact_ + // dependencies. One day when we limit dependencies more exactly + // this will have to change. We have a test case covering this + // (depNonCBDCountBoth) so it'll be caught. + addr := dn.DestroyAddr() + if addr.Index >= 0 { + addr = addr.Copy() // Copy so that we don't modify any pointers + addr.Index = -1 + } + // Add this to the list of nodes that we need to fix up // the edges for (step 2 above in the docs). - key := dn.DestroyAddr().String() + key := addr.String() destroyMap[key] = append(destroyMap[key], v) } @@ -134,9 +145,19 @@ func (t *CBDEdgeTransformer) Transform(g *Graph) error { // Get the address addr := rn.CreateAddr() - key := addr.String() + + // If the address has an index, we strip that. Our depMap creation + // graph doesn't expand counts so we don't currently get _exact_ + // dependencies. One day when we limit dependencies more exactly + // this will have to change. We have a test case covering this + // (depNonCBDCount) so it'll be caught. + if addr.Index >= 0 { + addr = addr.Copy() // Copy so that we don't modify any pointers + addr.Index = -1 + } // If there is nothing this resource should depend on, ignore it + key := addr.String() dns, ok := depMap[key] if !ok { continue diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_destroy_edge.go b/vendor/github.com/hashicorp/terraform/terraform/transform_destroy_edge.go index c837cf1..22be1ab 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_destroy_edge.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_destroy_edge.go @@ -159,9 +159,15 @@ func (t *DestroyEdgeTransformer) Transform(g *Graph) error { // This part is a little bit weird but is the best way to // find the dependencies we need to: build a graph and use the // attach config and state transformers then ask for references. - node := &NodeAbstractResource{Addr: addr} - tempG.Add(node) - tempDestroyed = append(tempDestroyed, node) + abstract := &NodeAbstractResource{Addr: addr} + tempG.Add(abstract) + tempDestroyed = append(tempDestroyed, abstract) + + // We also add the destroy version here since the destroy can + // depend on things that the creation doesn't (destroy provisioners). + destroy := &NodeDestroyResource{NodeAbstractResource: abstract} + tempG.Add(destroy) + tempDestroyed = append(tempDestroyed, destroy) } // Run the graph transforms so we have the information we need to diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_expand.go b/vendor/github.com/hashicorp/terraform/terraform/transform_expand.go index b58c6bf..982c098 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_expand.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_expand.go @@ -46,20 +46,3 @@ func (t *ExpandTransform) Transform(v dag.Vertex) (dag.Vertex, error) { log.Printf("[DEBUG] vertex %q: static expanding", dag.VertexName(ev)) return ev.Expand(t.Builder) } - -type GraphNodeBasicSubgraph struct { - NameValue string - Graph *Graph -} - -func (n *GraphNodeBasicSubgraph) Name() string { - return n.NameValue -} - -func (n *GraphNodeBasicSubgraph) Subgraph() dag.Grapher { - return n.Graph -} - -func (n *GraphNodeBasicSubgraph) FlattenGraph() *Graph { - return n.Graph -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_flatten.go b/vendor/github.com/hashicorp/terraform/terraform/transform_flatten.go deleted file mode 100644 index 206bf97..0000000 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_flatten.go +++ /dev/null @@ -1,107 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform/dag" -) - -// GraphNodeFlatGraph must be implemented by nodes that have subgraphs -// that they want flattened into the graph. -type GraphNodeFlatGraph interface { - FlattenGraph() *Graph -} - -// GraphNodeFlattenable must be implemented by all nodes that can be -// flattened. If a FlattenGraph returns any nodes that can't be flattened, -// it will be an error. -// -// If Flatten returns nil for the Vertex along with a nil error, it will -// removed from the graph. -type GraphNodeFlattenable interface { - Flatten(path []string) (dag.Vertex, error) -} - -// FlattenTransformer is a transformer that goes through the graph, finds -// subgraphs that can be flattened, and flattens them into this graph, -// removing the prior subgraph node. -type FlattenTransformer struct{} - -func (t *FlattenTransformer) Transform(g *Graph) error { - for _, v := range g.Vertices() { - fn, ok := v.(GraphNodeFlatGraph) - if !ok { - continue - } - - // If we don't want to be flattened, don't do it - subgraph := fn.FlattenGraph() - if subgraph == nil { - continue - } - - // Get all the things that depend on this node. We'll re-connect - // dependents later. We have to copy these here since the UpEdges - // value will be deleted after the Remove below. - dependents := make([]dag.Vertex, 0, 5) - for _, v := range g.UpEdges(v).List() { - dependents = append(dependents, v) - } - - // Remove the old node - g.Remove(v) - - // Go through the subgraph and flatten all the nodes - for _, sv := range subgraph.Vertices() { - // If the vertex already has a subpath then we assume it has - // already been flattened. Ignore it. - if _, ok := sv.(GraphNodeSubPath); ok { - continue - } - - fn, ok := sv.(GraphNodeFlattenable) - if !ok { - return fmt.Errorf( - "unflattenable node: %s %T", - dag.VertexName(sv), sv) - } - - v, err := fn.Flatten(subgraph.Path) - if err != nil { - return fmt.Errorf( - "error flattening %s (%T): %s", - dag.VertexName(sv), sv, err) - } - - if v == nil { - subgraph.Remove(v) - } else { - subgraph.Replace(sv, v) - } - } - - // Now that we've handled any changes to the graph that are - // needed, we can add them all to our graph along with their edges. - for _, sv := range subgraph.Vertices() { - g.Add(sv) - } - for _, se := range subgraph.Edges() { - g.Connect(se) - } - - // Connect the dependencies for all the new nodes that we added. - // This will properly connect variables to their sources, for example. - for _, sv := range subgraph.Vertices() { - g.ConnectDependent(sv) - } - - // Re-connect all the things that dependent on the graph - // we just flattened. This should connect them back into the - // correct nodes if their DependentOn() is setup correctly. - for _, v := range dependents { - g.ConnectDependent(v) - } - } - - return nil -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_module_destroy_old.go b/vendor/github.com/hashicorp/terraform/terraform/transform_module_destroy_old.go deleted file mode 100644 index e971838..0000000 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_module_destroy_old.go +++ /dev/null @@ -1,62 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform/dag" -) - -// ModuleDestroyTransformer is a GraphTransformer that adds a node -// to the graph that will just mark the full module for destroy in -// the destroy scenario. -type ModuleDestroyTransformerOld struct{} - -func (t *ModuleDestroyTransformerOld) Transform(g *Graph) error { - // Create the node - n := &graphNodeModuleDestroy{Path: g.Path} - - // Add it to the graph. We don't need any edges because - // it can happen whenever. - g.Add(n) - - return nil -} - -type graphNodeModuleDestroy struct { - Path []string -} - -func (n *graphNodeModuleDestroy) Name() string { - return "plan-destroy" -} - -// GraphNodeEvalable impl. -func (n *graphNodeModuleDestroy) EvalTree() EvalNode { - return &EvalOpFilter{ - Ops: []walkOperation{walkPlanDestroy}, - Node: &EvalDiffDestroyModule{Path: n.Path}, - } -} - -// GraphNodeFlattenable impl. -func (n *graphNodeModuleDestroy) Flatten(p []string) (dag.Vertex, error) { - return &graphNodeModuleDestroyFlat{ - graphNodeModuleDestroy: n, - PathValue: p, - }, nil -} - -type graphNodeModuleDestroyFlat struct { - *graphNodeModuleDestroy - - PathValue []string -} - -func (n *graphNodeModuleDestroyFlat) Name() string { - return fmt.Sprintf( - "%s.%s", modulePrefixStr(n.PathValue), n.graphNodeModuleDestroy.Name()) -} - -func (n *graphNodeModuleDestroyFlat) Path() []string { - return n.PathValue -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_noop.go b/vendor/github.com/hashicorp/terraform/terraform/transform_noop.go deleted file mode 100644 index e36b619..0000000 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_noop.go +++ /dev/null @@ -1,104 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform/dag" -) - -// GraphNodeNoopPrunable can be implemented by nodes that can be -// pruned if they are noops. -type GraphNodeNoopPrunable interface { - Noop(*NoopOpts) bool -} - -// NoopOpts are the options available to determine if your node is a noop. -type NoopOpts struct { - Graph *Graph - Vertex dag.Vertex - Diff *Diff - State *State - ModDiff *ModuleDiff - ModState *ModuleState -} - -// PruneNoopTransformer is a graph transform that prunes nodes that -// consider themselves no-ops. This is done to both simplify the graph -// as well as to remove graph nodes that might otherwise cause problems -// during the graph run. Therefore, this transformer isn't completely -// an optimization step, and can instead be considered critical to -// Terraform operations. -// -// Example of the above case: variables for modules interpolate their values. -// Interpolation will fail on destruction (since attributes are being deleted), -// but variables shouldn't even eval if there is nothing that will consume -// the variable. Therefore, variables can note that they can be omitted -// safely in this case. -// -// The PruneNoopTransformer will prune nodes depth first, and will automatically -// create connect through the dependencies of pruned nodes. For example, -// if we have a graph A => B => C (A depends on B, etc.), and B decides to -// be removed, we'll still be left with A => C; the edge will be properly -// connected. -type PruneNoopTransformer struct { - Diff *Diff - State *State -} - -func (t *PruneNoopTransformer) Transform(g *Graph) error { - // Find the leaves. - leaves := make([]dag.Vertex, 0, 10) - for _, v := range g.Vertices() { - if g.DownEdges(v).Len() == 0 { - leaves = append(leaves, v) - } - } - - // Do a depth first walk from the leaves and remove things. - return g.ReverseDepthFirstWalk(leaves, func(v dag.Vertex, depth int) error { - // We need a prunable - pn, ok := v.(GraphNodeNoopPrunable) - if !ok { - return nil - } - - // Start building the noop opts - path := g.Path - if pn, ok := v.(GraphNodeSubPath); ok { - path = pn.Path() - } - - var modDiff *ModuleDiff - var modState *ModuleState - if t.Diff != nil { - modDiff = t.Diff.ModuleByPath(path) - } - if t.State != nil { - modState = t.State.ModuleByPath(path) - } - - // Determine if its a noop. If it isn't, just return - noop := pn.Noop(&NoopOpts{ - Graph: g, - Vertex: v, - Diff: t.Diff, - State: t.State, - ModDiff: modDiff, - ModState: modState, - }) - if !noop { - return nil - } - - // It is a noop! We first preserve edges. - up := g.UpEdges(v).List() - for _, downV := range g.DownEdges(v).List() { - for _, upV := range up { - g.Connect(dag.BasicEdge(upV, downV)) - } - } - - // Then remove it - g.Remove(v) - - return nil - }) -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_orphan.go b/vendor/github.com/hashicorp/terraform/terraform/transform_orphan.go deleted file mode 100644 index 83a4f6d..0000000 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_orphan.go +++ /dev/null @@ -1,432 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/config/module" - "github.com/hashicorp/terraform/dag" -) - -// GraphNodeStateRepresentative is an interface that can be implemented by -// a node to say that it is representing a resource in the state. -type GraphNodeStateRepresentative interface { - StateId() []string -} - -// OrphanTransformer is a GraphTransformer that adds orphans to the -// graph. This transformer adds both resource and module orphans. -type OrphanTransformer struct { - // Resource is resource configuration. This is only non-nil when - // expanding a resource that is in the configuration. It can't be - // dependend on. - Resource *config.Resource - - // State is the global state. We require the global state to - // properly find module orphans at our path. - State *State - - // Module is the root module. We'll look up the proper configuration - // using the graph path. - Module *module.Tree - - // View, if non-nil will set a view on the module state. - View string -} - -func (t *OrphanTransformer) Transform(g *Graph) error { - if t.State == nil { - // If the entire state is nil, there can't be any orphans - return nil - } - - // Build up all our state representatives - resourceRep := make(map[string]struct{}) - for _, v := range g.Vertices() { - if sr, ok := v.(GraphNodeStateRepresentative); ok { - for _, k := range sr.StateId() { - resourceRep[k] = struct{}{} - } - } - } - - var config *config.Config - if t.Module != nil { - if module := t.Module.Child(g.Path[1:]); module != nil { - config = module.Config() - } - } - - var resourceVertexes []dag.Vertex - if state := t.State.ModuleByPath(g.Path); state != nil { - // If we have state, then we can have orphan resources - - // If we have a view, get the view - if t.View != "" { - state = state.View(t.View) - } - - resourceOrphans := state.Orphans(config) - - resourceVertexes = make([]dag.Vertex, len(resourceOrphans)) - for i, k := range resourceOrphans { - // If this orphan is represented by some other node somehow, - // then ignore it. - if _, ok := resourceRep[k]; ok { - continue - } - - rs := state.Resources[k] - - rsk, err := ParseResourceStateKey(k) - if err != nil { - return err - } - resourceVertexes[i] = g.Add(&graphNodeOrphanResource{ - Path: g.Path, - ResourceKey: rsk, - Resource: t.Resource, - Provider: rs.Provider, - dependentOn: rs.Dependencies, - }) - } - } - - // Go over each module orphan and add it to the graph. We store the - // vertexes and states outside so that we can connect dependencies later. - moduleOrphans := t.State.ModuleOrphans(g.Path, config) - moduleVertexes := make([]dag.Vertex, len(moduleOrphans)) - for i, path := range moduleOrphans { - var deps []string - if s := t.State.ModuleByPath(path); s != nil { - deps = s.Dependencies - } - - moduleVertexes[i] = g.Add(&graphNodeOrphanModule{ - Path: path, - dependentOn: deps, - }) - } - - // Now do the dependencies. We do this _after_ adding all the orphan - // nodes above because there are cases in which the orphans themselves - // depend on other orphans. - - // Resource dependencies - for _, v := range resourceVertexes { - g.ConnectDependent(v) - } - - // Module dependencies - for _, v := range moduleVertexes { - g.ConnectDependent(v) - } - - return nil -} - -// graphNodeOrphanModule is the graph vertex representing an orphan resource.. -type graphNodeOrphanModule struct { - Path []string - - dependentOn []string -} - -func (n *graphNodeOrphanModule) DependableName() []string { - return []string{n.dependableName()} -} - -func (n *graphNodeOrphanModule) DependentOn() []string { - return n.dependentOn -} - -func (n *graphNodeOrphanModule) Name() string { - return fmt.Sprintf("%s (orphan)", n.dependableName()) -} - -func (n *graphNodeOrphanModule) dependableName() string { - return fmt.Sprintf("module.%s", n.Path[len(n.Path)-1]) -} - -// GraphNodeExpandable -func (n *graphNodeOrphanModule) Expand(b GraphBuilder) (GraphNodeSubgraph, error) { - g, err := b.Build(n.Path) - if err != nil { - return nil, err - } - - return &GraphNodeBasicSubgraph{ - NameValue: n.Name(), - Graph: g, - }, nil -} - -// graphNodeOrphanResource is the graph vertex representing an orphan resource.. -type graphNodeOrphanResource struct { - Path []string - ResourceKey *ResourceStateKey - Resource *config.Resource - Provider string - - dependentOn []string -} - -func (n *graphNodeOrphanResource) ConfigType() GraphNodeConfigType { - return GraphNodeConfigTypeResource -} - -func (n *graphNodeOrphanResource) ResourceAddress() *ResourceAddress { - return &ResourceAddress{ - Index: n.ResourceKey.Index, - InstanceType: TypePrimary, - Name: n.ResourceKey.Name, - Path: n.Path[1:], - Type: n.ResourceKey.Type, - Mode: n.ResourceKey.Mode, - } -} - -func (n *graphNodeOrphanResource) DependableName() []string { - return []string{n.dependableName()} -} - -func (n *graphNodeOrphanResource) DependentOn() []string { - return n.dependentOn -} - -func (n *graphNodeOrphanResource) Flatten(p []string) (dag.Vertex, error) { - return &graphNodeOrphanResourceFlat{ - graphNodeOrphanResource: n, - PathValue: p, - }, nil -} - -func (n *graphNodeOrphanResource) Name() string { - return fmt.Sprintf("%s (orphan)", n.ResourceKey) -} - -func (n *graphNodeOrphanResource) ProvidedBy() []string { - return []string{resourceProvider(n.ResourceKey.Type, n.Provider)} -} - -// GraphNodeEvalable impl. -func (n *graphNodeOrphanResource) EvalTree() EvalNode { - - seq := &EvalSequence{Nodes: make([]EvalNode, 0, 5)} - - // Build instance info - info := &InstanceInfo{Id: n.ResourceKey.String(), Type: n.ResourceKey.Type} - info.uniqueExtra = "destroy" - - seq.Nodes = append(seq.Nodes, &EvalInstanceInfo{Info: info}) - - // Each resource mode has its own lifecycle - switch n.ResourceKey.Mode { - case config.ManagedResourceMode: - seq.Nodes = append( - seq.Nodes, - n.managedResourceEvalNodes(info)..., - ) - case config.DataResourceMode: - seq.Nodes = append( - seq.Nodes, - n.dataResourceEvalNodes(info)..., - ) - default: - panic(fmt.Errorf("unsupported resource mode %s", n.ResourceKey.Mode)) - } - - return seq -} - -func (n *graphNodeOrphanResource) managedResourceEvalNodes(info *InstanceInfo) []EvalNode { - var provider ResourceProvider - var state *InstanceState - - nodes := make([]EvalNode, 0, 3) - - // Refresh the resource - nodes = append(nodes, &EvalOpFilter{ - Ops: []walkOperation{walkRefresh}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Name: n.ProvidedBy()[0], - Output: &provider, - }, - &EvalReadState{ - Name: n.ResourceKey.String(), - Output: &state, - }, - &EvalRefresh{ - Info: info, - Provider: &provider, - State: &state, - Output: &state, - }, - &EvalWriteState{ - Name: n.ResourceKey.String(), - ResourceType: n.ResourceKey.Type, - Provider: n.Provider, - Dependencies: n.DependentOn(), - State: &state, - }, - }, - }, - }) - - // Diff the resource - var diff *InstanceDiff - nodes = append(nodes, &EvalOpFilter{ - Ops: []walkOperation{walkPlan, walkPlanDestroy}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalReadState{ - Name: n.ResourceKey.String(), - Output: &state, - }, - &EvalDiffDestroy{ - Info: info, - State: &state, - Output: &diff, - }, - &EvalCheckPreventDestroy{ - Resource: n.Resource, - ResourceId: n.ResourceKey.String(), - Diff: &diff, - }, - &EvalWriteDiff{ - Name: n.ResourceKey.String(), - Diff: &diff, - }, - }, - }, - }) - - // Apply - var err error - nodes = append(nodes, &EvalOpFilter{ - Ops: []walkOperation{walkApply, walkDestroy}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalReadDiff{ - Name: n.ResourceKey.String(), - Diff: &diff, - }, - &EvalGetProvider{ - Name: n.ProvidedBy()[0], - Output: &provider, - }, - &EvalReadState{ - Name: n.ResourceKey.String(), - Output: &state, - }, - &EvalApply{ - Info: info, - State: &state, - Diff: &diff, - Provider: &provider, - Output: &state, - Error: &err, - }, - &EvalWriteState{ - Name: n.ResourceKey.String(), - ResourceType: n.ResourceKey.Type, - Provider: n.Provider, - Dependencies: n.DependentOn(), - State: &state, - }, - &EvalApplyPost{ - Info: info, - State: &state, - Error: &err, - }, - &EvalUpdateStateHook{}, - }, - }, - }) - - return nodes -} - -func (n *graphNodeOrphanResource) dataResourceEvalNodes(info *InstanceInfo) []EvalNode { - nodes := make([]EvalNode, 0, 3) - - // This will remain nil, since we don't retain states for orphaned - // data resources. - var state *InstanceState - - // On both refresh and apply we just drop our state altogether, - // since the config resource validation pass will have proven that the - // resources remaining in the configuration don't need it. - nodes = append(nodes, &EvalOpFilter{ - Ops: []walkOperation{walkRefresh, walkApply}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalWriteState{ - Name: n.ResourceKey.String(), - ResourceType: n.ResourceKey.Type, - Provider: n.Provider, - Dependencies: n.DependentOn(), - State: &state, // state is nil - }, - }, - }, - }) - - return nodes -} - -func (n *graphNodeOrphanResource) dependableName() string { - return n.ResourceKey.String() -} - -// GraphNodeDestroyable impl. -func (n *graphNodeOrphanResource) DestroyNode() GraphNodeDestroy { - return n -} - -// GraphNodeDestroy impl. -func (n *graphNodeOrphanResource) CreateBeforeDestroy() bool { - return false -} - -func (n *graphNodeOrphanResource) CreateNode() dag.Vertex { - return n -} - -// Same as graphNodeOrphanResource, but for flattening -type graphNodeOrphanResourceFlat struct { - *graphNodeOrphanResource - - PathValue []string -} - -func (n *graphNodeOrphanResourceFlat) Name() string { - return fmt.Sprintf( - "%s.%s", modulePrefixStr(n.PathValue), n.graphNodeOrphanResource.Name()) -} - -func (n *graphNodeOrphanResourceFlat) Path() []string { - return n.PathValue -} - -// GraphNodeDestroyable impl. -func (n *graphNodeOrphanResourceFlat) DestroyNode() GraphNodeDestroy { - return n -} - -// GraphNodeDestroy impl. -func (n *graphNodeOrphanResourceFlat) CreateBeforeDestroy() bool { - return false -} - -func (n *graphNodeOrphanResourceFlat) CreateNode() dag.Vertex { - return n -} - -func (n *graphNodeOrphanResourceFlat) ProvidedBy() []string { - return modulePrefixList( - n.graphNodeOrphanResource.ProvidedBy(), - modulePrefixStr(n.PathValue)) -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_output_orphan.go b/vendor/github.com/hashicorp/terraform/terraform/transform_output_orphan.go deleted file mode 100644 index ffaa0b7..0000000 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_output_orphan.go +++ /dev/null @@ -1,101 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform/dag" -) - -// GraphNodeOutput is an interface that nodes that are outputs must -// implement. The OutputName returned is the name of the output key -// that they manage. -type GraphNodeOutput interface { - OutputName() string -} - -// AddOutputOrphanTransformer is a transformer that adds output orphans -// to the graph. Output orphans are outputs that are no longer in the -// configuration and therefore need to be removed from the state. -// -// NOTE: This is the _old_ way to add output orphans that is used with -// legacy graph builders. The new way is OrphanOutputTransformer. -type AddOutputOrphanTransformer struct { - State *State -} - -func (t *AddOutputOrphanTransformer) Transform(g *Graph) error { - // Get the state for this module. If we have no state, we have no orphans - state := t.State.ModuleByPath(g.Path) - if state == nil { - return nil - } - - // Create the set of outputs we do have in the graph - found := make(map[string]struct{}) - for _, v := range g.Vertices() { - on, ok := v.(GraphNodeOutput) - if !ok { - continue - } - - found[on.OutputName()] = struct{}{} - } - - // Go over all the outputs. If we don't have a graph node for it, - // create it. It doesn't need to depend on anything, since its just - // setting it empty. - for k, _ := range state.Outputs { - if _, ok := found[k]; ok { - continue - } - - g.Add(&graphNodeOrphanOutput{OutputName: k}) - } - - return nil -} - -type graphNodeOrphanOutput struct { - OutputName string -} - -func (n *graphNodeOrphanOutput) Name() string { - return fmt.Sprintf("output.%s (orphan)", n.OutputName) -} - -func (n *graphNodeOrphanOutput) EvalTree() EvalNode { - return &EvalOpFilter{ - Ops: []walkOperation{walkApply, walkDestroy, walkRefresh}, - Node: &EvalDeleteOutput{ - Name: n.OutputName, - }, - } -} - -// GraphNodeFlattenable impl. -func (n *graphNodeOrphanOutput) Flatten(p []string) (dag.Vertex, error) { - return &graphNodeOrphanOutputFlat{ - graphNodeOrphanOutput: n, - PathValue: p, - }, nil -} - -type graphNodeOrphanOutputFlat struct { - *graphNodeOrphanOutput - - PathValue []string -} - -func (n *graphNodeOrphanOutputFlat) Name() string { - return fmt.Sprintf( - "%s.%s", modulePrefixStr(n.PathValue), n.graphNodeOrphanOutput.Name()) -} - -func (n *graphNodeOrphanOutputFlat) EvalTree() EvalNode { - return &EvalOpFilter{ - Ops: []walkOperation{walkApply, walkDestroy, walkRefresh}, - Node: &EvalDeleteOutput{ - Name: n.OutputName, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_provider.go b/vendor/github.com/hashicorp/terraform/terraform/transform_provider.go index ac13bb9..b9695d5 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_provider.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_provider.go @@ -6,7 +6,6 @@ import ( "strings" "github.com/hashicorp/go-multierror" - "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/dag" ) @@ -15,7 +14,6 @@ import ( // they satisfy. type GraphNodeProvider interface { ProviderName() string - ProviderConfig() *config.RawConfig } // GraphNodeCloseProvider is an interface that nodes that can be a close @@ -126,7 +124,7 @@ func (t *MissingProviderTransformer) Transform(g *Graph) error { // Initialize factory if t.Concrete == nil { t.Concrete = func(a *NodeAbstractProvider) dag.Vertex { - return &graphNodeProvider{ProviderNameValue: a.NameValue} + return a } } @@ -188,14 +186,6 @@ func (t *MissingProviderTransformer) Transform(g *Graph) error { PathValue: path, }).(dag.Vertex) if len(path) > 0 { - if fn, ok := v.(GraphNodeFlattenable); ok { - var err error - v, err = fn.Flatten(path) - if err != nil { - return err - } - } - // We'll need the parent provider as well, so let's // add a dummy node to check to make sure that we add // that parent provider. @@ -230,9 +220,6 @@ func (t *ParentProviderTransformer) Transform(g *Graph) error { // We eventually want to get rid of the flat version entirely so // this is a stop-gap while it still exists. var v dag.Vertex = raw - if f, ok := v.(*graphNodeProviderFlat); ok { - v = f.graphNodeProvider - } // Only care about providers pn, ok := v.(GraphNodeProvider) @@ -313,15 +300,7 @@ func providerVertexMap(g *Graph) map[string]dag.Vertex { m := make(map[string]dag.Vertex) for _, v := range g.Vertices() { if pv, ok := v.(GraphNodeProvider); ok { - key := pv.ProviderName() - - // This special case is because the new world view of providers - // is that they should return only their pure name (not the full - // module path with ProviderName). Working towards this future. - if _, ok := v.(*NodeApplyableProvider); ok { - key = providerMapKey(pv.ProviderName(), v) - } - + key := providerMapKey(pv.ProviderName(), v) m[key] = v } } @@ -376,97 +355,13 @@ func (n *graphNodeCloseProvider) DotNode(name string, opts *dag.DotOpts) *dag.Do } } -type graphNodeProvider struct { - ProviderNameValue string -} - -func (n *graphNodeProvider) Name() string { - return fmt.Sprintf("provider.%s", n.ProviderNameValue) -} - -// GraphNodeEvalable impl. -func (n *graphNodeProvider) EvalTree() EvalNode { - return ProviderEvalTree(n.ProviderNameValue, nil) -} - -// GraphNodeDependable impl. -func (n *graphNodeProvider) DependableName() []string { - return []string{n.Name()} -} - -// GraphNodeProvider -func (n *graphNodeProvider) ProviderName() string { - return n.ProviderNameValue -} - -func (n *graphNodeProvider) ProviderConfig() *config.RawConfig { - return nil -} - -// GraphNodeDotter impl. -func (n *graphNodeProvider) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": n.Name(), - "shape": "diamond", - }, - } -} - -// GraphNodeDotterOrigin impl. -func (n *graphNodeProvider) DotOrigin() bool { +// RemovableIfNotTargeted +func (n *graphNodeCloseProvider) RemoveIfNotTargeted() bool { + // We need to add this so that this node will be removed if + // it isn't targeted or a dependency of a target. return true } -// GraphNodeFlattenable impl. -func (n *graphNodeProvider) Flatten(p []string) (dag.Vertex, error) { - return &graphNodeProviderFlat{ - graphNodeProvider: n, - PathValue: p, - }, nil -} - -// Same as graphNodeMissingProvider, but for flattening -type graphNodeProviderFlat struct { - *graphNodeProvider - - PathValue []string -} - -func (n *graphNodeProviderFlat) Name() string { - return fmt.Sprintf( - "%s.%s", modulePrefixStr(n.PathValue), n.graphNodeProvider.Name()) -} - -func (n *graphNodeProviderFlat) Path() []string { - return n.PathValue -} - -func (n *graphNodeProviderFlat) ProviderName() string { - return fmt.Sprintf( - "%s.%s", modulePrefixStr(n.PathValue), - n.graphNodeProvider.ProviderName()) -} - -// GraphNodeDependable impl. -func (n *graphNodeProviderFlat) DependableName() []string { - return []string{n.Name()} -} - -func (n *graphNodeProviderFlat) DependentOn() []string { - var result []string - - // If we're in a module, then depend on all parent providers. Some of - // these may not exist, hence we depend on all of them. - for i := len(n.PathValue); i > 1; i-- { - prefix := modulePrefixStr(n.PathValue[:i-1]) - result = modulePrefixList(n.graphNodeProvider.DependableName(), prefix) - } - - return result -} - // graphNodeProviderConsumerDummy is a struct that never enters the real // graph (though it could to no ill effect). It implements // GraphNodeProviderConsumer and GraphNodeSubpath as a way to force diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_provider_old.go b/vendor/github.com/hashicorp/terraform/terraform/transform_provider_old.go deleted file mode 100644 index 50b4522..0000000 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_provider_old.go +++ /dev/null @@ -1,174 +0,0 @@ -package terraform - -import ( - "fmt" - - "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/dag" -) - -// DisableProviderTransformer "disables" any providers that are only -// depended on by modules. -// -// NOTE: "old" = used by old graph builders, will be removed one day -type DisableProviderTransformerOld struct{} - -func (t *DisableProviderTransformerOld) Transform(g *Graph) error { - // Since we're comparing against edges, we need to make sure we connect - g.ConnectDependents() - - for _, v := range g.Vertices() { - // We only care about providers - pn, ok := v.(GraphNodeProvider) - if !ok || pn.ProviderName() == "" { - continue - } - - // Go through all the up-edges (things that depend on this - // provider) and if any is not a module, then ignore this node. - nonModule := false - for _, sourceRaw := range g.UpEdges(v).List() { - source := sourceRaw.(dag.Vertex) - cn, ok := source.(graphNodeConfig) - if !ok { - nonModule = true - break - } - - if cn.ConfigType() != GraphNodeConfigTypeModule { - nonModule = true - break - } - } - if nonModule { - // We found something that depends on this provider that - // isn't a module, so skip it. - continue - } - - // Disable the provider by replacing it with a "disabled" provider - disabled := &graphNodeDisabledProvider{GraphNodeProvider: pn} - if !g.Replace(v, disabled) { - panic(fmt.Sprintf( - "vertex disappeared from under us: %s", - dag.VertexName(v))) - } - } - - return nil -} - -type graphNodeDisabledProvider struct { - GraphNodeProvider -} - -// GraphNodeEvalable impl. -func (n *graphNodeDisabledProvider) EvalTree() EvalNode { - var resourceConfig *ResourceConfig - - return &EvalOpFilter{ - Ops: []walkOperation{walkInput, walkValidate, walkRefresh, walkPlan, walkApply, walkDestroy}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalInterpolate{ - Config: n.ProviderConfig(), - Output: &resourceConfig, - }, - &EvalBuildProviderConfig{ - Provider: n.ProviderName(), - Config: &resourceConfig, - Output: &resourceConfig, - }, - &EvalSetProviderConfig{ - Provider: n.ProviderName(), - Config: &resourceConfig, - }, - }, - }, - } -} - -// GraphNodeFlattenable impl. -func (n *graphNodeDisabledProvider) Flatten(p []string) (dag.Vertex, error) { - return &graphNodeDisabledProviderFlat{ - graphNodeDisabledProvider: n, - PathValue: p, - }, nil -} - -func (n *graphNodeDisabledProvider) Name() string { - return fmt.Sprintf("%s (disabled)", dag.VertexName(n.GraphNodeProvider)) -} - -// GraphNodeDotter impl. -func (n *graphNodeDisabledProvider) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { - return &dag.DotNode{ - Name: name, - Attrs: map[string]string{ - "label": n.Name(), - "shape": "diamond", - }, - } -} - -// GraphNodeDotterOrigin impl. -func (n *graphNodeDisabledProvider) DotOrigin() bool { - return true -} - -// GraphNodeDependable impl. -func (n *graphNodeDisabledProvider) DependableName() []string { - return []string{"provider." + n.ProviderName()} -} - -// GraphNodeProvider impl. -func (n *graphNodeDisabledProvider) ProviderName() string { - return n.GraphNodeProvider.ProviderName() -} - -// GraphNodeProvider impl. -func (n *graphNodeDisabledProvider) ProviderConfig() *config.RawConfig { - return n.GraphNodeProvider.ProviderConfig() -} - -// Same as graphNodeDisabledProvider, but for flattening -type graphNodeDisabledProviderFlat struct { - *graphNodeDisabledProvider - - PathValue []string -} - -func (n *graphNodeDisabledProviderFlat) Name() string { - return fmt.Sprintf( - "%s.%s", modulePrefixStr(n.PathValue), n.graphNodeDisabledProvider.Name()) -} - -func (n *graphNodeDisabledProviderFlat) Path() []string { - return n.PathValue -} - -func (n *graphNodeDisabledProviderFlat) ProviderName() string { - return fmt.Sprintf( - "%s.%s", modulePrefixStr(n.PathValue), - n.graphNodeDisabledProvider.ProviderName()) -} - -// GraphNodeDependable impl. -func (n *graphNodeDisabledProviderFlat) DependableName() []string { - return modulePrefixList( - n.graphNodeDisabledProvider.DependableName(), - modulePrefixStr(n.PathValue)) -} - -func (n *graphNodeDisabledProviderFlat) DependentOn() []string { - var result []string - - // If we're in a module, then depend on our parent's provider - if len(n.PathValue) > 1 { - prefix := modulePrefixStr(n.PathValue[:len(n.PathValue)-1]) - result = modulePrefixList( - n.graphNodeDisabledProvider.DependableName(), prefix) - } - - return result -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_provisioner.go b/vendor/github.com/hashicorp/terraform/terraform/transform_provisioner.go index 5bd3f65..f49d824 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_provisioner.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_provisioner.go @@ -107,18 +107,9 @@ func (t *MissingProvisionerTransformer) Transform(g *Graph) error { } // Build the vertex - var newV dag.Vertex = &graphNodeProvisioner{ProvisionerNameValue: p} - if len(path) > 0 { - // If we have a path, we do the flattening immediately. This - // is to support new-style graph nodes that are already - // flattened. - if fn, ok := newV.(GraphNodeFlattenable); ok { - var err error - newV, err = fn.Flatten(path) - if err != nil { - return err - } - } + var newV dag.Vertex = &NodeProvisioner{ + NameValue: p, + PathValue: path, } // Add the missing provisioner node to the graph @@ -178,7 +169,8 @@ func provisionerVertexMap(g *Graph) map[string]dag.Vertex { m := make(map[string]dag.Vertex) for _, v := range g.Vertices() { if pv, ok := v.(GraphNodeProvisioner); ok { - m[pv.ProvisionerName()] = v + key := provisionerMapKey(pv.ProvisionerName(), v) + m[key] = v } } @@ -212,50 +204,3 @@ func (n *graphNodeCloseProvisioner) EvalTree() EvalNode { func (n *graphNodeCloseProvisioner) CloseProvisionerName() string { return n.ProvisionerNameValue } - -type graphNodeProvisioner struct { - ProvisionerNameValue string -} - -func (n *graphNodeProvisioner) Name() string { - return fmt.Sprintf("provisioner.%s", n.ProvisionerNameValue) -} - -// GraphNodeEvalable impl. -func (n *graphNodeProvisioner) EvalTree() EvalNode { - return &EvalInitProvisioner{Name: n.ProvisionerNameValue} -} - -func (n *graphNodeProvisioner) ProvisionerName() string { - return n.ProvisionerNameValue -} - -// GraphNodeFlattenable impl. -func (n *graphNodeProvisioner) Flatten(p []string) (dag.Vertex, error) { - return &graphNodeProvisionerFlat{ - graphNodeProvisioner: n, - PathValue: p, - }, nil -} - -// Same as graphNodeMissingProvisioner, but for flattening -type graphNodeProvisionerFlat struct { - *graphNodeProvisioner - - PathValue []string -} - -func (n *graphNodeProvisionerFlat) Name() string { - return fmt.Sprintf( - "%s.%s", modulePrefixStr(n.PathValue), n.graphNodeProvisioner.Name()) -} - -func (n *graphNodeProvisionerFlat) Path() []string { - return n.PathValue -} - -func (n *graphNodeProvisionerFlat) ProvisionerName() string { - return fmt.Sprintf( - "%s.%s", modulePrefixStr(n.PathValue), - n.graphNodeProvisioner.ProvisionerName()) -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_proxy.go b/vendor/github.com/hashicorp/terraform/terraform/transform_proxy.go deleted file mode 100644 index db7b34e..0000000 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_proxy.go +++ /dev/null @@ -1,62 +0,0 @@ -package terraform - -import ( - "github.com/hashicorp/terraform/dag" -) - -// GraphNodeProxy must be implemented by nodes that are proxies. -// -// A node that is a proxy says that anything that depends on this -// node (the proxy), should also copy all the things that the proxy -// itself depends on. Example: -// -// A => proxy => C -// -// Should transform into (two edges): -// -// A => proxy => C -// A => C -// -// The purpose for this is because some transforms only look at direct -// edge connections and the proxy generally isn't meaningful in those -// situations, so we should complete all the edges. -type GraphNodeProxy interface { - Proxy() bool -} - -// ProxyTransformer is a transformer that goes through the graph, finds -// vertices that are marked as proxies, and connects through their -// dependents. See above for what a proxy is. -type ProxyTransformer struct{} - -func (t *ProxyTransformer) Transform(g *Graph) error { - for _, v := range g.Vertices() { - pn, ok := v.(GraphNodeProxy) - if !ok { - continue - } - - // If we don't want to be proxies, don't do it - if !pn.Proxy() { - continue - } - - // Connect all the things that depend on this to things that - // we depend on as the proxy. See docs for GraphNodeProxy for - // a visual explanation. - for _, s := range g.UpEdges(v).List() { - for _, t := range g.DownEdges(v).List() { - g.Connect(GraphProxyEdge{ - Edge: dag.BasicEdge(s, t), - }) - } - } - } - - return nil -} - -// GraphProxyEdge is the edge that is used for proxied edges. -type GraphProxyEdge struct { - dag.Edge -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_reference.go b/vendor/github.com/hashicorp/terraform/terraform/transform_reference.go index 7d8a544..c545235 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_reference.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_reference.go @@ -300,3 +300,22 @@ func ReferenceFromInterpolatedVar(v config.InterpolatedVariable) []string { return nil } } + +func modulePrefixStr(p []string) string { + parts := make([]string, 0, len(p)*2) + for _, p := range p[1:] { + parts = append(parts, "module", p) + } + + return strings.Join(parts, ".") +} + +func modulePrefixList(result []string, prefix string) []string { + if prefix != "" { + for i, v := range result { + result[i] = fmt.Sprintf("%s.%s", prefix, v) + } + } + + return result +} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_resource.go b/vendor/github.com/hashicorp/terraform/terraform/transform_resource.go deleted file mode 100644 index 00628c7..0000000 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_resource.go +++ /dev/null @@ -1,962 +0,0 @@ -package terraform - -import ( - "fmt" - "strings" - - "github.com/hashicorp/terraform/config" - "github.com/hashicorp/terraform/dag" -) - -// ResourceCountTransformerOld is a GraphTransformer that expands the count -// out for a specific resource. -type ResourceCountTransformerOld struct { - Resource *config.Resource - Destroy bool - Targets []ResourceAddress -} - -func (t *ResourceCountTransformerOld) Transform(g *Graph) error { - // Expand the resource count - count, err := t.Resource.Count() - if err != nil { - return err - } - - // Don't allow the count to be negative - if count < 0 { - return fmt.Errorf("negative count: %d", count) - } - - // For each count, build and add the node - nodes := make([]dag.Vertex, 0, count) - for i := 0; i < count; i++ { - // Set the index. If our count is 1 we special case it so that - // we handle the "resource.0" and "resource" boundary properly. - index := i - if count == 1 { - index = -1 - } - - // Save the node for later so we can do connections. Make the - // proper node depending on if we're just a destroy node or if - // were a regular node. - var node dag.Vertex = &graphNodeExpandedResource{ - Index: index, - Resource: t.Resource, - Path: g.Path, - } - if t.Destroy { - node = &graphNodeExpandedResourceDestroy{ - graphNodeExpandedResource: node.(*graphNodeExpandedResource), - } - } - - // Skip nodes if targeting excludes them - if !t.nodeIsTargeted(node) { - continue - } - - // Add the node now - nodes = append(nodes, node) - g.Add(node) - } - - // Make the dependency connections - for _, n := range nodes { - // Connect the dependents. We ignore the return value for missing - // dependents since that should've been caught at a higher level. - g.ConnectDependent(n) - } - - return nil -} - -func (t *ResourceCountTransformerOld) nodeIsTargeted(node dag.Vertex) bool { - // no targets specified, everything stays in the graph - if len(t.Targets) == 0 { - return true - } - addressable, ok := node.(GraphNodeAddressable) - if !ok { - return false - } - - addr := addressable.ResourceAddress() - for _, targetAddr := range t.Targets { - if targetAddr.Equals(addr) { - return true - } - } - return false -} - -type graphNodeExpandedResource struct { - Index int - Resource *config.Resource - Path []string -} - -func (n *graphNodeExpandedResource) Name() string { - if n.Index == -1 { - return n.Resource.Id() - } - - return fmt.Sprintf("%s #%d", n.Resource.Id(), n.Index) -} - -// GraphNodeAddressable impl. -func (n *graphNodeExpandedResource) ResourceAddress() *ResourceAddress { - // We want this to report the logical index properly, so we must undo the - // special case from the expand - index := n.Index - if index == -1 { - index = 0 - } - return &ResourceAddress{ - Path: n.Path[1:], - Index: index, - InstanceType: TypePrimary, - Name: n.Resource.Name, - Type: n.Resource.Type, - Mode: n.Resource.Mode, - } -} - -// graphNodeConfig impl. -func (n *graphNodeExpandedResource) ConfigType() GraphNodeConfigType { - return GraphNodeConfigTypeResource -} - -// GraphNodeDependable impl. -func (n *graphNodeExpandedResource) DependableName() []string { - return []string{ - n.Resource.Id(), - n.stateId(), - } -} - -// GraphNodeDependent impl. -func (n *graphNodeExpandedResource) DependentOn() []string { - configNode := &GraphNodeConfigResource{Resource: n.Resource} - result := configNode.DependentOn() - - // Walk the variables to find any count-specific variables we depend on. - configNode.VarWalk(func(v config.InterpolatedVariable) { - rv, ok := v.(*config.ResourceVariable) - if !ok { - return - } - - // We only want ourselves - if rv.ResourceId() != n.Resource.Id() { - return - } - - // If this isn't a multi-access (which shouldn't be allowed but - // is verified elsewhere), then we depend on the specific count - // of this resource, ignoring ourself (which again should be - // validated elsewhere). - if rv.Index > -1 { - id := fmt.Sprintf("%s.%d", rv.ResourceId(), rv.Index) - if id != n.stateId() && id != n.stateId()+".0" { - result = append(result, id) - } - } - }) - - return result -} - -// GraphNodeProviderConsumer -func (n *graphNodeExpandedResource) ProvidedBy() []string { - return []string{resourceProvider(n.Resource.Type, n.Resource.Provider)} -} - -func (n *graphNodeExpandedResource) StateDependencies() []string { - depsRaw := n.DependentOn() - deps := make([]string, 0, len(depsRaw)) - for _, d := range depsRaw { - // Ignore any variable dependencies - if strings.HasPrefix(d, "var.") { - continue - } - - // This is sad. The dependencies are currently in the format of - // "module.foo.bar" (the full field). This strips the field off. - if strings.HasPrefix(d, "module.") { - parts := strings.SplitN(d, ".", 3) - d = strings.Join(parts[0:2], ".") - } - deps = append(deps, d) - } - - return deps -} - -// GraphNodeEvalable impl. -func (n *graphNodeExpandedResource) EvalTree() EvalNode { - var provider ResourceProvider - var resourceConfig *ResourceConfig - - // Build the resource. If we aren't part of a multi-resource, then - // we still consider ourselves as count index zero. - index := n.Index - if index < 0 { - index = 0 - } - resource := &Resource{ - Name: n.Resource.Name, - Type: n.Resource.Type, - CountIndex: index, - } - - seq := &EvalSequence{Nodes: make([]EvalNode, 0, 5)} - - // Validate the resource - vseq := &EvalSequence{Nodes: make([]EvalNode, 0, 5)} - vseq.Nodes = append(vseq.Nodes, &EvalGetProvider{ - Name: n.ProvidedBy()[0], - Output: &provider, - }) - vseq.Nodes = append(vseq.Nodes, &EvalInterpolate{ - Config: n.Resource.RawConfig.Copy(), - Resource: resource, - Output: &resourceConfig, - }) - vseq.Nodes = append(vseq.Nodes, &EvalValidateResource{ - Provider: &provider, - Config: &resourceConfig, - ResourceName: n.Resource.Name, - ResourceType: n.Resource.Type, - ResourceMode: n.Resource.Mode, - }) - - // Validate all the provisioners - for _, p := range n.Resource.Provisioners { - var provisioner ResourceProvisioner - vseq.Nodes = append(vseq.Nodes, &EvalGetProvisioner{ - Name: p.Type, - Output: &provisioner, - }, &EvalInterpolate{ - Config: p.RawConfig.Copy(), - Resource: resource, - Output: &resourceConfig, - }, &EvalValidateProvisioner{ - Provisioner: &provisioner, - Config: &resourceConfig, - }) - } - - // Add the validation operations - seq.Nodes = append(seq.Nodes, &EvalOpFilter{ - Ops: []walkOperation{walkValidate}, - Node: vseq, - }) - - // Build instance info - info := n.instanceInfo() - seq.Nodes = append(seq.Nodes, &EvalInstanceInfo{Info: info}) - - // Each resource mode has its own lifecycle - switch n.Resource.Mode { - case config.ManagedResourceMode: - seq.Nodes = append( - seq.Nodes, - n.managedResourceEvalNodes(resource, info, resourceConfig)..., - ) - case config.DataResourceMode: - seq.Nodes = append( - seq.Nodes, - n.dataResourceEvalNodes(resource, info, resourceConfig)..., - ) - default: - panic(fmt.Errorf("unsupported resource mode %s", n.Resource.Mode)) - } - - return seq -} - -func (n *graphNodeExpandedResource) managedResourceEvalNodes(resource *Resource, info *InstanceInfo, resourceConfig *ResourceConfig) []EvalNode { - var diff *InstanceDiff - var provider ResourceProvider - var state *InstanceState - - nodes := make([]EvalNode, 0, 5) - - // Refresh the resource - nodes = append(nodes, &EvalOpFilter{ - Ops: []walkOperation{walkRefresh}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalGetProvider{ - Name: n.ProvidedBy()[0], - Output: &provider, - }, - &EvalReadState{ - Name: n.stateId(), - Output: &state, - }, - &EvalRefresh{ - Info: info, - Provider: &provider, - State: &state, - Output: &state, - }, - &EvalWriteState{ - Name: n.stateId(), - ResourceType: n.Resource.Type, - Provider: n.Resource.Provider, - Dependencies: n.StateDependencies(), - State: &state, - }, - }, - }, - }) - - // Diff the resource - nodes = append(nodes, &EvalOpFilter{ - Ops: []walkOperation{walkPlan}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalInterpolate{ - Config: n.Resource.RawConfig.Copy(), - Resource: resource, - Output: &resourceConfig, - }, - &EvalGetProvider{ - Name: n.ProvidedBy()[0], - Output: &provider, - }, - // Re-run validation to catch any errors we missed, e.g. type - // mismatches on computed values. - &EvalValidateResource{ - Provider: &provider, - Config: &resourceConfig, - ResourceName: n.Resource.Name, - ResourceType: n.Resource.Type, - ResourceMode: n.Resource.Mode, - IgnoreWarnings: true, - }, - &EvalReadState{ - Name: n.stateId(), - Output: &state, - }, - &EvalDiff{ - Info: info, - Config: &resourceConfig, - Resource: n.Resource, - Provider: &provider, - State: &state, - OutputDiff: &diff, - OutputState: &state, - }, - &EvalCheckPreventDestroy{ - Resource: n.Resource, - Diff: &diff, - }, - &EvalWriteState{ - Name: n.stateId(), - ResourceType: n.Resource.Type, - Provider: n.Resource.Provider, - Dependencies: n.StateDependencies(), - State: &state, - }, - &EvalWriteDiff{ - Name: n.stateId(), - Diff: &diff, - }, - }, - }, - }) - - // Diff the resource for destruction - nodes = append(nodes, &EvalOpFilter{ - Ops: []walkOperation{walkPlanDestroy}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - &EvalReadState{ - Name: n.stateId(), - Output: &state, - }, - &EvalDiffDestroy{ - Info: info, - State: &state, - Output: &diff, - }, - &EvalCheckPreventDestroy{ - Resource: n.Resource, - Diff: &diff, - }, - &EvalWriteDiff{ - Name: n.stateId(), - Diff: &diff, - }, - }, - }, - }) - - // Apply - var diffApply *InstanceDiff - var err error - var createNew bool - var createBeforeDestroyEnabled bool - nodes = append(nodes, &EvalOpFilter{ - Ops: []walkOperation{walkApply, walkDestroy}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - // Get the saved diff for apply - &EvalReadDiff{ - Name: n.stateId(), - Diff: &diffApply, - }, - - // We don't want to do any destroys - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - if diffApply == nil { - return true, EvalEarlyExitError{} - } - - if diffApply.GetDestroy() && diffApply.GetAttributesLen() == 0 { - return true, EvalEarlyExitError{} - } - - diffApply.SetDestroy(false) - return true, nil - }, - Then: EvalNoop{}, - }, - - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - destroy := false - if diffApply != nil { - destroy = diffApply.GetDestroy() || diffApply.RequiresNew() - } - - createBeforeDestroyEnabled = - n.Resource.Lifecycle.CreateBeforeDestroy && - destroy - - return createBeforeDestroyEnabled, nil - }, - Then: &EvalDeposeState{ - Name: n.stateId(), - }, - }, - - &EvalInterpolate{ - Config: n.Resource.RawConfig.Copy(), - Resource: resource, - Output: &resourceConfig, - }, - &EvalGetProvider{ - Name: n.ProvidedBy()[0], - Output: &provider, - }, - &EvalReadState{ - Name: n.stateId(), - Output: &state, - }, - // Re-run validation to catch any errors we missed, e.g. type - // mismatches on computed values. - &EvalValidateResource{ - Provider: &provider, - Config: &resourceConfig, - ResourceName: n.Resource.Name, - ResourceType: n.Resource.Type, - ResourceMode: n.Resource.Mode, - IgnoreWarnings: true, - }, - &EvalDiff{ - Info: info, - Config: &resourceConfig, - Resource: n.Resource, - Provider: &provider, - Diff: &diffApply, - State: &state, - OutputDiff: &diffApply, - }, - - // Get the saved diff - &EvalReadDiff{ - Name: n.stateId(), - Diff: &diff, - }, - - // Compare the diffs - &EvalCompareDiff{ - Info: info, - One: &diff, - Two: &diffApply, - }, - - &EvalGetProvider{ - Name: n.ProvidedBy()[0], - Output: &provider, - }, - &EvalReadState{ - Name: n.stateId(), - Output: &state, - }, - &EvalApply{ - Info: info, - State: &state, - Diff: &diffApply, - Provider: &provider, - Output: &state, - Error: &err, - CreateNew: &createNew, - }, - &EvalWriteState{ - Name: n.stateId(), - ResourceType: n.Resource.Type, - Provider: n.Resource.Provider, - Dependencies: n.StateDependencies(), - State: &state, - }, - &EvalApplyProvisioners{ - Info: info, - State: &state, - Resource: n.Resource, - InterpResource: resource, - CreateNew: &createNew, - Error: &err, - }, - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - return createBeforeDestroyEnabled && err != nil, nil - }, - Then: &EvalUndeposeState{ - Name: n.stateId(), - State: &state, - }, - Else: &EvalWriteState{ - Name: n.stateId(), - ResourceType: n.Resource.Type, - Provider: n.Resource.Provider, - Dependencies: n.StateDependencies(), - State: &state, - }, - }, - - // We clear the diff out here so that future nodes - // don't see a diff that is already complete. There - // is no longer a diff! - &EvalWriteDiff{ - Name: n.stateId(), - Diff: nil, - }, - - &EvalApplyPost{ - Info: info, - State: &state, - Error: &err, - }, - &EvalUpdateStateHook{}, - }, - }, - }) - - return nodes -} - -func (n *graphNodeExpandedResource) dataResourceEvalNodes(resource *Resource, info *InstanceInfo, resourceConfig *ResourceConfig) []EvalNode { - //var diff *InstanceDiff - var provider ResourceProvider - var config *ResourceConfig - var diff *InstanceDiff - var state *InstanceState - - nodes := make([]EvalNode, 0, 5) - - // Refresh the resource - nodes = append(nodes, &EvalOpFilter{ - Ops: []walkOperation{walkRefresh}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - - // Always destroy the existing state first, since we must - // make sure that values from a previous read will not - // get interpolated if we end up needing to defer our - // loading until apply time. - &EvalWriteState{ - Name: n.stateId(), - ResourceType: n.Resource.Type, - Provider: n.Resource.Provider, - Dependencies: n.StateDependencies(), - State: &state, // state is nil here - }, - - &EvalInterpolate{ - Config: n.Resource.RawConfig.Copy(), - Resource: resource, - Output: &config, - }, - - // The rest of this pass can proceed only if there are no - // computed values in our config. - // (If there are, we'll deal with this during the plan and - // apply phases.) - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - - if config.ComputedKeys != nil && len(config.ComputedKeys) > 0 { - return true, EvalEarlyExitError{} - } - - // If the config explicitly has a depends_on for this - // data source, assume the intention is to prevent - // refreshing ahead of that dependency. - if len(n.Resource.DependsOn) > 0 { - return true, EvalEarlyExitError{} - } - - return true, nil - }, - Then: EvalNoop{}, - }, - - // The remainder of this pass is the same as running - // a "plan" pass immediately followed by an "apply" pass, - // populating the state early so it'll be available to - // provider configurations that need this data during - // refresh/plan. - - &EvalGetProvider{ - Name: n.ProvidedBy()[0], - Output: &provider, - }, - - &EvalReadDataDiff{ - Info: info, - Config: &config, - Provider: &provider, - Output: &diff, - OutputState: &state, - }, - - &EvalReadDataApply{ - Info: info, - Diff: &diff, - Provider: &provider, - Output: &state, - }, - - &EvalWriteState{ - Name: n.stateId(), - ResourceType: n.Resource.Type, - Provider: n.Resource.Provider, - Dependencies: n.StateDependencies(), - State: &state, - }, - - &EvalUpdateStateHook{}, - }, - }, - }) - - // Diff the resource - nodes = append(nodes, &EvalOpFilter{ - Ops: []walkOperation{walkPlan}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - - &EvalReadState{ - Name: n.stateId(), - Output: &state, - }, - - // We need to re-interpolate the config here because some - // of the attributes may have become computed during - // earlier planning, due to other resources having - // "requires new resource" diffs. - &EvalInterpolate{ - Config: n.Resource.RawConfig.Copy(), - Resource: resource, - Output: &config, - }, - - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - computed := config.ComputedKeys != nil && len(config.ComputedKeys) > 0 - - // If the configuration is complete and we - // already have a state then we don't need to - // do any further work during apply, because we - // already populated the state during refresh. - if !computed && state != nil { - return true, EvalEarlyExitError{} - } - - return true, nil - }, - Then: EvalNoop{}, - }, - - &EvalGetProvider{ - Name: n.ProvidedBy()[0], - Output: &provider, - }, - - &EvalReadDataDiff{ - Info: info, - Config: &config, - Provider: &provider, - Output: &diff, - OutputState: &state, - }, - - &EvalWriteState{ - Name: n.stateId(), - ResourceType: n.Resource.Type, - Provider: n.Resource.Provider, - Dependencies: n.StateDependencies(), - State: &state, - }, - - &EvalWriteDiff{ - Name: n.stateId(), - Diff: &diff, - }, - }, - }, - }) - - // Diff the resource for destruction - nodes = append(nodes, &EvalOpFilter{ - Ops: []walkOperation{walkPlanDestroy}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - - &EvalReadState{ - Name: n.stateId(), - Output: &state, - }, - - // Since EvalDiffDestroy doesn't interact with the - // provider at all, we can safely share the same - // implementation for data vs. managed resources. - &EvalDiffDestroy{ - Info: info, - State: &state, - Output: &diff, - }, - - &EvalWriteDiff{ - Name: n.stateId(), - Diff: &diff, - }, - }, - }, - }) - - // Apply - nodes = append(nodes, &EvalOpFilter{ - Ops: []walkOperation{walkApply, walkDestroy}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - // Get the saved diff for apply - &EvalReadDiff{ - Name: n.stateId(), - Diff: &diff, - }, - - // Stop here if we don't actually have a diff - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - if diff == nil { - return true, EvalEarlyExitError{} - } - - if diff.GetAttributesLen() == 0 { - return true, EvalEarlyExitError{} - } - - return true, nil - }, - Then: EvalNoop{}, - }, - - // We need to re-interpolate the config here, rather than - // just using the diff's values directly, because we've - // potentially learned more variable values during the - // apply pass that weren't known when the diff was produced. - &EvalInterpolate{ - Config: n.Resource.RawConfig.Copy(), - Resource: resource, - Output: &config, - }, - - &EvalGetProvider{ - Name: n.ProvidedBy()[0], - Output: &provider, - }, - - // Make a new diff with our newly-interpolated config. - &EvalReadDataDiff{ - Info: info, - Config: &config, - Previous: &diff, - Provider: &provider, - Output: &diff, - }, - - &EvalReadDataApply{ - Info: info, - Diff: &diff, - Provider: &provider, - Output: &state, - }, - - &EvalWriteState{ - Name: n.stateId(), - ResourceType: n.Resource.Type, - Provider: n.Resource.Provider, - Dependencies: n.StateDependencies(), - State: &state, - }, - - // Clear the diff now that we've applied it, so - // later nodes won't see a diff that's now a no-op. - &EvalWriteDiff{ - Name: n.stateId(), - Diff: nil, - }, - - &EvalUpdateStateHook{}, - }, - }, - }) - - return nodes -} - -// instanceInfo is used for EvalTree. -func (n *graphNodeExpandedResource) instanceInfo() *InstanceInfo { - return &InstanceInfo{Id: n.stateId(), Type: n.Resource.Type} -} - -// stateId is the name used for the state key -func (n *graphNodeExpandedResource) stateId() string { - if n.Index == -1 { - return n.Resource.Id() - } - - return fmt.Sprintf("%s.%d", n.Resource.Id(), n.Index) -} - -// GraphNodeStateRepresentative impl. -func (n *graphNodeExpandedResource) StateId() []string { - return []string{n.stateId()} -} - -// graphNodeExpandedResourceDestroy represents an expanded resource that -// is to be destroyed. -type graphNodeExpandedResourceDestroy struct { - *graphNodeExpandedResource -} - -func (n *graphNodeExpandedResourceDestroy) Name() string { - return fmt.Sprintf("%s (destroy)", n.graphNodeExpandedResource.Name()) -} - -// graphNodeConfig impl. -func (n *graphNodeExpandedResourceDestroy) ConfigType() GraphNodeConfigType { - return GraphNodeConfigTypeResource -} - -// GraphNodeEvalable impl. -func (n *graphNodeExpandedResourceDestroy) EvalTree() EvalNode { - info := n.instanceInfo() - info.uniqueExtra = "destroy" - - var diffApply *InstanceDiff - var provider ResourceProvider - var state *InstanceState - var err error - return &EvalOpFilter{ - Ops: []walkOperation{walkApply, walkDestroy}, - Node: &EvalSequence{ - Nodes: []EvalNode{ - // Get the saved diff for apply - &EvalReadDiff{ - Name: n.stateId(), - Diff: &diffApply, - }, - - // Filter the diff so we only get the destroy - &EvalFilterDiff{ - Diff: &diffApply, - Output: &diffApply, - Destroy: true, - }, - - // If we're not destroying, then compare diffs - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - if diffApply != nil && diffApply.GetDestroy() { - return true, nil - } - - return true, EvalEarlyExitError{} - }, - Then: EvalNoop{}, - }, - - // Load the instance info so we have the module path set - &EvalInstanceInfo{Info: info}, - - &EvalGetProvider{ - Name: n.ProvidedBy()[0], - Output: &provider, - }, - &EvalReadState{ - Name: n.stateId(), - Output: &state, - }, - &EvalRequireState{ - State: &state, - }, - // Make sure we handle data sources properly. - &EvalIf{ - If: func(ctx EvalContext) (bool, error) { - if n.Resource.Mode == config.DataResourceMode { - return true, nil - } - - return false, nil - }, - - Then: &EvalReadDataApply{ - Info: info, - Diff: &diffApply, - Provider: &provider, - Output: &state, - }, - Else: &EvalApply{ - Info: info, - State: &state, - Diff: &diffApply, - Provider: &provider, - Output: &state, - Error: &err, - }, - }, - &EvalWriteState{ - Name: n.stateId(), - ResourceType: n.Resource.Type, - Provider: n.Resource.Provider, - Dependencies: n.StateDependencies(), - State: &state, - }, - &EvalApplyPost{ - Info: info, - State: &state, - Error: &err, - }, - }, - }, - } -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_root.go b/vendor/github.com/hashicorp/terraform/terraform/transform_root.go index 7a422b8..aee053d 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_root.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_root.go @@ -36,7 +36,3 @@ type graphNodeRoot struct{} func (n graphNodeRoot) Name() string { return rootNodeName } - -func (n graphNodeRoot) Flatten(p []string) (dag.Vertex, error) { - return n, nil -} diff --git a/vendor/github.com/hashicorp/terraform/terraform/transform_targets.go b/vendor/github.com/hashicorp/terraform/terraform/transform_targets.go index 0ba98ee..225ac4b 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/transform_targets.go +++ b/vendor/github.com/hashicorp/terraform/terraform/transform_targets.go @@ -6,6 +6,15 @@ import ( "github.com/hashicorp/terraform/dag" ) +// GraphNodeTargetable is an interface for graph nodes to implement when they +// need to be told about incoming targets. This is useful for nodes that need +// to respect targets as they dynamically expand. Note that the list of targets +// provided will contain every target provided, and each implementing graph +// node must filter this list to targets considered relevant. +type GraphNodeTargetable interface { + SetTargets([]ResourceAddress) +} + // TargetsTransformer is a GraphTransformer that, when the user specifies a // list of resources to target, limits the graph to only those resources and // their dependencies. @@ -40,7 +49,7 @@ func (t *TargetsTransformer) Transform(g *Graph) error { for _, v := range g.Vertices() { removable := false - if _, ok := v.(GraphNodeAddressable); ok { + if _, ok := v.(GraphNodeResource); ok { removable = true } if vr, ok := v.(RemovableIfNotTargeted); ok { @@ -90,15 +99,6 @@ func (t *TargetsTransformer) selectTargetedNodes( var err error if t.Destroy { deps, err = g.Descendents(v) - - // Select any variables that we depend on in case we need them later for - // interpolating in the count - ancestors, _ := g.Ancestors(v) - for _, a := range ancestors.List() { - if _, ok := a.(*GraphNodeConfigVariableFlat); ok { - deps.Add(a) - } - } } else { deps, err = g.Ancestors(v) } @@ -117,12 +117,12 @@ func (t *TargetsTransformer) selectTargetedNodes( func (t *TargetsTransformer) nodeIsTarget( v dag.Vertex, addrs []ResourceAddress) bool { - r, ok := v.(GraphNodeAddressable) + r, ok := v.(GraphNodeResource) if !ok { return false } - addr := r.ResourceAddress() + addr := r.ResourceAddr() for _, targetAddr := range addrs { if targetAddr.Equals(addr) { return true diff --git a/vendor/github.com/hashicorp/terraform/terraform/version.go b/vendor/github.com/hashicorp/terraform/terraform/version.go index c98c5c4..ada5dcc 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/version.go +++ b/vendor/github.com/hashicorp/terraform/terraform/version.go @@ -7,12 +7,12 @@ import ( ) // The main version number that is being run at the moment. -const Version = "0.8.2" +const Version = "0.9.3" // A pre-release marker for the version. If this is "" (empty string) // then it means that it is a final release. Otherwise, this is a pre-release // such as "dev" (in development), "beta", "rc1", etc. -const VersionPrerelease = "" +const VersionPrerelease = "dev" // SemVersion is an instance of version.Version. This has the secondary // benefit of verifying during tests and init time that our version is a diff --git a/vendor/github.com/hashicorp/terraform/terraform/walkoperation_string.go b/vendor/github.com/hashicorp/terraform/terraform/walkoperation_string.go index 8fb33d7..cbd78dd 100644 --- a/vendor/github.com/hashicorp/terraform/terraform/walkoperation_string.go +++ b/vendor/github.com/hashicorp/terraform/terraform/walkoperation_string.go @@ -1,4 +1,4 @@ -// Code generated by "stringer -type=walkOperation graph_walk_operation.go"; DO NOT EDIT +// Code generated by "stringer -type=walkOperation graph_walk_operation.go"; DO NOT EDIT. package terraform diff --git a/vendor/github.com/hashicorp/yamux/session.go b/vendor/github.com/hashicorp/yamux/session.go index 20369bd..e179818 100644 --- a/vendor/github.com/hashicorp/yamux/session.go +++ b/vendor/github.com/hashicorp/yamux/session.go @@ -46,8 +46,11 @@ type Session struct { pingID uint32 pingLock sync.Mutex - // streams maps a stream id to a stream + // streams maps a stream id to a stream, and inflight has an entry + // for any outgoing stream that has not yet been established. Both are + // protected by streamLock. streams map[uint32]*Stream + inflight map[uint32]struct{} streamLock sync.Mutex // synCh acts like a semaphore. It is sized to the AcceptBacklog which @@ -90,6 +93,7 @@ func newSession(config *Config, conn io.ReadWriteCloser, client bool) *Session { bufRead: bufio.NewReader(conn), pings: make(map[uint32]chan struct{}), streams: make(map[uint32]*Stream), + inflight: make(map[uint32]struct{}), synCh: make(chan struct{}, config.AcceptBacklog), acceptCh: make(chan *Stream, config.AcceptBacklog), sendCh: make(chan sendReady, 64), @@ -153,7 +157,7 @@ func (s *Session) OpenStream() (*Stream, error) { } GET_ID: - // Get and ID, and check for stream exhaustion + // Get an ID, and check for stream exhaustion id := atomic.LoadUint32(&s.nextStreamID) if id >= math.MaxUint32-1 { return nil, ErrStreamsExhausted @@ -166,10 +170,16 @@ GET_ID: stream := newStream(s, id, streamInit) s.streamLock.Lock() s.streams[id] = stream + s.inflight[id] = struct{}{} s.streamLock.Unlock() // Send the window update to create if err := stream.sendWindowUpdate(); err != nil { + select { + case <-s.synCh: + default: + s.logger.Printf("[ERR] yamux: aborted stream open without inflight syn semaphore") + } return nil, err } return stream, nil @@ -580,19 +590,34 @@ func (s *Session) incomingStream(id uint32) error { } // closeStream is used to close a stream once both sides have -// issued a close. +// issued a close. If there was an in-flight SYN and the stream +// was not yet established, then this will give the credit back. func (s *Session) closeStream(id uint32) { s.streamLock.Lock() + if _, ok := s.inflight[id]; ok { + select { + case <-s.synCh: + default: + s.logger.Printf("[ERR] yamux: SYN tracking out of sync") + } + } delete(s.streams, id) s.streamLock.Unlock() } // establishStream is used to mark a stream that was in the // SYN Sent state as established. -func (s *Session) establishStream() { +func (s *Session) establishStream(id uint32) { + s.streamLock.Lock() + if _, ok := s.inflight[id]; ok { + delete(s.inflight, id) + } else { + s.logger.Printf("[ERR] yamux: established stream without inflight SYN (no tracking entry)") + } select { case <-s.synCh: default: - panic("established stream without inflight syn") + s.logger.Printf("[ERR] yamux: established stream without inflight SYN (didn't have semaphore)") } + s.streamLock.Unlock() } diff --git a/vendor/github.com/hashicorp/yamux/spec.md b/vendor/github.com/hashicorp/yamux/spec.md index 419470b..183d797 100644 --- a/vendor/github.com/hashicorp/yamux/spec.md +++ b/vendor/github.com/hashicorp/yamux/spec.md @@ -22,7 +22,7 @@ Each field is described below: ## Version Field -The version field is used for future backwards compatibily. At the +The version field is used for future backward compatibility. At the current time, the field is always set to 0, to indicate the initial version. @@ -96,7 +96,7 @@ Because we are relying on the reliable stream underneath, a connection can begin sending data once the SYN flag is sent. The corresponding ACK does not need to be received. This is particularly well suited for an RPC system where a client wants to open a stream and immediately -fire a request without wiating for the RTT of the ACK. +fire a request without waiting for the RTT of the ACK. This does introduce the possibility of a connection being rejected after data has been sent already. This is a slight semantic difference @@ -138,4 +138,3 @@ provide an error code: * 0x0 Normal termination * 0x1 Protocol error * 0x2 Internal error - diff --git a/vendor/github.com/hashicorp/yamux/stream.go b/vendor/github.com/hashicorp/yamux/stream.go index 4c3242d..d216e28 100644 --- a/vendor/github.com/hashicorp/yamux/stream.go +++ b/vendor/github.com/hashicorp/yamux/stream.go @@ -91,10 +91,13 @@ START: case streamRemoteClose: fallthrough case streamClosed: + s.recvLock.Lock() if s.recvBuf == nil || s.recvBuf.Len() == 0 { + s.recvLock.Unlock() s.stateLock.Unlock() return 0, io.EOF } + s.recvLock.Unlock() case streamReset: s.stateLock.Unlock() return 0, ErrConnectionReset @@ -118,12 +121,17 @@ START: WAIT: var timeout <-chan time.Time + var timer *time.Timer if !s.readDeadline.IsZero() { delay := s.readDeadline.Sub(time.Now()) - timeout = time.After(delay) + timer = time.NewTimer(delay) + timeout = timer.C } select { case <-s.recvNotifyCh: + if timer != nil { + timer.Stop() + } goto START case <-timeout: return 0, ErrTimeout @@ -327,7 +335,7 @@ func (s *Stream) processFlags(flags uint16) error { if s.state == streamSYNSent { s.state = streamEstablished } - s.session.establishStream() + s.session.establishStream(s.id) } if flags&flagFIN == flagFIN { switch s.state { @@ -348,9 +356,6 @@ func (s *Stream) processFlags(flags uint16) error { } } if flags&flagRST == flagRST { - if s.state == streamSYNSent { - s.session.establishStream() - } s.state = streamReset closeStream = true s.notifyWaiting() diff --git a/vendor/github.com/mitchellh/hashstructure/LICENSE b/vendor/github.com/mitchellh/hashstructure/LICENSE new file mode 100644 index 0000000..a3866a2 --- /dev/null +++ b/vendor/github.com/mitchellh/hashstructure/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Mitchell Hashimoto + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/github.com/mitchellh/hashstructure/README.md b/vendor/github.com/mitchellh/hashstructure/README.md new file mode 100644 index 0000000..7d0de5b --- /dev/null +++ b/vendor/github.com/mitchellh/hashstructure/README.md @@ -0,0 +1,61 @@ +# hashstructure + +hashstructure is a Go library for creating a unique hash value +for arbitrary values in Go. + +This can be used to key values in a hash (for use in a map, set, etc.) +that are complex. The most common use case is comparing two values without +sending data across the network, caching values locally (de-dup), and so on. + +## Features + + * Hash any arbitrary Go value, including complex types. + + * Tag a struct field to ignore it and not affect the hash value. + + * Tag a slice type struct field to treat it as a set where ordering + doesn't affect the hash code but the field itself is still taken into + account to create the hash value. + + * Optionally specify a custom hash function to optimize for speed, collision + avoidance for your data set, etc. + +## Installation + +Standard `go get`: + +``` +$ go get github.com/mitchellh/hashstructure +``` + +## Usage & Example + +For usage and examples see the [Godoc](http://godoc.org/github.com/mitchellh/hashstructure). + +A quick code example is shown below: + + + type ComplexStruct struct { + Name string + Age uint + Metadata map[string]interface{} + } + + v := ComplexStruct{ + Name: "mitchellh", + Age: 64, + Metadata: map[string]interface{}{ + "car": true, + "location": "California", + "siblings": []string{"Bob", "John"}, + }, + } + + hash, err := hashstructure.Hash(v, nil) + if err != nil { + panic(err) + } + + fmt.Printf("%d", hash) + // Output: + // 2307517237273902113 diff --git a/vendor/github.com/mitchellh/hashstructure/hashstructure.go b/vendor/github.com/mitchellh/hashstructure/hashstructure.go new file mode 100644 index 0000000..6f586fa --- /dev/null +++ b/vendor/github.com/mitchellh/hashstructure/hashstructure.go @@ -0,0 +1,323 @@ +package hashstructure + +import ( + "encoding/binary" + "fmt" + "hash" + "hash/fnv" + "reflect" +) + +// HashOptions are options that are available for hashing. +type HashOptions struct { + // Hasher is the hash function to use. If this isn't set, it will + // default to FNV. + Hasher hash.Hash64 + + // TagName is the struct tag to look at when hashing the structure. + // By default this is "hash". + TagName string +} + +// Hash returns the hash value of an arbitrary value. +// +// If opts is nil, then default options will be used. See HashOptions +// for the default values. +// +// Notes on the value: +// +// * Unexported fields on structs are ignored and do not affect the +// hash value. +// +// * Adding an exported field to a struct with the zero value will change +// the hash value. +// +// For structs, the hashing can be controlled using tags. For example: +// +// struct { +// Name string +// UUID string `hash:"ignore"` +// } +// +// The available tag values are: +// +// * "ignore" - The field will be ignored and not affect the hash code. +// +// * "set" - The field will be treated as a set, where ordering doesn't +// affect the hash code. This only works for slices. +// +func Hash(v interface{}, opts *HashOptions) (uint64, error) { + // Create default options + if opts == nil { + opts = &HashOptions{} + } + if opts.Hasher == nil { + opts.Hasher = fnv.New64() + } + if opts.TagName == "" { + opts.TagName = "hash" + } + + // Reset the hash + opts.Hasher.Reset() + + // Create our walker and walk the structure + w := &walker{ + h: opts.Hasher, + tag: opts.TagName, + } + return w.visit(reflect.ValueOf(v), nil) +} + +type walker struct { + h hash.Hash64 + tag string +} + +type visitOpts struct { + // Flags are a bitmask of flags to affect behavior of this visit + Flags visitFlag + + // Information about the struct containing this field + Struct interface{} + StructField string +} + +func (w *walker) visit(v reflect.Value, opts *visitOpts) (uint64, error) { + // Loop since these can be wrapped in multiple layers of pointers + // and interfaces. + for { + // If we have an interface, dereference it. We have to do this up + // here because it might be a nil in there and the check below must + // catch that. + if v.Kind() == reflect.Interface { + v = v.Elem() + continue + } + + if v.Kind() == reflect.Ptr { + v = reflect.Indirect(v) + continue + } + + break + } + + // If it is nil, treat it like a zero. + if !v.IsValid() { + var tmp int8 + v = reflect.ValueOf(tmp) + } + + // Binary writing can use raw ints, we have to convert to + // a sized-int, we'll choose the largest... + switch v.Kind() { + case reflect.Int: + v = reflect.ValueOf(int64(v.Int())) + case reflect.Uint: + v = reflect.ValueOf(uint64(v.Uint())) + case reflect.Bool: + var tmp int8 + if v.Bool() { + tmp = 1 + } + v = reflect.ValueOf(tmp) + } + + k := v.Kind() + + // We can shortcut numeric values by directly binary writing them + if k >= reflect.Int && k <= reflect.Complex64 { + // A direct hash calculation + w.h.Reset() + err := binary.Write(w.h, binary.LittleEndian, v.Interface()) + return w.h.Sum64(), err + } + + switch k { + case reflect.Array: + var h uint64 + l := v.Len() + for i := 0; i < l; i++ { + current, err := w.visit(v.Index(i), nil) + if err != nil { + return 0, err + } + + h = hashUpdateOrdered(w.h, h, current) + } + + return h, nil + + case reflect.Map: + var includeMap IncludableMap + if opts != nil && opts.Struct != nil { + if v, ok := opts.Struct.(IncludableMap); ok { + includeMap = v + } + } + + // Build the hash for the map. We do this by XOR-ing all the key + // and value hashes. This makes it deterministic despite ordering. + var h uint64 + for _, k := range v.MapKeys() { + v := v.MapIndex(k) + if includeMap != nil { + incl, err := includeMap.HashIncludeMap( + opts.StructField, k.Interface(), v.Interface()) + if err != nil { + return 0, err + } + if !incl { + continue + } + } + + kh, err := w.visit(k, nil) + if err != nil { + return 0, err + } + vh, err := w.visit(v, nil) + if err != nil { + return 0, err + } + + fieldHash := hashUpdateOrdered(w.h, kh, vh) + h = hashUpdateUnordered(h, fieldHash) + } + + return h, nil + + case reflect.Struct: + var include Includable + parent := v.Interface() + if impl, ok := parent.(Includable); ok { + include = impl + } + + t := v.Type() + h, err := w.visit(reflect.ValueOf(t.Name()), nil) + if err != nil { + return 0, err + } + + l := v.NumField() + for i := 0; i < l; i++ { + if v := v.Field(i); v.CanSet() || t.Field(i).Name != "_" { + var f visitFlag + fieldType := t.Field(i) + if fieldType.PkgPath != "" { + // Unexported + continue + } + + tag := fieldType.Tag.Get(w.tag) + if tag == "ignore" { + // Ignore this field + continue + } + + // Check if we implement includable and check it + if include != nil { + incl, err := include.HashInclude(fieldType.Name, v) + if err != nil { + return 0, err + } + if !incl { + continue + } + } + + switch tag { + case "set": + f |= visitFlagSet + } + + kh, err := w.visit(reflect.ValueOf(fieldType.Name), nil) + if err != nil { + return 0, err + } + + vh, err := w.visit(v, &visitOpts{ + Flags: f, + Struct: parent, + StructField: fieldType.Name, + }) + if err != nil { + return 0, err + } + + fieldHash := hashUpdateOrdered(w.h, kh, vh) + h = hashUpdateUnordered(h, fieldHash) + } + } + + return h, nil + + case reflect.Slice: + // We have two behaviors here. If it isn't a set, then we just + // visit all the elements. If it is a set, then we do a deterministic + // hash code. + var h uint64 + var set bool + if opts != nil { + set = (opts.Flags & visitFlagSet) != 0 + } + l := v.Len() + for i := 0; i < l; i++ { + current, err := w.visit(v.Index(i), nil) + if err != nil { + return 0, err + } + + if set { + h = hashUpdateUnordered(h, current) + } else { + h = hashUpdateOrdered(w.h, h, current) + } + } + + return h, nil + + case reflect.String: + // Directly hash + w.h.Reset() + _, err := w.h.Write([]byte(v.String())) + return w.h.Sum64(), err + + default: + return 0, fmt.Errorf("unknown kind to hash: %s", k) + } + + return 0, nil +} + +func hashUpdateOrdered(h hash.Hash64, a, b uint64) uint64 { + // For ordered updates, use a real hash function + h.Reset() + + // We just panic if the binary writes fail because we are writing + // an int64 which should never be fail-able. + e1 := binary.Write(h, binary.LittleEndian, a) + e2 := binary.Write(h, binary.LittleEndian, b) + if e1 != nil { + panic(e1) + } + if e2 != nil { + panic(e2) + } + + return h.Sum64() +} + +func hashUpdateUnordered(a, b uint64) uint64 { + return a ^ b +} + +// visitFlag is used as a bitmask for affecting visit behavior +type visitFlag uint + +const ( + visitFlagInvalid visitFlag = iota + visitFlagSet = iota << 1 +) diff --git a/vendor/github.com/mitchellh/hashstructure/include.go b/vendor/github.com/mitchellh/hashstructure/include.go new file mode 100644 index 0000000..b6289c0 --- /dev/null +++ b/vendor/github.com/mitchellh/hashstructure/include.go @@ -0,0 +1,15 @@ +package hashstructure + +// Includable is an interface that can optionally be implemented by +// a struct. It will be called for each field in the struct to check whether +// it should be included in the hash. +type Includable interface { + HashInclude(field string, v interface{}) (bool, error) +} + +// IncludableMap is an interface that can optionally be implemented by +// a struct. It will be called when a map-type field is found to ask the +// struct if the map item should be included in the hash. +type IncludableMap interface { + HashIncludeMap(field string, k, v interface{}) (bool, error) +} diff --git a/vendor/github.com/satori/go.uuid/LICENSE b/vendor/github.com/satori/go.uuid/LICENSE index 6a1fb91..488357b 100644 --- a/vendor/github.com/satori/go.uuid/LICENSE +++ b/vendor/github.com/satori/go.uuid/LICENSE @@ -1,4 +1,4 @@ -Copyright (C) 2013-2015 by Maxim Bublis +Copyright (C) 2013-2016 by Maxim Bublis Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/vendor/github.com/satori/go.uuid/README.md b/vendor/github.com/satori/go.uuid/README.md index 48d4937..b6aad1c 100644 --- a/vendor/github.com/satori/go.uuid/README.md +++ b/vendor/github.com/satori/go.uuid/README.md @@ -1,6 +1,7 @@ # UUID package for Go language [![Build Status](https://travis-ci.org/satori/go.uuid.png?branch=master)](https://travis-ci.org/satori/go.uuid) +[![Coverage Status](https://coveralls.io/repos/github/satori/go.uuid/badge.svg?branch=master)](https://coveralls.io/github/satori/go.uuid) [![GoDoc](http://godoc.org/github.com/satori/go.uuid?status.png)](http://godoc.org/github.com/satori/go.uuid) This package provides pure Go implementation of Universally Unique Identifier (UUID). Supported both creation and parsing of UUIDs. @@ -22,9 +23,7 @@ Use the `go` command: ## Requirements -UUID package requires any stable version of Go Programming Language. - -It is tested against following versions of Go: 1.0-1.5 +UUID package requires Go >= 1.2. ## Example @@ -60,7 +59,7 @@ func main() { ## Copyright -Copyright (C) 2013-2015 by Maxim Bublis . +Copyright (C) 2013-2016 by Maxim Bublis . UUID package released under MIT License. See [LICENSE](https://github.com/satori/go.uuid/blob/master/LICENSE) for details. diff --git a/vendor/github.com/satori/go.uuid/uuid.go b/vendor/github.com/satori/go.uuid/uuid.go index 03841d8..295f3fc 100644 --- a/vendor/github.com/satori/go.uuid/uuid.go +++ b/vendor/github.com/satori/go.uuid/uuid.go @@ -127,6 +127,13 @@ func unixTimeFunc() uint64 { // described in RFC 4122. type UUID [16]byte +// NullUUID can be used with the standard sql package to represent a +// UUID value that can be NULL in the database +type NullUUID struct { + UUID UUID + Valid bool +} + // The nil UUID is special form of UUID that is specified to have all // 128 bits set to zero. var Nil = UUID{} @@ -227,30 +234,48 @@ func (u UUID) MarshalText() (text []byte, err error) { // "urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8" func (u *UUID) UnmarshalText(text []byte) (err error) { if len(text) < 32 { - err = fmt.Errorf("uuid: invalid UUID string: %s", text) + err = fmt.Errorf("uuid: UUID string too short: %s", text) return } - if bytes.Equal(text[:9], urnPrefix) { - text = text[9:] - } else if text[0] == '{' { - text = text[1:] + t := text[:] + braced := false + + if bytes.Equal(t[:9], urnPrefix) { + t = t[9:] + } else if t[0] == '{' { + braced = true + t = t[1:] } b := u[:] - for _, byteGroup := range byteGroups { - if text[0] == '-' { - text = text[1:] + for i, byteGroup := range byteGroups { + if i > 0 { + if t[0] != '-' { + err = fmt.Errorf("uuid: invalid string format") + return + } + t = t[1:] + } + + if len(t) < byteGroup { + err = fmt.Errorf("uuid: UUID string too short: %s", text) + return } - _, err = hex.Decode(b[:byteGroup/2], text[:byteGroup]) + if i == 4 && len(t) > byteGroup && + ((braced && t[byteGroup] != '}') || len(t[byteGroup:]) > 1 || !braced) { + err = fmt.Errorf("uuid: UUID string too long: %s", text) + return + } + _, err = hex.Decode(b[:byteGroup/2], t[:byteGroup]) if err != nil { return } - text = text[byteGroup:] + t = t[byteGroup:] b = b[byteGroup/2:] } @@ -298,6 +323,27 @@ func (u *UUID) Scan(src interface{}) error { return fmt.Errorf("uuid: cannot convert %T to UUID", src) } +// Value implements the driver.Valuer interface. +func (u NullUUID) Value() (driver.Value, error) { + if !u.Valid { + return nil, nil + } + // Delegate to UUID Value function + return u.UUID.Value() +} + +// Scan implements the sql.Scanner interface. +func (u *NullUUID) Scan(src interface{}) error { + if src == nil { + u.UUID, u.Valid = Nil, false + return nil + } + + // Delegate to UUID Scan function + u.Valid = true + return u.UUID.Scan(src) +} + // FromBytes returns UUID converted from raw byte slice input. // It will return error if the slice isn't 16 bytes long. func FromBytes(input []byte) (u UUID, err error) { diff --git a/vendor/vendor.json b/vendor/vendor.json index 8d402fa..29b97bf 100644 --- a/vendor/vendor.json +++ b/vendor/vendor.json @@ -6,454 +6,455 @@ "checksumSHA1": "kn+zdUr5TNsoAX8BgjOaWYtMT5U=", "origin": "github.com/hashicorp/terraform/vendor/github.com/apparentlymart/go-cidr/cidr", "path": "github.com/apparentlymart/go-cidr/cidr", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "ViE0bliPiLZR8jWVm/lkDay45C4=", + "checksumSHA1": "FQz+RL20lsUYIpT2CNpYeyKn8Lg=", "path": "github.com/aws/aws-sdk-go/aws", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { "checksumSHA1": "Y9W+4GimK4Fuxq+vyIskVYFRnX4=", "path": "github.com/aws/aws-sdk-go/aws/awserr", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { "checksumSHA1": "yyYr41HZ1Aq0hWc3J5ijXwYEcac=", "path": "github.com/aws/aws-sdk-go/aws/awsutil", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { - "checksumSHA1": "7cQU8tU9hBgsG23XZmko1GePqjQ=", + "checksumSHA1": "iThCyNRL/oQFD9CF2SYgBGl+aww=", "path": "github.com/aws/aws-sdk-go/aws/client", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { "checksumSHA1": "ieAJ+Cvp/PKv1LpUEnUXpc3OI6E=", "path": "github.com/aws/aws-sdk-go/aws/client/metadata", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { - "checksumSHA1": "Fl8vRSCY0MbM04cmiz/0MID+goA=", + "checksumSHA1": "0Gfk83qXYimO87ZoK1lL9+ifWHo=", "path": "github.com/aws/aws-sdk-go/aws/corehandlers", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { - "checksumSHA1": "zu5C95rmCZff6NYZb62lEaT5ibE=", + "checksumSHA1": "P7gt3PNk6bDOoTZ2N9QOonkaGWw=", "path": "github.com/aws/aws-sdk-go/aws/credentials", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { "checksumSHA1": "u3GOAJLmdvbuNUeUEcZSEAOeL/0=", "path": "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { "checksumSHA1": "NUJUTWlc1sV8b7WjfiYc4JZbXl0=", "path": "github.com/aws/aws-sdk-go/aws/credentials/endpointcreds", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { - "checksumSHA1": "4Ipx+5xN0gso+cENC2MHMWmQlR4=", + "checksumSHA1": "6cj/zsRmcxkE1TLS+v910GbQYg0=", "path": "github.com/aws/aws-sdk-go/aws/credentials/stscreds", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { - "checksumSHA1": "lqh3fG7wCochvB4iHAZJuhhEJW0=", + "checksumSHA1": "l2O7P/kvovK2zxKhuFehFNXLk+Q=", "path": "github.com/aws/aws-sdk-go/aws/defaults", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { "checksumSHA1": "/EXbk/z2TWjWc1Hvb4QYs3Wmhb8=", "path": "github.com/aws/aws-sdk-go/aws/ec2metadata", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { - "checksumSHA1": "6R/PDscI/I+Vd/xHdcLUrTz56gc=", + "checksumSHA1": "+yCOae0vRONrO27QiITkGWblOKk=", "path": "github.com/aws/aws-sdk-go/aws/endpoints", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { - "checksumSHA1": "M78rTxU55Qagqr3MYj91im2031E=", + "checksumSHA1": "/L6UweKsmfyHTu01qrFD1ijzSbE=", "path": "github.com/aws/aws-sdk-go/aws/request", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { - "checksumSHA1": "HynfxYegMG8sq9MpFfPu7h1EOvI=", + "checksumSHA1": "5pzA5afgeU1alfACFh8z2CDUMao=", "path": "github.com/aws/aws-sdk-go/aws/session", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { - "checksumSHA1": "0FvPLvkBUpTElfUc/FZtPsJfuV0=", + "checksumSHA1": "SvIsunO8D9MEKbetMENA4WRnyeE=", "path": "github.com/aws/aws-sdk-go/aws/signer/v4", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { "checksumSHA1": "wk7EyvDaHwb5qqoOP/4d3cV0708=", "path": "github.com/aws/aws-sdk-go/private/protocol", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { - "checksumSHA1": "b7xeY3whqyXRFakWvUkP5sifXt8=", + "checksumSHA1": "O6hcK24yI6w7FA+g4Pbr+eQ7pys=", "path": "github.com/aws/aws-sdk-go/private/protocol/json/jsonutil", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { "checksumSHA1": "R00RL5jJXRYq1iiK1+PGvMfvXyM=", "path": "github.com/aws/aws-sdk-go/private/protocol/jsonrpc", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { "checksumSHA1": "ZqY5RWavBLWTo6j9xqdyBEaNFRk=", "path": "github.com/aws/aws-sdk-go/private/protocol/query", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { - "checksumSHA1": "hqTEmgtchF9SwVTW0IQId2eLUKM=", + "checksumSHA1": "Drt1JfLMa0DQEZLWrnMlTWaIcC8=", "path": "github.com/aws/aws-sdk-go/private/protocol/query/queryutil", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { - "checksumSHA1": "szZSLm3BlYkL3vqlZhNAlYk8iwM=", + "checksumSHA1": "VCTh+dEaqqhog5ncy/WTt9+/gFM=", "path": "github.com/aws/aws-sdk-go/private/protocol/rest", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { "checksumSHA1": "ODo+ko8D6unAxZuN1jGzMcN4QCc=", "origin": "github.com/hashicorp/terraform/vendor/github.com/aws/aws-sdk-go/private/protocol/restxml", "path": "github.com/aws/aws-sdk-go/private/protocol/restxml", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "lZ1z4xAbT8euCzKoAsnEYic60VE=", "path": "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { - "checksumSHA1": "Eo9yODN5U99BK0pMzoqnBm7PCrY=", - "path": "github.com/aws/aws-sdk-go/private/waiter", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" - }, - { - "checksumSHA1": "wVhVyL7RjRCOaDuOAVZaDU+QioA=", + "checksumSHA1": "Y4Wg7dxPIU3W1dqN3vnpSLA1ChQ=", "path": "github.com/aws/aws-sdk-go/service/dynamodb", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { - "checksumSHA1": "wRF+8slIqMQxj3esVcZkoZ2fTVU=", + "checksumSHA1": "zeEh/FDxM81fU3X2ftWU2Z++iQg=", "path": "github.com/aws/aws-sdk-go/service/kms", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { - "checksumSHA1": "P4zlIUVrFx5kaMA8OZHsjgNekiM=", + "checksumSHA1": "o7qpn0kxj43Ej/RwfCb9JbzfbfQ=", "origin": "github.com/hashicorp/terraform/vendor/github.com/aws/aws-sdk-go/service/s3", "path": "github.com/aws/aws-sdk-go/service/s3", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "kZvAnT2KFYZBxgUHXzV0kv3KccA=", + "checksumSHA1": "SdsHiTUR9eRarThv/i7y6/rVyF4=", "path": "github.com/aws/aws-sdk-go/service/sts", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { "checksumSHA1": "nqw2Qn5xUklssHTubS5HDvEL9L4=", "origin": "github.com/hashicorp/terraform/vendor/github.com/bgentry/go-netrc/netrc", "path": "github.com/bgentry/go-netrc/netrc", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "FCeEm2BWZV/n4oTy+SGd/k0Ab5c=", + "checksumSHA1": "VvZKmbuBN1QAG699KduTdmSPwA4=", "origin": "github.com/aws/aws-sdk-go/vendor/github.com/go-ini/ini", "path": "github.com/go-ini/ini", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { "checksumSHA1": "cdOCt0Yb+hdErz8NAQqayxPmRsY=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/errwrap", "path": "github.com/hashicorp/errwrap", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "aOWXSbYAdK3PBSMNFiK2ze4lPEc=", + "checksumSHA1": "nsL2kI426RMuq1jw15e7igFqdIY=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/go-getter", "path": "github.com/hashicorp/go-getter", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "9J+kDr29yDrwsdu2ULzewmqGjpA=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/go-getter/helper/url", "path": "github.com/hashicorp/go-getter/helper/url", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "lrSl49G23l6NhfilxPM0XFs5rZo=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/go-multierror", "path": "github.com/hashicorp/go-multierror", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "htXEADpvjCVuFpDEERXcZj1kqiI=", + "checksumSHA1": "b0nQutPMJHeUmz4SjpreotAo6Yk=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/go-plugin", "path": "github.com/hashicorp/go-plugin", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "85XUnluYJL7F55ptcwdmN8eSOsk=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/go-uuid", "path": "github.com/hashicorp/go-uuid", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "9nNGCY0dWyRDEm7xb57BzV0AKeA=", + "checksumSHA1": "EcZfls6vcqjasWV/nBlu+C+EFmc=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/go-version", "path": "github.com/hashicorp/go-version", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "8OPDk+bKyRGJoKcS4QNw9F7dpE8=", + "checksumSHA1": "Ok3Csn6Voou7pQT6Dv2mkwpqFtw=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/hcl", "path": "github.com/hashicorp/hcl", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "XQmjDva9JCGGkIecOgwtBEMCJhU=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/hcl/hcl/ast", "path": "github.com/hashicorp/hcl/hcl/ast", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "vF6LLywGDoAaccTcAGrcY7mYvZc=", + "checksumSHA1": "MGYzZActhzSs9AnCx3wrEYVbKFg=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/hcl/hcl/parser", "path": "github.com/hashicorp/hcl/hcl/parser", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "z6wdP4mRw4GVjShkNHDaOWkbxS0=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/hcl/hcl/scanner", "path": "github.com/hashicorp/hcl/hcl/scanner", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "oS3SCN9Wd6D8/LG0Yx1fu84a7gI=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/hcl/hcl/strconv", "path": "github.com/hashicorp/hcl/hcl/strconv", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "c6yprzj06ASwCo18TtbbNNBHljA=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/hcl/hcl/token", "path": "github.com/hashicorp/hcl/hcl/token", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "138aCV5n8n7tkGYMsMVQQnnLq+0=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/hcl/json/parser", "path": "github.com/hashicorp/hcl/json/parser", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "YdvFsNOMSWMLnY6fcliWQa0O5Fw=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/hcl/json/scanner", "path": "github.com/hashicorp/hcl/json/scanner", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "fNlXQCQEnb+B3k5UDL/r15xtSJY=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/hcl/json/token", "path": "github.com/hashicorp/hcl/json/token", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "2Nrl/YKrmowkRgCDLhA6UTFgYEY=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/hil", "path": "github.com/hashicorp/hil", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "oZ2a2x9qyHqvqJdv/Du3LGeaFdA=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/hil/ast", "path": "github.com/hashicorp/hil/ast", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "P5PZ3k7SmqWmxgJ8Q0gLzeNpGhE=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/hil/parser", "path": "github.com/hashicorp/hil/parser", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "DC1k5kOua4oFqmo+JRt0YzfP44o=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/hil/scanner", "path": "github.com/hashicorp/hil/scanner", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "lCG3a+my0Mw6kskZH9000DfZb+M=", + "checksumSHA1": "+D/IlTDpRyf73ZzkL9KQlb/Nn3Y=", "path": "github.com/hashicorp/terraform/config", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "CrKVfaeQDBtO4R7wXPU87BN4EMc=", + "checksumSHA1": "YiREjXkb7CDMZuUmkPGK0yySe8A=", "path": "github.com/hashicorp/terraform/config/module", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "E9yooTQGxP6k9KUAD9d80EgWyCo=", + "checksumSHA1": "sXtlkvFMY+O7eHwE9LvIBDYTxYc=", "path": "github.com/hashicorp/terraform/dag", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "uUQ2PNojZb7ya+QrwTb18ObYX/M=", + "checksumSHA1": "qmpOWfKZx+46bDvhzZePh+hJ4jo=", "path": "github.com/hashicorp/terraform/flatmap", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "go1fw84tUwRRBgwOKrMtWPtPCno=", + "checksumSHA1": "Vbo55GDzPgG/L/+W2pcvDhxrPZc=", "path": "github.com/hashicorp/terraform/helper/experiment", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "BmIPKTr0zDutSJdyq7pYXrK1I3E=", "path": "github.com/hashicorp/terraform/helper/hashcode", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "B267stWNQd0/pBTXHfI/tJsxzfc=", "path": "github.com/hashicorp/terraform/helper/hilmapstructure", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "k7aKv4a5bmAkG66ILU3xDbgPQUU=", + "checksumSHA1": "OUsys9XFVNSo2cbpJSidOTJx6vs=", "path": "github.com/hashicorp/terraform/helper/schema", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "oLui7dYxhzfAczwwdNZDm4tzHtk=", "path": "github.com/hashicorp/terraform/helper/shadow", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "z59GrKQVRxwgvc1sQA6Yh2F/q18=", + "checksumSHA1": "6AA7ZAzswfl7SOzleP6e6he0lq4=", "path": "github.com/hashicorp/terraform/plugin", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "gZBchnebX0CijSTnpGG6ZjJDsTg=", + "checksumSHA1": "GDWHN+gZfEnmkO/PQ3I8mBekIKw=", "path": "github.com/hashicorp/terraform/terraform", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "Gm2k+46HxKqsjI8lCWBp/jRaPrM=", + "checksumSHA1": "ZhK6IO2XN81Y+3RAjTcVm1Ic7oU=", "origin": "github.com/hashicorp/terraform/vendor/github.com/hashicorp/yamux", "path": "github.com/hashicorp/yamux", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "0ZrwvB6KoGPj2PoDNSEJwxQ6Mog=", "origin": "github.com/aws/aws-sdk-go/vendor/github.com/jmespath/go-jmespath", "path": "github.com/jmespath/go-jmespath", - "revision": "9a0c8a57d9bb717d481bc91f995df80d9bb9238c", - "revisionTime": "2016-12-22T21:31:12Z" + "revision": "4c307b6c988d40b9601a86768b29c28e8fb033eb", + "revisionTime": "2017-04-06T18:18:18Z" }, { "checksumSHA1": "guxbLo8KHHBeM0rzou4OTzzpDNs=", "origin": "github.com/hashicorp/terraform/vendor/github.com/mitchellh/copystructure", "path": "github.com/mitchellh/copystructure", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "V/quM7+em2ByJbWBLOsEwnY3j/Q=", "origin": "github.com/hashicorp/terraform/vendor/github.com/mitchellh/go-homedir", "path": "github.com/mitchellh/go-homedir", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" + }, + { + "checksumSHA1": "xyoJKalfQwTUN1qzZGQKWYAwl0A=", + "origin": "github.com/hashicorp/terraform/vendor/github.com/mitchellh/hashstructure", + "path": "github.com/mitchellh/hashstructure", + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "4Js6Jlu93Wa0o6Kjt393L9Z7diE=", "origin": "github.com/hashicorp/terraform/vendor/github.com/mitchellh/mapstructure", "path": "github.com/mitchellh/mapstructure", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { "checksumSHA1": "vBpuqNfSTZcAR/0tP8tNYacySGs=", "origin": "github.com/hashicorp/terraform/vendor/github.com/mitchellh/reflectwalk", "path": "github.com/mitchellh/reflectwalk", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" }, { - "checksumSHA1": "TvF3ym5sZVNqGlUOS9HgOIl/sZM=", + "checksumSHA1": "zmC8/3V4ls53DJlNTKDZwPSC/dA=", "origin": "github.com/hashicorp/terraform/vendor/github.com/satori/go.uuid", "path": "github.com/satori/go.uuid", - "revision": "dd2c6da4f6226b5ccd0601a15bba197fc223b1ec", - "revisionTime": "2016-12-21T20:03:36Z" + "revision": "84fca9ec83ce4bccb6d68785a98c0da9a57c4c94", + "revisionTime": "2017-04-07T12:16:13Z" } ], - "rootPath": "github.com/sspinc/terraform-credstash" + "rootPath": "github.com/sspinc/terraform-provider-credstash" }