diff --git a/.circleci/config.yml b/.circleci/config.yml index db8013bd3..3990953fb 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -7,11 +7,11 @@ version: 2.1 executors: golang: docker: - - image: circleci/golang:1.13 + - image: circleci/golang:1.15 resource_class: medium+ darwin: macos: - xcode: "9.0" + xcode: "12.0.0" commands: install-go-run-tests-unix: @@ -67,7 +67,7 @@ jobs: steps: - install-go-run-tests-unix: GOOS: darwin - GOVERSION: "1.13" + GOVERSION: "1.15" - codecov/upload: file: coverage.txt test-windows: @@ -76,7 +76,7 @@ jobs: shell: bash.exe steps: - install-go-run-tests-windows: - GOVERSION: "1.13" + GOVERSION: "1.15" - codecov/upload: file: coverage.txt check-lint: diff --git a/.codecov.yml b/.codecov.yml index c06f98c05..7a5e9710a 100644 --- a/.codecov.yml +++ b/.codecov.yml @@ -13,5 +13,6 @@ coverage: project: off patch: off -ignore: # ignore hcl2spec generated code for coverage - - "**/*.hcl2spec.go" \ No newline at end of file +ignore: # ignore hcl2spec generated code for coverage and mocks + - "**/*.hcl2spec.go" + - "**/*_mock.go" \ No newline at end of file diff --git a/.gitattributes b/.gitattributes index 6c076338a..0eb67ecaf 100644 --- a/.gitattributes +++ b/.gitattributes @@ -6,6 +6,7 @@ *.mdx text eol=lf *.ps1 text eol=lf *.hcl text eol=lf +*.txt text eol=lf go.mod text eol=lf go.sum text eol=lf common/test-fixtures/root/* eol=lf diff --git a/CHANGELOG.md b/CHANGELOG.md index c8450e990..7349bc856 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,116 @@ -## 1.6.3 (Upcoming) +## 1.6.5 (Upcoming) + +### BUG FIXES: + +* core/hcl2: Packer HCL's "Coalesce" function now behaves same way as + Terraform's. [GH-10016] +* core/HCL: Hide sensitive variables from output. [GH-10031] +* core: Fix artifact handling so that input artifacts are properly preserved in + postprocessors that don't modify artifacts. [GH-9996] +* core: Fix pathing in cd_files to copy proper directory tree when user + provided absolute paths. [GH-10022] +* provisioner/ansible: Ansible galaxy no longer forces use of collections in v1 + files. [GH-10010] + +### IMPROVEMENTS: + +* builder/oracle-oci: New option to specify image compartment separate from + build compartment. [GH-10040] +* builder/oracle-oci: New option to specify boot volume size. [GH-10017] + +## 1.6.4 (September 30, 2020) + +### BUG FIXES: +* builder/amazon: Fix authentication issue when using instance profiles or + assumed roles for loading session-derived credentials. [GH-10007] +* builder/azure: Fix crash when using `azure_tag` or `azure_tags` configuration + options. [GH-10014] +* builder/qemu: Ensure `qemu_img_args` are honored during the disk convert + step. [GH-10001] + + ## 1.6.3 (September 25, 2020) + +### IMPROVEMENTS: +* builder/amazon: Add `pause_before_ssm` option to pause for some time before + establishing a Session Manager session; defaults to 10s. [GH-9988] +* builder/amazon: Implement assume_role option that matches Terraform behavior. + [GH-9981] +* builder/azure: Support publishing to a Shared Image Gallery with a different + subscription id [GH-9875] +* builder/openstack: Add `external_source_image_url` and + `external_source_image_format` to support building images from external + source URLs. [GH-9992] +* builder/openstack: Include API requests and responses as part of the debug + log output. [GH-9972] +* builder/oracle-oci: Add `create_vnic_details` option for launch details. + [GH-9856] +* builder/oracle-oci: Allow freeform and defined tags to be added to an instance. + [GH-9802] +* builder/proxmox: Add `io_thread` option for supporting io threads when using + a `virtio-scsi-single` controller with a `scsi` or `virtio` disk type. + [GH-9969] +* builder/proxmox: Add ability to specify interfaces for http_directory and VM. + [GH-9874] +* builder/proxmox: Allow the mounting of multiple ISOs via the `cd_drive` + option. [GH-9653] +* builder/proxmox: Fix boot command special keys. [GH-9885] +* builder/qemu: Add `qemu_img_args` option to set special cli flags for calls + to qemu-img [GH-9956] +* builder/qemu: Add `skip_resize_disk` option to skip the resizing of QCOW2 + images. [GH-9896] [GH-9860] +* builder/qemu: Skip qemu-img convert on MacOS to prevent the creation of + corrupt images [QEMU + #1776920](https://bugs.launchpad.net/qemu/+bug/1776920) [GH-9949] +* builder/scaleway: Change default boottype to local. [GH-9853] +* builder/scaleway: Update scaleway to use non-deprecated sdk. [GH-9902] +* builder/vmware: Add `vnc_over_websocket` to allow the sending of a + `boot_command` to hosts running ESXi 6.7 and above. [GH-9938] +* builder/vmware: Allow user to set vmware tools source path. [GH-9983] +* builder/vsphere-clone: Add ability to set `mac_address` [GH-9930] +* builder/vsphere-clone: Add floppy_files, cd_files, and iso_paths options. + [GH-9963] +* builder/vsphere-iso: Add NVMe controller support. [GH-9880] +* builder/vsphere: Look for a default resource pool when root resource pool is + not found. [GH-9809] +* core: Add support for running cygwin/msys2 based cd/iso creation tool + [GH-9954] +* core: New `cd_files` option to mount iso for modern OSes which don't support + floppies. [GH-9796] [GH-9919] [GH-9928] [GH-9932] [GH-9941] +* HCL2: When the type of a variable is not known evaluate setting as a literal + string instead of a variable name. [GH-9863] +* post-processor/vagrant: Support the use of template variables within + Vagrantfile templates. [GH-9923] +* post-processor/yandex-import: Allow custom API endpoint. [GH-9850] +* provisioner/ansible: Add support for Ansible Galaxy Collections. [GH-9903] + +### BUG FIXES: +* builder/amazon-ebs: Fix issue where retrying on invalid IAM instance profile + error was creating multiple spot instances. [GH-9946] +* builder/amazon-ebssurrogate: Fix issue where builder defaults to AWS managed + key even when custom `kms_key_id` is set. [GH-9959] +* builder/amazon: Update ssm_driver log polling logic to prevent infinite loops + when SSM driver is terminated outside of Packer. [GH-9991] +* builder/azure: Fix crash when using HCL2 configs. [GH-9984] [GH-9985] +* builder/qemu: Fix hardcoded lowerbound causing negative ports [GH-9905] +* builder/qemu: Skip compaction when backing file is used. [GH-9918] +* builder/scaleway: Add pre validate step to prevent the creation of multiple + images with the same name. [GH-9840] +* builder/vmware-iso: Prevent the use of reserved SCSI ID 0:7 when attaching + multiple disks. [GH-9940] +* builder/vsphere: Fix overly strict iso_path validation regex. [GH-9855] +* command/console: Prevent failure when there are unknown vars. [GH-9864] +* command/inspect: Allow unset variables in HCL2 and JSON. [GH-9832] +* core: Prevent the UI progressbar from hanging and crashing when there is no + TTY available. [GH-9974] +* core: Use $APPDATA over $HOME on Windows hosts when determining homedir. + [GH-9830] +* post-processor/digitalocean-import: Fix crash caused by empty artifact.Files + slice. [GH-9857] +* post-processor/yandex-export: Check for error after runner completes. + [GH-9925] +* post-processor/yandex-export: Set metadata key to expected value on error. + [GH-9849] +* post-processor/yandex-import: Fix S3 URL construct process. [GH-9931] ## 1.6.2 (August 28, 2020) diff --git a/builder/amazon/chroot/builder.hcl2spec.go b/builder/amazon/chroot/builder.hcl2spec.go index 9f87fb150..4a2647a34 100644 --- a/builder/amazon/chroot/builder.hcl2spec.go +++ b/builder/amazon/chroot/builder.hcl2spec.go @@ -41,7 +41,9 @@ type FlatConfig struct { SnapshotUsers []string `mapstructure:"snapshot_users" required:"false" cty:"snapshot_users" hcl:"snapshot_users"` SnapshotGroups []string `mapstructure:"snapshot_groups" required:"false" cty:"snapshot_groups" hcl:"snapshot_groups"` AccessKey *string `mapstructure:"access_key" required:"true" cty:"access_key" hcl:"access_key"` + AssumeRole *common.FlatAssumeRoleConfig `mapstructure:"assume_role" required:"false" cty:"assume_role" hcl:"assume_role"` CustomEndpointEc2 *string `mapstructure:"custom_endpoint_ec2" required:"false" cty:"custom_endpoint_ec2" hcl:"custom_endpoint_ec2"` + CredsFilename *string `mapstructure:"shared_credentials_file" required:"false" cty:"shared_credentials_file" hcl:"shared_credentials_file"` DecodeAuthZMessages *bool `mapstructure:"decode_authorization_messages" required:"false" cty:"decode_authorization_messages" hcl:"decode_authorization_messages"` InsecureSkipTLSVerify *bool `mapstructure:"insecure_skip_tls_verify" required:"false" cty:"insecure_skip_tls_verify" hcl:"insecure_skip_tls_verify"` MaxRetries *int `mapstructure:"max_retries" required:"false" cty:"max_retries" hcl:"max_retries"` @@ -50,6 +52,7 @@ type FlatConfig struct { RawRegion *string `mapstructure:"region" required:"true" cty:"region" hcl:"region"` SecretKey *string `mapstructure:"secret_key" required:"true" cty:"secret_key" hcl:"secret_key"` SkipMetadataApiCheck *bool `mapstructure:"skip_metadata_api_check" cty:"skip_metadata_api_check" hcl:"skip_metadata_api_check"` + SkipCredsValidation *bool `mapstructure:"skip_credential_validation" cty:"skip_credential_validation" hcl:"skip_credential_validation"` Token *string `mapstructure:"token" required:"false" cty:"token" hcl:"token"` VaultAWSEngine *common.FlatVaultAWSEngineOptions `mapstructure:"vault_aws_engine" required:"false" cty:"vault_aws_engine" hcl:"vault_aws_engine"` PollingConfig *common.FlatAWSPollingConfig `mapstructure:"aws_polling" required:"false" cty:"aws_polling" hcl:"aws_polling"` @@ -117,7 +120,9 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "snapshot_users": &hcldec.AttrSpec{Name: "snapshot_users", Type: cty.List(cty.String), Required: false}, "snapshot_groups": &hcldec.AttrSpec{Name: "snapshot_groups", Type: cty.List(cty.String), Required: false}, "access_key": &hcldec.AttrSpec{Name: "access_key", Type: cty.String, Required: false}, + "assume_role": &hcldec.BlockSpec{TypeName: "assume_role", Nested: hcldec.ObjectSpec((*common.FlatAssumeRoleConfig)(nil).HCL2Spec())}, "custom_endpoint_ec2": &hcldec.AttrSpec{Name: "custom_endpoint_ec2", Type: cty.String, Required: false}, + "shared_credentials_file": &hcldec.AttrSpec{Name: "shared_credentials_file", Type: cty.String, Required: false}, "decode_authorization_messages": &hcldec.AttrSpec{Name: "decode_authorization_messages", Type: cty.Bool, Required: false}, "insecure_skip_tls_verify": &hcldec.AttrSpec{Name: "insecure_skip_tls_verify", Type: cty.Bool, Required: false}, "max_retries": &hcldec.AttrSpec{Name: "max_retries", Type: cty.Number, Required: false}, @@ -126,6 +131,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "region": &hcldec.AttrSpec{Name: "region", Type: cty.String, Required: false}, "secret_key": &hcldec.AttrSpec{Name: "secret_key", Type: cty.String, Required: false}, "skip_metadata_api_check": &hcldec.AttrSpec{Name: "skip_metadata_api_check", Type: cty.Bool, Required: false}, + "skip_credential_validation": &hcldec.AttrSpec{Name: "skip_credential_validation", Type: cty.Bool, Required: false}, "token": &hcldec.AttrSpec{Name: "token", Type: cty.String, Required: false}, "vault_aws_engine": &hcldec.BlockSpec{TypeName: "vault_aws_engine", Nested: hcldec.ObjectSpec((*common.FlatVaultAWSEngineOptions)(nil).HCL2Spec())}, "aws_polling": &hcldec.BlockSpec{TypeName: "aws_polling", Nested: hcldec.ObjectSpec((*common.FlatAWSPollingConfig)(nil).HCL2Spec())}, diff --git a/builder/amazon/common/access_config.go b/builder/amazon/common/access_config.go index 9b645ada3..6ebd372d3 100644 --- a/builder/amazon/common/access_config.go +++ b/builder/amazon/common/access_config.go @@ -1,5 +1,5 @@ //go:generate struct-markdown -//go:generate mapstructure-to-hcl2 -type VaultAWSEngineOptions +//go:generate mapstructure-to-hcl2 -type VaultAWSEngineOptions,AssumeRoleConfig package common @@ -11,15 +11,67 @@ import ( "strings" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/credentials" + awsCredentials "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/ec2/ec2iface" + awsbase "github.com/hashicorp/aws-sdk-go-base" cleanhttp "github.com/hashicorp/go-cleanhttp" "github.com/hashicorp/packer/template/interpolate" vaultapi "github.com/hashicorp/vault/api" ) +// AssumeRoleConfig lets users set configuration options for assuming a special +// role when executing Packer. +// +// Usage example: +// +// HCL config example: +// +// ```HCL +// source "example" "amazon-ebs"{ +// assume_role { +// role_arn = "arn:aws:iam::ACCOUNT_ID:role/ROLE_NAME" +// session_name = "SESSION_NAME" +// external_id = "EXTERNAL_ID" +// } +// } +// ``` +// +// JSON config example: +// +// ```json +// builder{ +// "type": "amazon-ebs", +// "assume_role": { +// "role_arn" : "arn:aws:iam::ACCOUNT_ID:role/ROLE_NAME", +// "session_name": "SESSION_NAME", +// "external_id" : "EXTERNAL_ID" +// } +// } +// ``` +type AssumeRoleConfig struct { + // Amazon Resource Name (ARN) of the IAM Role to assume. + AssumeRoleARN string `mapstructure:"role_arn" required:"false"` + // Number of seconds to restrict the assume role session duration. + AssumeRoleDurationSeconds int `mapstructure:"duration_seconds" required:"false"` + // The external ID to use when assuming the role. If omitted, no external + // ID is passed to the AssumeRole call. + AssumeRoleExternalID string `mapstructure:"external_id" required:"false"` + // IAM Policy JSON describing further restricting permissions for the IAM + // Role being assumed. + AssumeRolePolicy string `mapstructure:"policy" required:"false"` + // Set of Amazon Resource Names (ARNs) of IAM Policies describing further + // restricting permissions for the IAM Role being + AssumeRolePolicyARNs []string `mapstructure:"policy_arns" required:"false"` + // Session name to use when assuming the role. + AssumeRoleSessionName string `mapstructure:"session_name" required:"false"` + // Map of assume role session tags. + AssumeRoleTags map[string]string `mapstructure:"tags" required:"false"` + // Set of assume role session tag keys to pass to any subsequent sessions. + AssumeRoleTransitiveTagKeys []string `mapstructure:"transitive_tag_keys" required:"false"` +} + type VaultAWSEngineOptions struct { Name string `mapstructure:"name"` RoleARN string `mapstructure:"role_arn"` @@ -48,10 +100,17 @@ type AccessConfig struct { // is not required if you are using `use_vault_aws_engine` for // authentication instead. AccessKey string `mapstructure:"access_key" required:"true"` + // If provided with a role ARN, Packer will attempt to assume this role + // using the supplied credentials. See + // [AssumeRoleConfig](#assume-role-configuration) below for more + // details on all of the options available, and for a usage example. + AssumeRole AssumeRoleConfig `mapstructure:"assume_role" required:"false"` // This option is useful if you use a cloud // provider whose API is compatible with aws EC2. Specify another endpoint // like this https://ec2.custom.endpoint.com. CustomEndpointEc2 string `mapstructure:"custom_endpoint_ec2" required:"false"` + // Path to a credentials file to load credentials from + CredsFilename string `mapstructure:"shared_credentials_file" required:"false"` // Enable automatic decoding of any encoded authorization (error) messages // using the `sts:DecodeAuthorizationMessage` API. Note: requires that the // effective user/role have permissions to `sts:DecodeAuthorizationMessage` @@ -86,6 +145,8 @@ type AccessConfig struct { // validation of the ami_regions configuration option. Default false. SkipValidation bool `mapstructure:"skip_region_validation" required:"false"` SkipMetadataApiCheck bool `mapstructure:"skip_metadata_api_check"` + // Set to true if you want to skip validating AWS credentials before runtime. + SkipCredsValidation bool `mapstructure:"skip_credential_validation"` // The access token to use. This is different from the // access key and secret key. If you're not sure what this is, then you // probably don't need it. This will also be read from the AWS_SESSION_TOKEN @@ -152,16 +213,13 @@ func (c *AccessConfig) Session() (*session.Session, error) { return c.session, nil } + // Create new AWS config config := aws.NewConfig().WithCredentialsChainVerboseErrors(true) if c.MaxRetries > 0 { config = config.WithMaxRetries(c.MaxRetries) } - staticCreds := credentials.NewStaticCredentials(c.AccessKey, c.SecretKey, c.Token) - if _, err := staticCreds.Get(); err != credentials.ErrStaticCredentialsEmpty { - config.WithCredentials(staticCreds) - } - + // Set AWS config defaults. if c.RawRegion != "" { config = config.WithRegion(c.RawRegion) } @@ -179,6 +237,16 @@ func (c *AccessConfig) Session() (*session.Session, error) { } transport.Proxy = http.ProxyFromEnvironment + // Figure out which possible credential providers are valid; test that we + // can get credentials via the selected providers, and set the providers in + // the config. + creds, err := c.GetCredentials(config) + if err != nil { + return nil, err + } + config.WithCredentials(creds) + + // Create session options based on our AWS config opts := session.Options{ SharedConfigState: session.SharedConfigEnable, Config: *config, @@ -204,9 +272,7 @@ func (c *AccessConfig) Session() (*session.Session, error) { cp, err := c.session.Config.Credentials.Get() if IsAWSErr(err, "NoCredentialProviders", "") { - return nil, fmt.Errorf("No valid credential sources found for AWS Builder. " + - "Please see https://www.packer.io/docs/builders/amazon#specifying-amazon-credentials " + - "for more information on providing credentials for the AWS Builder.") + return nil, c.NewNoValidCredentialSourcesError(err) } if err != nil { @@ -237,6 +303,42 @@ func (c *AccessConfig) IsChinaCloud() bool { return strings.HasPrefix(c.SessionRegion(), "cn-") } +// GetCredentials gets credentials from the environment, shared credentials, +// the session (which may include a credential process), or ECS/EC2 metadata +// endpoints. GetCredentials also validates the credentials and the ability to +// assume a role or will return an error if unsuccessful. +func (c *AccessConfig) GetCredentials(config *aws.Config) (*awsCredentials.Credentials, error) { + // Reload values into the config used by the Packer-Terraform shared SDK + awsbaseConfig := &awsbase.Config{ + AccessKey: c.AccessKey, + AssumeRoleARN: c.AssumeRole.AssumeRoleARN, + AssumeRoleDurationSeconds: c.AssumeRole.AssumeRoleDurationSeconds, + AssumeRoleExternalID: c.AssumeRole.AssumeRoleExternalID, + AssumeRolePolicy: c.AssumeRole.AssumeRolePolicy, + AssumeRolePolicyARNs: c.AssumeRole.AssumeRolePolicyARNs, + AssumeRoleSessionName: c.AssumeRole.AssumeRoleSessionName, + AssumeRoleTags: c.AssumeRole.AssumeRoleTags, + AssumeRoleTransitiveTagKeys: c.AssumeRole.AssumeRoleTransitiveTagKeys, + CredsFilename: c.CredsFilename, + DebugLogging: false, + // TODO: implement for Packer + // IamEndpoint: c.Endpoints["iam"], + Insecure: c.InsecureSkipTLSVerify, + MaxRetries: c.MaxRetries, + Profile: c.ProfileName, + Region: c.RawRegion, + SecretKey: c.SecretKey, + SkipCredsValidation: c.SkipCredsValidation, + SkipMetadataApiCheck: c.SkipMetadataApiCheck, + // TODO: implement for Packer + // SkipRequestingAccountId: c.SkipRequestingAccountId, + // StsEndpoint: c.Endpoints["sts"], + Token: c.Token, + } + + return awsbase.GetCredentials(awsbaseConfig) +} + func (c *AccessConfig) GetCredsFromVault() error { // const EnvVaultAddress = "VAULT_ADDR" // const EnvVaultToken = "VAULT_TOKEN" @@ -306,6 +408,13 @@ func (c *AccessConfig) Prepare(ctx *interpolate.Context) []error { return errs } +func (c *AccessConfig) NewNoValidCredentialSourcesError(err error) error { + return fmt.Errorf("No valid credential sources found for AWS Builder. "+ + "Please see https://www.packer.io/docs/builders/amazon#authentication "+ + "for more information on providing credentials for the AWS Builder. "+ + "Error: %w", err) +} + func (c *AccessConfig) NewEC2Connection() (ec2iface.EC2API, error) { if c.getEC2Connection != nil { return c.getEC2Connection(), nil diff --git a/builder/amazon/common/access_config.hcl2spec.go b/builder/amazon/common/access_config.hcl2spec.go index a4ed99359..177553620 100644 --- a/builder/amazon/common/access_config.hcl2spec.go +++ b/builder/amazon/common/access_config.hcl2spec.go @@ -1,4 +1,4 @@ -// Code generated by "mapstructure-to-hcl2 -type VaultAWSEngineOptions"; DO NOT EDIT. +// Code generated by "mapstructure-to-hcl2 -type VaultAWSEngineOptions,AssumeRoleConfig"; DO NOT EDIT. package common import ( @@ -6,6 +6,43 @@ import ( "github.com/zclconf/go-cty/cty" ) +// FlatAssumeRoleConfig is an auto-generated flat version of AssumeRoleConfig. +// Where the contents of a field with a `mapstructure:,squash` tag are bubbled up. +type FlatAssumeRoleConfig struct { + AssumeRoleARN *string `mapstructure:"role_arn" required:"false" cty:"role_arn" hcl:"role_arn"` + AssumeRoleDurationSeconds *int `mapstructure:"duration_seconds" required:"false" cty:"duration_seconds" hcl:"duration_seconds"` + AssumeRoleExternalID *string `mapstructure:"external_id" required:"false" cty:"external_id" hcl:"external_id"` + AssumeRolePolicy *string `mapstructure:"policy" required:"false" cty:"policy" hcl:"policy"` + AssumeRolePolicyARNs []string `mapstructure:"policy_arns" required:"false" cty:"policy_arns" hcl:"policy_arns"` + AssumeRoleSessionName *string `mapstructure:"session_name" required:"false" cty:"session_name" hcl:"session_name"` + AssumeRoleTags map[string]string `mapstructure:"tags" required:"false" cty:"tags" hcl:"tags"` + AssumeRoleTransitiveTagKeys []string `mapstructure:"transitive_tag_keys" required:"false" cty:"transitive_tag_keys" hcl:"transitive_tag_keys"` +} + +// FlatMapstructure returns a new FlatAssumeRoleConfig. +// FlatAssumeRoleConfig is an auto-generated flat version of AssumeRoleConfig. +// Where the contents a fields with a `mapstructure:,squash` tag are bubbled up. +func (*AssumeRoleConfig) FlatMapstructure() interface{ HCL2Spec() map[string]hcldec.Spec } { + return new(FlatAssumeRoleConfig) +} + +// HCL2Spec returns the hcl spec of a AssumeRoleConfig. +// This spec is used by HCL to read the fields of AssumeRoleConfig. +// The decoded values from this spec will then be applied to a FlatAssumeRoleConfig. +func (*FlatAssumeRoleConfig) HCL2Spec() map[string]hcldec.Spec { + s := map[string]hcldec.Spec{ + "role_arn": &hcldec.AttrSpec{Name: "role_arn", Type: cty.String, Required: false}, + "duration_seconds": &hcldec.AttrSpec{Name: "duration_seconds", Type: cty.Number, Required: false}, + "external_id": &hcldec.AttrSpec{Name: "external_id", Type: cty.String, Required: false}, + "policy": &hcldec.AttrSpec{Name: "policy", Type: cty.String, Required: false}, + "policy_arns": &hcldec.AttrSpec{Name: "policy_arns", Type: cty.List(cty.String), Required: false}, + "session_name": &hcldec.AttrSpec{Name: "session_name", Type: cty.String, Required: false}, + "tags": &hcldec.AttrSpec{Name: "tags", Type: cty.Map(cty.String), Required: false}, + "transitive_tag_keys": &hcldec.AttrSpec{Name: "transitive_tag_keys", Type: cty.List(cty.String), Required: false}, + } + return s +} + // FlatVaultAWSEngineOptions is an auto-generated flat version of VaultAWSEngineOptions. // Where the contents of a field with a `mapstructure:,squash` tag are bubbled up. type FlatVaultAWSEngineOptions struct { diff --git a/builder/amazon/common/run_config.go b/builder/amazon/common/run_config.go index 7905eeef1..54985cac8 100644 --- a/builder/amazon/common/run_config.go +++ b/builder/amazon/common/run_config.go @@ -473,6 +473,13 @@ type RunConfig struct { // terminating the tunnel it will automatically terminate itself after 20 minutes of inactivity. SSHInterface string `mapstructure:"ssh_interface"` + // The time to wait before establishing the Session Manager session. + // The value of this should be a duration. Examples are + // `5s` and `1m30s` which will cause Packer to wait five seconds and one + // minute 30 seconds, respectively. If no set, defaults to 10 seconds. + // This option is useful when the remote port takes longer to become available. + PauseBeforeSSM time.Duration `mapstructure:"pause_before_ssm"` + // Which port to connect the local end of the session tunnel to. If // left blank, Packer will choose a port for you from available ports. // This option is only used when `ssh_interface` is set `session_manager`. @@ -535,6 +542,10 @@ func (c *RunConfig) Prepare(ctx *interpolate.Context) []error { msg := fmt.Errorf(`no iam_instance_profile defined; session_manager connectivity requires a valid instance profile with AmazonSSMManagedInstanceCore permissions. Alternatively a temporary_iam_instance_profile_policy_document can be used.`) errs = append(errs, msg) } + + if c.PauseBeforeSSM == 0 { + c.PauseBeforeSSM = 10 * time.Second + } } if c.Comm.SSHKeyPairName != "" { diff --git a/builder/amazon/common/ssm_driver.go b/builder/amazon/common/ssm_driver.go index 5ba73c8bd..563fa7eab 100644 --- a/builder/amazon/common/ssm_driver.go +++ b/builder/amazon/common/ssm_driver.go @@ -46,7 +46,7 @@ func NewSSMDriver(config SSMDriverConfig) *SSMDriver { // not wish to manage the session manually calling StopSession on a instance of this driver will terminate the active session // created from calling StartSession. func (d *SSMDriver) StartSession(ctx context.Context, input ssm.StartSessionInput) (*ssm.StartSessionOutput, error) { - log.Printf("Starting PortForwarding session to instance %q with following params %v", aws.StringValue(input.Target), input.Parameters) + log.Printf("Starting PortForwarding session to instance %q", aws.StringValue(input.Target)) var output *ssm.StartSessionOutput err := retry.Config{ @@ -110,15 +110,30 @@ func (d *SSMDriver) openTunnelForSession(ctx context.Context) error { select { case <-ctx.Done(): return - case output := <-stderrCh: + case output, ok := <-stderrCh: + if !ok { + stderrCh = nil + break + } + if output != "" { log.Printf("[ERROR] %s: %s", prefix, output) } - case output := <-stdoutCh: + case output, ok := <-stdoutCh: + if !ok { + stdoutCh = nil + break + } + if output != "" { log.Printf("[DEBUG] %s: %s", prefix, output) } } + + if stdoutCh == nil && stderrCh == nil { + log.Printf("[DEBUG] %s: %s", prefix, "active session has been terminated; stopping all log polling processes.") + return + } } }(ctx, sessionManagerPluginName) diff --git a/builder/amazon/common/step_create_ssm_tunnel.go b/builder/amazon/common/step_create_ssm_tunnel.go index 72f6b2ced..c29a4dc5b 100644 --- a/builder/amazon/common/step_create_ssm_tunnel.go +++ b/builder/amazon/common/step_create_ssm_tunnel.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "strconv" + "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" @@ -21,6 +22,7 @@ type StepCreateSSMTunnel struct { RemotePortNumber int SSMAgentEnabled bool instanceId string + PauseBeforeSSM time.Duration driver *SSMDriver } @@ -32,6 +34,17 @@ func (s *StepCreateSSMTunnel) Run(ctx context.Context, state multistep.StateBag) return multistep.ActionContinue } + // Wait for the remote port to become available + if s.PauseBeforeSSM > 0 { + ui.Say(fmt.Sprintf("Waiting %s for establishing the SSM session...", s.PauseBeforeSSM)) + select { + case <-time.After(s.PauseBeforeSSM): + break + case <-ctx.Done(): + return multistep.ActionHalt + } + } + // Configure local port number if err := s.ConfigureLocalHostPort(ctx); err != nil { err := fmt.Errorf("error finding an available port to initiate a session tunnel: %s", err) diff --git a/builder/amazon/common/step_run_spot_instance.go b/builder/amazon/common/step_run_spot_instance.go index 940e7c8ac..fae1dc4bc 100644 --- a/builder/amazon/common/step_run_spot_instance.go +++ b/builder/amazon/common/step_run_spot_instance.go @@ -10,7 +10,6 @@ import ( "time" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/service/ec2" "github.com/hashicorp/packer/common/random" "github.com/hashicorp/packer/common/retry" @@ -281,7 +280,6 @@ func (s *StepRunSpotInstance) Run(ctx context.Context, state multistep.StateBag) } var createOutput *ec2.CreateFleetOutput - err = retry.Config{ Tries: 11, ShouldRetry: func(err error) bool { @@ -291,40 +289,39 @@ func (s *StepRunSpotInstance) Run(ctx context.Context, state multistep.StateBag) // we can wait on those operations, this can be removed. return true } - return request.IsErrorRetryable(err) + return false }, RetryDelay: (&retry.Backoff{InitialBackoff: 500 * time.Millisecond, MaxBackoff: 30 * time.Second, Multiplier: 2}).Linear, }.Run(ctx, func(ctx context.Context) error { createOutput, err = ec2conn.CreateFleet(createFleetInput) - if err == nil && createOutput.Errors != nil { err = fmt.Errorf("errors: %v", createOutput.Errors) } + // We can end up with errors because one of the allowed availability + // zones doesn't have one of the allowed instance types; as long as + // an instance is launched, these errors aren't important. + if len(createOutput.Instances) > 0 { + if err != nil { + log.Printf("create request failed for some instances %v", err.Error()) + } + return nil + } if err != nil { log.Printf("create request failed %v", err) } return err }) - // Create the request for the spot instance. if err != nil { if createOutput.FleetId != nil { err = fmt.Errorf("Error waiting for fleet request (%s): %s", *createOutput.FleetId, err) - } else { - err = fmt.Errorf("Error waiting for fleet request: %s", err) } - // We can end up with errors because one of the allowed availability - // zones doesn't have one of the allowed instance types; as long as - // an instance is launched, these errors aren't important. if len(createOutput.Errors) > 0 { errString := fmt.Sprintf("Error waiting for fleet request (%s) to become ready:", *createOutput.FleetId) for _, outErr := range createOutput.Errors { errString = errString + aws.StringValue(outErr.ErrorMessage) } err = fmt.Errorf(errString) - state.Put("error", err) - ui.Error(err.Error()) - return multistep.ActionHalt } state.Put("error", err) ui.Error(err.Error()) diff --git a/builder/amazon/ebs/builder.go b/builder/amazon/ebs/builder.go index a19fbc423..56f48c49d 100644 --- a/builder/amazon/ebs/builder.go +++ b/builder/amazon/ebs/builder.go @@ -269,6 +269,7 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack &awscommon.StepCreateSSMTunnel{ AWSSession: session, Region: *ec2conn.Config.Region, + PauseBeforeSSM: b.config.PauseBeforeSSM, LocalPortNumber: b.config.SessionManagerPort, RemotePortNumber: b.config.Comm.Port(), SSMAgentEnabled: b.config.SSMAgentEnabled(), diff --git a/builder/amazon/ebs/builder.hcl2spec.go b/builder/amazon/ebs/builder.hcl2spec.go index 0e3bcac1c..571d93717 100644 --- a/builder/amazon/ebs/builder.hcl2spec.go +++ b/builder/amazon/ebs/builder.hcl2spec.go @@ -19,7 +19,9 @@ type FlatConfig struct { PackerUserVars map[string]string `mapstructure:"packer_user_variables" cty:"packer_user_variables" hcl:"packer_user_variables"` PackerSensitiveVars []string `mapstructure:"packer_sensitive_variables" cty:"packer_sensitive_variables" hcl:"packer_sensitive_variables"` AccessKey *string `mapstructure:"access_key" required:"true" cty:"access_key" hcl:"access_key"` + AssumeRole *common.FlatAssumeRoleConfig `mapstructure:"assume_role" required:"false" cty:"assume_role" hcl:"assume_role"` CustomEndpointEc2 *string `mapstructure:"custom_endpoint_ec2" required:"false" cty:"custom_endpoint_ec2" hcl:"custom_endpoint_ec2"` + CredsFilename *string `mapstructure:"shared_credentials_file" required:"false" cty:"shared_credentials_file" hcl:"shared_credentials_file"` DecodeAuthZMessages *bool `mapstructure:"decode_authorization_messages" required:"false" cty:"decode_authorization_messages" hcl:"decode_authorization_messages"` InsecureSkipTLSVerify *bool `mapstructure:"insecure_skip_tls_verify" required:"false" cty:"insecure_skip_tls_verify" hcl:"insecure_skip_tls_verify"` MaxRetries *int `mapstructure:"max_retries" required:"false" cty:"max_retries" hcl:"max_retries"` @@ -29,6 +31,7 @@ type FlatConfig struct { SecretKey *string `mapstructure:"secret_key" required:"true" cty:"secret_key" hcl:"secret_key"` SkipValidation *bool `mapstructure:"skip_region_validation" required:"false" cty:"skip_region_validation" hcl:"skip_region_validation"` SkipMetadataApiCheck *bool `mapstructure:"skip_metadata_api_check" cty:"skip_metadata_api_check" hcl:"skip_metadata_api_check"` + SkipCredsValidation *bool `mapstructure:"skip_credential_validation" cty:"skip_credential_validation" hcl:"skip_credential_validation"` Token *string `mapstructure:"token" required:"false" cty:"token" hcl:"token"` VaultAWSEngine *common.FlatVaultAWSEngineOptions `mapstructure:"vault_aws_engine" required:"false" cty:"vault_aws_engine" hcl:"vault_aws_engine"` PollingConfig *common.FlatAWSPollingConfig `mapstructure:"aws_polling" required:"false" cty:"aws_polling" hcl:"aws_polling"` @@ -132,6 +135,7 @@ type FlatConfig struct { WinRMInsecure *bool `mapstructure:"winrm_insecure" cty:"winrm_insecure" hcl:"winrm_insecure"` WinRMUseNTLM *bool `mapstructure:"winrm_use_ntlm" cty:"winrm_use_ntlm" hcl:"winrm_use_ntlm"` SSHInterface *string `mapstructure:"ssh_interface" cty:"ssh_interface" hcl:"ssh_interface"` + PauseBeforeSSM *string `mapstructure:"pause_before_ssm" cty:"pause_before_ssm" hcl:"pause_before_ssm"` SessionManagerPort *int `mapstructure:"session_manager_port" cty:"session_manager_port" hcl:"session_manager_port"` AMIMappings []common.FlatBlockDevice `mapstructure:"ami_block_device_mappings" required:"false" cty:"ami_block_device_mappings" hcl:"ami_block_device_mappings"` LaunchMappings []common.FlatBlockDevice `mapstructure:"launch_block_device_mappings" required:"false" cty:"launch_block_device_mappings" hcl:"launch_block_device_mappings"` @@ -160,7 +164,9 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "packer_user_variables": &hcldec.AttrSpec{Name: "packer_user_variables", Type: cty.Map(cty.String), Required: false}, "packer_sensitive_variables": &hcldec.AttrSpec{Name: "packer_sensitive_variables", Type: cty.List(cty.String), Required: false}, "access_key": &hcldec.AttrSpec{Name: "access_key", Type: cty.String, Required: false}, + "assume_role": &hcldec.BlockSpec{TypeName: "assume_role", Nested: hcldec.ObjectSpec((*common.FlatAssumeRoleConfig)(nil).HCL2Spec())}, "custom_endpoint_ec2": &hcldec.AttrSpec{Name: "custom_endpoint_ec2", Type: cty.String, Required: false}, + "shared_credentials_file": &hcldec.AttrSpec{Name: "shared_credentials_file", Type: cty.String, Required: false}, "decode_authorization_messages": &hcldec.AttrSpec{Name: "decode_authorization_messages", Type: cty.Bool, Required: false}, "insecure_skip_tls_verify": &hcldec.AttrSpec{Name: "insecure_skip_tls_verify", Type: cty.Bool, Required: false}, "max_retries": &hcldec.AttrSpec{Name: "max_retries", Type: cty.Number, Required: false}, @@ -170,6 +176,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "secret_key": &hcldec.AttrSpec{Name: "secret_key", Type: cty.String, Required: false}, "skip_region_validation": &hcldec.AttrSpec{Name: "skip_region_validation", Type: cty.Bool, Required: false}, "skip_metadata_api_check": &hcldec.AttrSpec{Name: "skip_metadata_api_check", Type: cty.Bool, Required: false}, + "skip_credential_validation": &hcldec.AttrSpec{Name: "skip_credential_validation", Type: cty.Bool, Required: false}, "token": &hcldec.AttrSpec{Name: "token", Type: cty.String, Required: false}, "vault_aws_engine": &hcldec.BlockSpec{TypeName: "vault_aws_engine", Nested: hcldec.ObjectSpec((*common.FlatVaultAWSEngineOptions)(nil).HCL2Spec())}, "aws_polling": &hcldec.BlockSpec{TypeName: "aws_polling", Nested: hcldec.ObjectSpec((*common.FlatAWSPollingConfig)(nil).HCL2Spec())}, @@ -273,6 +280,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "winrm_insecure": &hcldec.AttrSpec{Name: "winrm_insecure", Type: cty.Bool, Required: false}, "winrm_use_ntlm": &hcldec.AttrSpec{Name: "winrm_use_ntlm", Type: cty.Bool, Required: false}, "ssh_interface": &hcldec.AttrSpec{Name: "ssh_interface", Type: cty.String, Required: false}, + "pause_before_ssm": &hcldec.AttrSpec{Name: "pause_before_ssm", Type: cty.String, Required: false}, "session_manager_port": &hcldec.AttrSpec{Name: "session_manager_port", Type: cty.Number, Required: false}, "ami_block_device_mappings": &hcldec.BlockListSpec{TypeName: "ami_block_device_mappings", Nested: hcldec.ObjectSpec((*common.FlatBlockDevice)(nil).HCL2Spec())}, "launch_block_device_mappings": &hcldec.BlockListSpec{TypeName: "launch_block_device_mappings", Nested: hcldec.ObjectSpec((*common.FlatBlockDevice)(nil).HCL2Spec())}, diff --git a/builder/amazon/ebssurrogate/block_device.go b/builder/amazon/ebssurrogate/block_device.go index 0757ded46..18e442f22 100644 --- a/builder/amazon/ebssurrogate/block_device.go +++ b/builder/amazon/ebssurrogate/block_device.go @@ -3,9 +3,6 @@ package ebssurrogate import ( - "strings" - - "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" awscommon "github.com/hashicorp/packer/builder/amazon/common" "github.com/hashicorp/packer/template/interpolate" @@ -41,50 +38,6 @@ func (bds BlockDevices) BuildEC2BlockDeviceMappings() []*ec2.BlockDeviceMapping return blockDevices } -func (blockDevice BlockDevice) BuildEC2BlockDeviceMapping() *ec2.BlockDeviceMapping { - - mapping := &ec2.BlockDeviceMapping{ - DeviceName: aws.String(blockDevice.DeviceName), - } - - if blockDevice.NoDevice { - mapping.NoDevice = aws.String("") - return mapping - } else if blockDevice.VirtualName != "" { - if strings.HasPrefix(blockDevice.VirtualName, "ephemeral") { - mapping.VirtualName = aws.String(blockDevice.VirtualName) - } - return mapping - } - - ebsBlockDevice := &ec2.EbsBlockDevice{ - DeleteOnTermination: aws.Bool(blockDevice.DeleteOnTermination), - } - - if blockDevice.VolumeType != "" { - ebsBlockDevice.VolumeType = aws.String(blockDevice.VolumeType) - } - - if blockDevice.VolumeSize > 0 { - ebsBlockDevice.VolumeSize = aws.Int64(blockDevice.VolumeSize) - } - - // IOPS is only valid for io1 type - if blockDevice.VolumeType == "io1" { - ebsBlockDevice.Iops = aws.Int64(blockDevice.IOPS) - } - - // You cannot specify Encrypted if you specify a Snapshot ID - if blockDevice.SnapshotId != "" { - ebsBlockDevice.SnapshotId = aws.String(blockDevice.SnapshotId) - } - ebsBlockDevice.Encrypted = blockDevice.Encrypted.ToBoolPointer() - - mapping.Ebs = ebsBlockDevice - - return mapping -} - func (bds BlockDevices) Prepare(ctx *interpolate.Context) (errs []error) { for _, block := range bds { if err := block.Prepare(ctx); err != nil { diff --git a/builder/amazon/ebssurrogate/builder.go b/builder/amazon/ebssurrogate/builder.go index f53124128..d1620854f 100644 --- a/builder/amazon/ebssurrogate/builder.go +++ b/builder/amazon/ebssurrogate/builder.go @@ -293,6 +293,7 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack &awscommon.StepCreateSSMTunnel{ AWSSession: session, Region: *ec2conn.Config.Region, + PauseBeforeSSM: b.config.PauseBeforeSSM, LocalPortNumber: b.config.SessionManagerPort, RemotePortNumber: b.config.Comm.Port(), SSMAgentEnabled: b.config.SSMAgentEnabled(), diff --git a/builder/amazon/ebssurrogate/builder.hcl2spec.go b/builder/amazon/ebssurrogate/builder.hcl2spec.go index 733a8f2e5..deac89fac 100644 --- a/builder/amazon/ebssurrogate/builder.hcl2spec.go +++ b/builder/amazon/ebssurrogate/builder.hcl2spec.go @@ -62,7 +62,9 @@ type FlatConfig struct { PackerUserVars map[string]string `mapstructure:"packer_user_variables" cty:"packer_user_variables" hcl:"packer_user_variables"` PackerSensitiveVars []string `mapstructure:"packer_sensitive_variables" cty:"packer_sensitive_variables" hcl:"packer_sensitive_variables"` AccessKey *string `mapstructure:"access_key" required:"true" cty:"access_key" hcl:"access_key"` + AssumeRole *common.FlatAssumeRoleConfig `mapstructure:"assume_role" required:"false" cty:"assume_role" hcl:"assume_role"` CustomEndpointEc2 *string `mapstructure:"custom_endpoint_ec2" required:"false" cty:"custom_endpoint_ec2" hcl:"custom_endpoint_ec2"` + CredsFilename *string `mapstructure:"shared_credentials_file" required:"false" cty:"shared_credentials_file" hcl:"shared_credentials_file"` DecodeAuthZMessages *bool `mapstructure:"decode_authorization_messages" required:"false" cty:"decode_authorization_messages" hcl:"decode_authorization_messages"` InsecureSkipTLSVerify *bool `mapstructure:"insecure_skip_tls_verify" required:"false" cty:"insecure_skip_tls_verify" hcl:"insecure_skip_tls_verify"` MaxRetries *int `mapstructure:"max_retries" required:"false" cty:"max_retries" hcl:"max_retries"` @@ -72,6 +74,7 @@ type FlatConfig struct { SecretKey *string `mapstructure:"secret_key" required:"true" cty:"secret_key" hcl:"secret_key"` SkipValidation *bool `mapstructure:"skip_region_validation" required:"false" cty:"skip_region_validation" hcl:"skip_region_validation"` SkipMetadataApiCheck *bool `mapstructure:"skip_metadata_api_check" cty:"skip_metadata_api_check" hcl:"skip_metadata_api_check"` + SkipCredsValidation *bool `mapstructure:"skip_credential_validation" cty:"skip_credential_validation" hcl:"skip_credential_validation"` Token *string `mapstructure:"token" required:"false" cty:"token" hcl:"token"` VaultAWSEngine *common.FlatVaultAWSEngineOptions `mapstructure:"vault_aws_engine" required:"false" cty:"vault_aws_engine" hcl:"vault_aws_engine"` PollingConfig *common.FlatAWSPollingConfig `mapstructure:"aws_polling" required:"false" cty:"aws_polling" hcl:"aws_polling"` @@ -154,6 +157,7 @@ type FlatConfig struct { WinRMInsecure *bool `mapstructure:"winrm_insecure" cty:"winrm_insecure" hcl:"winrm_insecure"` WinRMUseNTLM *bool `mapstructure:"winrm_use_ntlm" cty:"winrm_use_ntlm" hcl:"winrm_use_ntlm"` SSHInterface *string `mapstructure:"ssh_interface" cty:"ssh_interface" hcl:"ssh_interface"` + PauseBeforeSSM *string `mapstructure:"pause_before_ssm" cty:"pause_before_ssm" hcl:"pause_before_ssm"` SessionManagerPort *int `mapstructure:"session_manager_port" cty:"session_manager_port" hcl:"session_manager_port"` AMIName *string `mapstructure:"ami_name" required:"true" cty:"ami_name" hcl:"ami_name"` AMIDescription *string `mapstructure:"ami_description" required:"false" cty:"ami_description" hcl:"ami_description"` @@ -204,7 +208,9 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "packer_user_variables": &hcldec.AttrSpec{Name: "packer_user_variables", Type: cty.Map(cty.String), Required: false}, "packer_sensitive_variables": &hcldec.AttrSpec{Name: "packer_sensitive_variables", Type: cty.List(cty.String), Required: false}, "access_key": &hcldec.AttrSpec{Name: "access_key", Type: cty.String, Required: false}, + "assume_role": &hcldec.BlockSpec{TypeName: "assume_role", Nested: hcldec.ObjectSpec((*common.FlatAssumeRoleConfig)(nil).HCL2Spec())}, "custom_endpoint_ec2": &hcldec.AttrSpec{Name: "custom_endpoint_ec2", Type: cty.String, Required: false}, + "shared_credentials_file": &hcldec.AttrSpec{Name: "shared_credentials_file", Type: cty.String, Required: false}, "decode_authorization_messages": &hcldec.AttrSpec{Name: "decode_authorization_messages", Type: cty.Bool, Required: false}, "insecure_skip_tls_verify": &hcldec.AttrSpec{Name: "insecure_skip_tls_verify", Type: cty.Bool, Required: false}, "max_retries": &hcldec.AttrSpec{Name: "max_retries", Type: cty.Number, Required: false}, @@ -214,6 +220,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "secret_key": &hcldec.AttrSpec{Name: "secret_key", Type: cty.String, Required: false}, "skip_region_validation": &hcldec.AttrSpec{Name: "skip_region_validation", Type: cty.Bool, Required: false}, "skip_metadata_api_check": &hcldec.AttrSpec{Name: "skip_metadata_api_check", Type: cty.Bool, Required: false}, + "skip_credential_validation": &hcldec.AttrSpec{Name: "skip_credential_validation", Type: cty.Bool, Required: false}, "token": &hcldec.AttrSpec{Name: "token", Type: cty.String, Required: false}, "vault_aws_engine": &hcldec.BlockSpec{TypeName: "vault_aws_engine", Nested: hcldec.ObjectSpec((*common.FlatVaultAWSEngineOptions)(nil).HCL2Spec())}, "aws_polling": &hcldec.BlockSpec{TypeName: "aws_polling", Nested: hcldec.ObjectSpec((*common.FlatAWSPollingConfig)(nil).HCL2Spec())}, @@ -296,6 +303,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "winrm_insecure": &hcldec.AttrSpec{Name: "winrm_insecure", Type: cty.Bool, Required: false}, "winrm_use_ntlm": &hcldec.AttrSpec{Name: "winrm_use_ntlm", Type: cty.Bool, Required: false}, "ssh_interface": &hcldec.AttrSpec{Name: "ssh_interface", Type: cty.String, Required: false}, + "pause_before_ssm": &hcldec.AttrSpec{Name: "pause_before_ssm", Type: cty.String, Required: false}, "session_manager_port": &hcldec.AttrSpec{Name: "session_manager_port", Type: cty.Number, Required: false}, "ami_name": &hcldec.AttrSpec{Name: "ami_name", Type: cty.String, Required: false}, "ami_description": &hcldec.AttrSpec{Name: "ami_description", Type: cty.String, Required: false}, diff --git a/builder/amazon/ebsvolume/builder.go b/builder/amazon/ebsvolume/builder.go index f6aa47b2f..a1ed2a935 100644 --- a/builder/amazon/ebsvolume/builder.go +++ b/builder/amazon/ebsvolume/builder.go @@ -263,6 +263,7 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack &awscommon.StepCreateSSMTunnel{ AWSSession: session, Region: *ec2conn.Config.Region, + PauseBeforeSSM: b.config.PauseBeforeSSM, LocalPortNumber: b.config.SessionManagerPort, RemotePortNumber: b.config.Comm.Port(), SSMAgentEnabled: b.config.SSMAgentEnabled(), diff --git a/builder/amazon/ebsvolume/builder.hcl2spec.go b/builder/amazon/ebsvolume/builder.hcl2spec.go index 392bdf304..fa5aad217 100644 --- a/builder/amazon/ebsvolume/builder.hcl2spec.go +++ b/builder/amazon/ebsvolume/builder.hcl2spec.go @@ -64,7 +64,9 @@ type FlatConfig struct { PackerUserVars map[string]string `mapstructure:"packer_user_variables" cty:"packer_user_variables" hcl:"packer_user_variables"` PackerSensitiveVars []string `mapstructure:"packer_sensitive_variables" cty:"packer_sensitive_variables" hcl:"packer_sensitive_variables"` AccessKey *string `mapstructure:"access_key" required:"true" cty:"access_key" hcl:"access_key"` + AssumeRole *common.FlatAssumeRoleConfig `mapstructure:"assume_role" required:"false" cty:"assume_role" hcl:"assume_role"` CustomEndpointEc2 *string `mapstructure:"custom_endpoint_ec2" required:"false" cty:"custom_endpoint_ec2" hcl:"custom_endpoint_ec2"` + CredsFilename *string `mapstructure:"shared_credentials_file" required:"false" cty:"shared_credentials_file" hcl:"shared_credentials_file"` DecodeAuthZMessages *bool `mapstructure:"decode_authorization_messages" required:"false" cty:"decode_authorization_messages" hcl:"decode_authorization_messages"` InsecureSkipTLSVerify *bool `mapstructure:"insecure_skip_tls_verify" required:"false" cty:"insecure_skip_tls_verify" hcl:"insecure_skip_tls_verify"` MaxRetries *int `mapstructure:"max_retries" required:"false" cty:"max_retries" hcl:"max_retries"` @@ -74,6 +76,7 @@ type FlatConfig struct { SecretKey *string `mapstructure:"secret_key" required:"true" cty:"secret_key" hcl:"secret_key"` SkipValidation *bool `mapstructure:"skip_region_validation" required:"false" cty:"skip_region_validation" hcl:"skip_region_validation"` SkipMetadataApiCheck *bool `mapstructure:"skip_metadata_api_check" cty:"skip_metadata_api_check" hcl:"skip_metadata_api_check"` + SkipCredsValidation *bool `mapstructure:"skip_credential_validation" cty:"skip_credential_validation" hcl:"skip_credential_validation"` Token *string `mapstructure:"token" required:"false" cty:"token" hcl:"token"` VaultAWSEngine *common.FlatVaultAWSEngineOptions `mapstructure:"vault_aws_engine" required:"false" cty:"vault_aws_engine" hcl:"vault_aws_engine"` PollingConfig *common.FlatAWSPollingConfig `mapstructure:"aws_polling" required:"false" cty:"aws_polling" hcl:"aws_polling"` @@ -156,6 +159,7 @@ type FlatConfig struct { WinRMInsecure *bool `mapstructure:"winrm_insecure" cty:"winrm_insecure" hcl:"winrm_insecure"` WinRMUseNTLM *bool `mapstructure:"winrm_use_ntlm" cty:"winrm_use_ntlm" hcl:"winrm_use_ntlm"` SSHInterface *string `mapstructure:"ssh_interface" cty:"ssh_interface" hcl:"ssh_interface"` + PauseBeforeSSM *string `mapstructure:"pause_before_ssm" cty:"pause_before_ssm" hcl:"pause_before_ssm"` SessionManagerPort *int `mapstructure:"session_manager_port" cty:"session_manager_port" hcl:"session_manager_port"` AMIENASupport *bool `mapstructure:"ena_support" required:"false" cty:"ena_support" hcl:"ena_support"` AMISriovNetSupport *bool `mapstructure:"sriov_support" required:"false" cty:"sriov_support" hcl:"sriov_support"` @@ -184,7 +188,9 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "packer_user_variables": &hcldec.AttrSpec{Name: "packer_user_variables", Type: cty.Map(cty.String), Required: false}, "packer_sensitive_variables": &hcldec.AttrSpec{Name: "packer_sensitive_variables", Type: cty.List(cty.String), Required: false}, "access_key": &hcldec.AttrSpec{Name: "access_key", Type: cty.String, Required: false}, + "assume_role": &hcldec.BlockSpec{TypeName: "assume_role", Nested: hcldec.ObjectSpec((*common.FlatAssumeRoleConfig)(nil).HCL2Spec())}, "custom_endpoint_ec2": &hcldec.AttrSpec{Name: "custom_endpoint_ec2", Type: cty.String, Required: false}, + "shared_credentials_file": &hcldec.AttrSpec{Name: "shared_credentials_file", Type: cty.String, Required: false}, "decode_authorization_messages": &hcldec.AttrSpec{Name: "decode_authorization_messages", Type: cty.Bool, Required: false}, "insecure_skip_tls_verify": &hcldec.AttrSpec{Name: "insecure_skip_tls_verify", Type: cty.Bool, Required: false}, "max_retries": &hcldec.AttrSpec{Name: "max_retries", Type: cty.Number, Required: false}, @@ -194,6 +200,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "secret_key": &hcldec.AttrSpec{Name: "secret_key", Type: cty.String, Required: false}, "skip_region_validation": &hcldec.AttrSpec{Name: "skip_region_validation", Type: cty.Bool, Required: false}, "skip_metadata_api_check": &hcldec.AttrSpec{Name: "skip_metadata_api_check", Type: cty.Bool, Required: false}, + "skip_credential_validation": &hcldec.AttrSpec{Name: "skip_credential_validation", Type: cty.Bool, Required: false}, "token": &hcldec.AttrSpec{Name: "token", Type: cty.String, Required: false}, "vault_aws_engine": &hcldec.BlockSpec{TypeName: "vault_aws_engine", Nested: hcldec.ObjectSpec((*common.FlatVaultAWSEngineOptions)(nil).HCL2Spec())}, "aws_polling": &hcldec.BlockSpec{TypeName: "aws_polling", Nested: hcldec.ObjectSpec((*common.FlatAWSPollingConfig)(nil).HCL2Spec())}, @@ -276,6 +283,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "winrm_insecure": &hcldec.AttrSpec{Name: "winrm_insecure", Type: cty.Bool, Required: false}, "winrm_use_ntlm": &hcldec.AttrSpec{Name: "winrm_use_ntlm", Type: cty.Bool, Required: false}, "ssh_interface": &hcldec.AttrSpec{Name: "ssh_interface", Type: cty.String, Required: false}, + "pause_before_ssm": &hcldec.AttrSpec{Name: "pause_before_ssm", Type: cty.String, Required: false}, "session_manager_port": &hcldec.AttrSpec{Name: "session_manager_port", Type: cty.Number, Required: false}, "ena_support": &hcldec.AttrSpec{Name: "ena_support", Type: cty.Bool, Required: false}, "sriov_support": &hcldec.AttrSpec{Name: "sriov_support", Type: cty.Bool, Required: false}, diff --git a/builder/amazon/instance/builder.go b/builder/amazon/instance/builder.go index b408ecf7d..bc8680c5b 100644 --- a/builder/amazon/instance/builder.go +++ b/builder/amazon/instance/builder.go @@ -343,6 +343,7 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack &awscommon.StepCreateSSMTunnel{ AWSSession: session, Region: *ec2conn.Config.Region, + PauseBeforeSSM: b.config.PauseBeforeSSM, LocalPortNumber: b.config.SessionManagerPort, RemotePortNumber: b.config.Comm.Port(), SSMAgentEnabled: b.config.SSMAgentEnabled(), diff --git a/builder/amazon/instance/builder.hcl2spec.go b/builder/amazon/instance/builder.hcl2spec.go index 6abbc5032..fa967cdb5 100644 --- a/builder/amazon/instance/builder.hcl2spec.go +++ b/builder/amazon/instance/builder.hcl2spec.go @@ -19,7 +19,9 @@ type FlatConfig struct { PackerUserVars map[string]string `mapstructure:"packer_user_variables" cty:"packer_user_variables" hcl:"packer_user_variables"` PackerSensitiveVars []string `mapstructure:"packer_sensitive_variables" cty:"packer_sensitive_variables" hcl:"packer_sensitive_variables"` AccessKey *string `mapstructure:"access_key" required:"true" cty:"access_key" hcl:"access_key"` + AssumeRole *common.FlatAssumeRoleConfig `mapstructure:"assume_role" required:"false" cty:"assume_role" hcl:"assume_role"` CustomEndpointEc2 *string `mapstructure:"custom_endpoint_ec2" required:"false" cty:"custom_endpoint_ec2" hcl:"custom_endpoint_ec2"` + CredsFilename *string `mapstructure:"shared_credentials_file" required:"false" cty:"shared_credentials_file" hcl:"shared_credentials_file"` DecodeAuthZMessages *bool `mapstructure:"decode_authorization_messages" required:"false" cty:"decode_authorization_messages" hcl:"decode_authorization_messages"` InsecureSkipTLSVerify *bool `mapstructure:"insecure_skip_tls_verify" required:"false" cty:"insecure_skip_tls_verify" hcl:"insecure_skip_tls_verify"` MaxRetries *int `mapstructure:"max_retries" required:"false" cty:"max_retries" hcl:"max_retries"` @@ -29,6 +31,7 @@ type FlatConfig struct { SecretKey *string `mapstructure:"secret_key" required:"true" cty:"secret_key" hcl:"secret_key"` SkipValidation *bool `mapstructure:"skip_region_validation" required:"false" cty:"skip_region_validation" hcl:"skip_region_validation"` SkipMetadataApiCheck *bool `mapstructure:"skip_metadata_api_check" cty:"skip_metadata_api_check" hcl:"skip_metadata_api_check"` + SkipCredsValidation *bool `mapstructure:"skip_credential_validation" cty:"skip_credential_validation" hcl:"skip_credential_validation"` Token *string `mapstructure:"token" required:"false" cty:"token" hcl:"token"` VaultAWSEngine *common.FlatVaultAWSEngineOptions `mapstructure:"vault_aws_engine" required:"false" cty:"vault_aws_engine" hcl:"vault_aws_engine"` PollingConfig *common.FlatAWSPollingConfig `mapstructure:"aws_polling" required:"false" cty:"aws_polling" hcl:"aws_polling"` @@ -132,6 +135,7 @@ type FlatConfig struct { WinRMInsecure *bool `mapstructure:"winrm_insecure" cty:"winrm_insecure" hcl:"winrm_insecure"` WinRMUseNTLM *bool `mapstructure:"winrm_use_ntlm" cty:"winrm_use_ntlm" hcl:"winrm_use_ntlm"` SSHInterface *string `mapstructure:"ssh_interface" cty:"ssh_interface" hcl:"ssh_interface"` + PauseBeforeSSM *string `mapstructure:"pause_before_ssm" cty:"pause_before_ssm" hcl:"pause_before_ssm"` SessionManagerPort *int `mapstructure:"session_manager_port" cty:"session_manager_port" hcl:"session_manager_port"` AMIMappings []common.FlatBlockDevice `mapstructure:"ami_block_device_mappings" required:"false" cty:"ami_block_device_mappings" hcl:"ami_block_device_mappings"` LaunchMappings []common.FlatBlockDevice `mapstructure:"launch_block_device_mappings" required:"false" cty:"launch_block_device_mappings" hcl:"launch_block_device_mappings"` @@ -166,7 +170,9 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "packer_user_variables": &hcldec.AttrSpec{Name: "packer_user_variables", Type: cty.Map(cty.String), Required: false}, "packer_sensitive_variables": &hcldec.AttrSpec{Name: "packer_sensitive_variables", Type: cty.List(cty.String), Required: false}, "access_key": &hcldec.AttrSpec{Name: "access_key", Type: cty.String, Required: false}, + "assume_role": &hcldec.BlockSpec{TypeName: "assume_role", Nested: hcldec.ObjectSpec((*common.FlatAssumeRoleConfig)(nil).HCL2Spec())}, "custom_endpoint_ec2": &hcldec.AttrSpec{Name: "custom_endpoint_ec2", Type: cty.String, Required: false}, + "shared_credentials_file": &hcldec.AttrSpec{Name: "shared_credentials_file", Type: cty.String, Required: false}, "decode_authorization_messages": &hcldec.AttrSpec{Name: "decode_authorization_messages", Type: cty.Bool, Required: false}, "insecure_skip_tls_verify": &hcldec.AttrSpec{Name: "insecure_skip_tls_verify", Type: cty.Bool, Required: false}, "max_retries": &hcldec.AttrSpec{Name: "max_retries", Type: cty.Number, Required: false}, @@ -176,6 +182,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "secret_key": &hcldec.AttrSpec{Name: "secret_key", Type: cty.String, Required: false}, "skip_region_validation": &hcldec.AttrSpec{Name: "skip_region_validation", Type: cty.Bool, Required: false}, "skip_metadata_api_check": &hcldec.AttrSpec{Name: "skip_metadata_api_check", Type: cty.Bool, Required: false}, + "skip_credential_validation": &hcldec.AttrSpec{Name: "skip_credential_validation", Type: cty.Bool, Required: false}, "token": &hcldec.AttrSpec{Name: "token", Type: cty.String, Required: false}, "vault_aws_engine": &hcldec.BlockSpec{TypeName: "vault_aws_engine", Nested: hcldec.ObjectSpec((*common.FlatVaultAWSEngineOptions)(nil).HCL2Spec())}, "aws_polling": &hcldec.BlockSpec{TypeName: "aws_polling", Nested: hcldec.ObjectSpec((*common.FlatAWSPollingConfig)(nil).HCL2Spec())}, @@ -279,6 +286,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "winrm_insecure": &hcldec.AttrSpec{Name: "winrm_insecure", Type: cty.Bool, Required: false}, "winrm_use_ntlm": &hcldec.AttrSpec{Name: "winrm_use_ntlm", Type: cty.Bool, Required: false}, "ssh_interface": &hcldec.AttrSpec{Name: "ssh_interface", Type: cty.String, Required: false}, + "pause_before_ssm": &hcldec.AttrSpec{Name: "pause_before_ssm", Type: cty.String, Required: false}, "session_manager_port": &hcldec.AttrSpec{Name: "session_manager_port", Type: cty.Number, Required: false}, "ami_block_device_mappings": &hcldec.BlockListSpec{TypeName: "ami_block_device_mappings", Nested: hcldec.ObjectSpec((*common.FlatBlockDevice)(nil).HCL2Spec())}, "launch_block_device_mappings": &hcldec.BlockListSpec{TypeName: "launch_block_device_mappings", Nested: hcldec.ObjectSpec((*common.FlatBlockDevice)(nil).HCL2Spec())}, diff --git a/builder/azure/arm/builder.go b/builder/azure/arm/builder.go index b0eced19e..3b01a5bfa 100644 --- a/builder/azure/arm/builder.go +++ b/builder/azure/arm/builder.go @@ -390,7 +390,7 @@ func (b *Builder) getBlobAccount(ctx context.Context, client *AzureClient, resou func (b *Builder) configureStateBag(stateBag multistep.StateBag) { stateBag.Put(constants.AuthorizedKey, b.config.sshAuthorizedKey) - stateBag.Put(constants.ArmTags, b.config.AzureTags) + stateBag.Put(constants.ArmTags, packerAzureCommon.MapToAzureTags(b.config.AzureTags)) stateBag.Put(constants.ArmComputeName, b.config.tmpComputeName) stateBag.Put(constants.ArmDeploymentName, b.config.tmpDeploymentName) diff --git a/builder/azure/arm/builder_acc_test.go b/builder/azure/arm/builder_acc_test.go index 57e48a4cb..b52f7fd42 100644 --- a/builder/azure/arm/builder_acc_test.go +++ b/builder/azure/arm/builder_acc_test.go @@ -223,7 +223,11 @@ const testBuilderAccManagedDiskLinux = ` "image_sku": "16.04-LTS", "location": "South Central US", - "vm_size": "Standard_DS2_v2" + "vm_size": "Standard_DS2_v2", + "azure_tags": { + "env": "testing", + "builder": "packer" + } }] } ` diff --git a/builder/azure/arm/builder_test.go b/builder/azure/arm/builder_test.go index 547a0c18a..3f4bb77c0 100644 --- a/builder/azure/arm/builder_test.go +++ b/builder/azure/arm/builder_test.go @@ -33,3 +33,35 @@ func TestStateBagShouldBePopulatedExpectedValues(t *testing.T) { } } } + +func TestStateBagShouldPoluateExpectedTags(t *testing.T) { + var testSubject Builder + + expectedTags := map[string]string{ + "env": "test", + "builder": "packer", + } + armConfig := getArmBuilderConfiguration() + armConfig["azure_tags"] = expectedTags + + _, _, err := testSubject.Prepare(armConfig, getPackerConfiguration()) + if err != nil { + t.Fatalf("failed to prepare: %s", err) + } + + tags, ok := testSubject.stateBag.Get(constants.ArmTags).(map[string]*string) + if !ok { + t.Errorf("Expected the builder's state bag to contain tags of type %T, but didn't.", testSubject.config.AzureTags) + } + + if len(tags) != len(expectedTags) { + t.Errorf("expect tags from state to be the same length as tags from config") + } + + for k, v := range tags { + if expectedTags[k] != *v { + t.Errorf("expect tag value of %s to be %s, but got %s", k, expectedTags[k], *v) + } + } + +} diff --git a/builder/azure/arm/config.go b/builder/azure/arm/config.go index 958098347..10f3a47f7 100644 --- a/builder/azure/arm/config.go +++ b/builder/azure/arm/config.go @@ -288,7 +288,7 @@ type Config struct { // Group, VM, NIC, VNET, Public IP, KeyVault, etc. The user can define up // to 15 tags. Tag names cannot exceed 512 characters, and tag values // cannot exceed 256 characters. - AzureTags map[string]*string `mapstructure:"azure_tags" required:"false"` + AzureTags map[string]string `mapstructure:"azure_tags" required:"false"` // Same as [`azure_tags`](#azure_tags) but defined as a singular repeatable block // containing a `name` and a `value` field. In HCL2 mode the // [`dynamic_block`](/docs/configuration/from-1.5/expressions#dynamic-blocks) @@ -513,7 +513,7 @@ func (c *Config) toImageParameters() *compute.Image { }, }, Location: to.StringPtr(c.Location), - Tags: c.AzureTags, + Tags: azcommon.MapToAzureTags(c.AzureTags), } } @@ -596,10 +596,7 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { } // copy singular blocks - for _, kv := range c.AzureTag { - v := kv.Value - c.AzureTags[kv.Name] = &v - } + c.AzureTag.CopyOn(&c.AzureTags) err = c.ClientConfig.SetDefaultValues() if err != nil { @@ -807,8 +804,8 @@ func assertTagProperties(c *Config, errs *packer.MultiError) { if len(k) > 512 { errs = packer.MultiErrorAppend(errs, fmt.Errorf("the tag name %q exceeds (%d) the 512 character limit", k, len(k))) } - if len(*v) > 256 { - errs = packer.MultiErrorAppend(errs, fmt.Errorf("the tag name %q exceeds (%d) the 256 character limit", *v, len(*v))) + if len(v) > 256 { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("the tag name %q exceeds (%d) the 256 character limit", v, len(v))) } } } @@ -1063,13 +1060,13 @@ func assertRequiredParametersSet(c *Config, errs *packer.MultiError) { errs = packer.MultiErrorAppend(errs, fmt.Errorf("if either plan_name, plan_product, plan_publisher, or plan_promotion_code are defined then plan_name, plan_product, and plan_publisher must be defined")) } else { if c.AzureTags == nil { - c.AzureTags = make(map[string]*string) + c.AzureTags = make(map[string]string) } - c.AzureTags["PlanInfo"] = &c.PlanInfo.PlanName - c.AzureTags["PlanProduct"] = &c.PlanInfo.PlanProduct - c.AzureTags["PlanPublisher"] = &c.PlanInfo.PlanPublisher - c.AzureTags["PlanPromotionCode"] = &c.PlanInfo.PlanPromotionCode + c.AzureTags["PlanInfo"] = c.PlanInfo.PlanName + c.AzureTags["PlanProduct"] = c.PlanInfo.PlanProduct + c.AzureTags["PlanPublisher"] = c.PlanInfo.PlanPublisher + c.AzureTags["PlanPromotionCode"] = c.PlanInfo.PlanPromotionCode } } diff --git a/builder/azure/arm/config.hcl2spec.go b/builder/azure/arm/config.hcl2spec.go index 64de1fb5e..27c798dc0 100644 --- a/builder/azure/arm/config.hcl2spec.go +++ b/builder/azure/arm/config.hcl2spec.go @@ -49,7 +49,7 @@ type FlatConfig struct { ManagedImageOSDiskSnapshotName *string `mapstructure:"managed_image_os_disk_snapshot_name" required:"false" cty:"managed_image_os_disk_snapshot_name" hcl:"managed_image_os_disk_snapshot_name"` ManagedImageDataDiskSnapshotPrefix *string `mapstructure:"managed_image_data_disk_snapshot_prefix" required:"false" cty:"managed_image_data_disk_snapshot_prefix" hcl:"managed_image_data_disk_snapshot_prefix"` ManagedImageZoneResilient *bool `mapstructure:"managed_image_zone_resilient" required:"false" cty:"managed_image_zone_resilient" hcl:"managed_image_zone_resilient"` - AzureTags map[string]*string `mapstructure:"azure_tags" required:"false" cty:"azure_tags" hcl:"azure_tags"` + AzureTags map[string]string `mapstructure:"azure_tags" required:"false" cty:"azure_tags" hcl:"azure_tags"` AzureTag []hcl2template.FlatNameValue `mapstructure:"azure_tag" required:"false" cty:"azure_tag" hcl:"azure_tag"` ResourceGroupName *string `mapstructure:"resource_group_name" cty:"resource_group_name" hcl:"resource_group_name"` StorageAccount *string `mapstructure:"storage_account" cty:"storage_account" hcl:"storage_account"` diff --git a/builder/azure/arm/config_test.go b/builder/azure/arm/config_test.go index 3f6df81ff..dda6e9234 100644 --- a/builder/azure/arm/config_test.go +++ b/builder/azure/arm/config_test.go @@ -6,7 +6,9 @@ import ( "time" "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-04-01/compute" + "github.com/google/go-cmp/cmp" "github.com/hashicorp/packer/builder/azure/common/constants" + "github.com/hashicorp/packer/hcl2template" ) // List of configuration parameters that are required by the ARM builder. @@ -910,32 +912,55 @@ func TestConfigShouldAcceptTags(t *testing.T) { }, } - var c Config + c := Config{ + AzureTag: hcl2template.NameValues{ + {Name: "tag03", Value: "value03"}, + }, + } _, err := c.Prepare(config, getPackerConfiguration()) - if err != nil { t.Fatal(err) } - if len(c.AzureTags) != 2 { - t.Fatalf("expected to find 2 tags, but got %d", len(c.AzureTags)) + if diff := cmp.Diff(c.AzureTags, map[string]string{ + "tag01": "value01", + "tag02": "value02", + "tag03": "value03", + }); diff != "" { + t.Fatalf("unexpected azure tags: %s", diff) + } +} + +func TestConfigShouldAcceptTag(t *testing.T) { + config := map[string]interface{}{ + "capture_name_prefix": "ignore", + "capture_container_name": "ignore", + "image_offer": "ignore", + "image_publisher": "ignore", + "image_sku": "ignore", + "location": "ignore", + "storage_account": "ignore", + "resource_group_name": "ignore", + "subscription_id": "ignore", + "communicator": "none", + // Does not matter for this test case, just pick one. + "os_type": constants.Target_Linux, } - if _, ok := c.AzureTags["tag01"]; !ok { - t.Error("expected to find key=\"tag01\", but did not") + c := Config{ + AzureTag: hcl2template.NameValues{ + {Name: "tag03", Value: "value03"}, + }, } - if _, ok := c.AzureTags["tag02"]; !ok { - t.Error("expected to find key=\"tag02\", but did not") + _, err := c.Prepare(config, getPackerConfiguration()) + if err != nil { + t.Fatal(err) } - value := c.AzureTags["tag01"] - if *value != "value01" { - t.Errorf("expected AzureTags[\"tag01\"] to have value \"value01\", but got %q", *value) - } - - value = c.AzureTags["tag02"] - if *value != "value02" { - t.Errorf("expected AzureTags[\"tag02\"] to have value \"value02\", but got %q", *value) + if diff := cmp.Diff(c.AzureTags, map[string]string{ + "tag03": "value03", + }); diff != "" { + t.Fatalf("unexpected azure tags: %s", diff) } } @@ -2047,8 +2072,8 @@ func TestConfig_PrepareProvidedWinRMPassword(t *testing.T) { } } -func getArmBuilderConfiguration() map[string]string { - m := make(map[string]string) +func getArmBuilderConfiguration() map[string]interface{} { + m := make(map[string]interface{}) for _, v := range requiredConfigValues { m[v] = "ignored00" } diff --git a/builder/azure/arm/step_create_resource_group.go b/builder/azure/arm/step_create_resource_group.go index b5be70452..f745d5054 100644 --- a/builder/azure/arm/step_create_resource_group.go +++ b/builder/azure/arm/step_create_resource_group.go @@ -61,7 +61,13 @@ func (s *StepCreateResourceGroup) Run(ctx context.Context, state multistep.State var resourceGroupName = state.Get(constants.ArmResourceGroupName).(string) var location = state.Get(constants.ArmLocation).(string) - var tags = state.Get(constants.ArmTags).(map[string]*string) + tags, ok := state.Get(constants.ArmTags).(map[string]*string) + if !ok { + err := fmt.Errorf("failed to extract tags from state bag") + state.Put(constants.Error, err) + s.error(err) + return multistep.ActionHalt + } exists, err := s.exists(ctx, resourceGroupName) if err != nil { diff --git a/builder/azure/arm/step_create_resource_group_test.go b/builder/azure/arm/step_create_resource_group_test.go index cb8707fbe..2073aa32c 100644 --- a/builder/azure/arm/step_create_resource_group_test.go +++ b/builder/azure/arm/step_create_resource_group_test.go @@ -220,3 +220,32 @@ func createTestExistingStateBagStepCreateResourceGroup() multistep.StateBag { stateBag.Put(constants.ArmTags, tags) return stateBag } + +func TestStepCreateResourceGroupShouldFailIfTagsFailCast(t *testing.T) { + stateBag := new(multistep.BasicStateBag) + + stateBag.Put(constants.ArmLocation, "Unit Test: Location") + stateBag.Put(constants.ArmResourceGroupName, "Unit Test: ResourceGroupName") + stateBag.Put(constants.ArmIsExistingResourceGroup, true) + + value := "Unit Test: Tags" + tags := map[string]string{ + "tag01": value, + } + + stateBag.Put(constants.ArmTags, tags) + var testSubject = &StepCreateResourceGroup{ + create: func(context.Context, string, string, map[string]*string) error { return nil }, + say: func(message string) {}, + error: func(e error) {}, + exists: func(context.Context, string) (bool, error) { return false, nil }, + } + var result = testSubject.Run(context.Background(), stateBag) + if result != multistep.ActionHalt { + t.Fatalf("Expected the step to return 'ActionHalt', but got '%d'.", result) + } + + if _, ok := stateBag.GetOk(constants.Error); ok == false { + t.Fatalf("Expected the step to set stateBag['%s'], but it was not.", constants.Error) + } +} diff --git a/builder/azure/common/map.go b/builder/azure/common/map.go new file mode 100644 index 000000000..318f2780b --- /dev/null +++ b/builder/azure/common/map.go @@ -0,0 +1,10 @@ +package common + +func MapToAzureTags(in map[string]string) map[string]*string { + res := map[string]*string{} + for k := range in { + v := in[k] + res[k] = &v + } + return res +} diff --git a/builder/azure/common/template/template.go b/builder/azure/common/template/template.go index dad684735..32fa39917 100644 --- a/builder/azure/common/template/template.go +++ b/builder/azure/common/template/template.go @@ -25,16 +25,16 @@ type Parameters struct { ///////////////////////////////////////////////// // Template > Resource type Resource struct { - ApiVersion *string `json:"apiVersion"` - Name *string `json:"name"` - Type *string `json:"type"` - Location *string `json:"location,omitempty"` - DependsOn *[]string `json:"dependsOn,omitempty"` - Plan *Plan `json:"plan,omitempty"` - Properties *Properties `json:"properties,omitempty"` - Tags *map[string]*string `json:"tags,omitempty"` - Resources *[]Resource `json:"resources,omitempty"` - Identity *Identity `json:"identity,omitempty"` + ApiVersion *string `json:"apiVersion"` + Name *string `json:"name"` + Type *string `json:"type"` + Location *string `json:"location,omitempty"` + DependsOn *[]string `json:"dependsOn,omitempty"` + Plan *Plan `json:"plan,omitempty"` + Properties *Properties `json:"properties,omitempty"` + Tags *map[string]string `json:"tags,omitempty"` + Resources *[]Resource `json:"resources,omitempty"` + Identity *Identity `json:"identity,omitempty"` } type Plan struct { diff --git a/builder/azure/common/template/template_builder.go b/builder/azure/common/template/template_builder.go index 754c2a91e..d4248d04b 100644 --- a/builder/azure/common/template/template_builder.go +++ b/builder/azure/common/template/template_builder.go @@ -374,7 +374,7 @@ func (s *TemplateBuilder) SetNetworkSecurityGroup(ipAddresses []string, port int return nil } -func (s *TemplateBuilder) SetTags(tags *map[string]*string) error { +func (s *TemplateBuilder) SetTags(tags *map[string]string) error { if tags == nil || len(*tags) == 0 { return nil } diff --git a/builder/cloudstack/config.hcl2spec.go b/builder/cloudstack/config.hcl2spec.go index 852e937f4..8c3c5c83e 100644 --- a/builder/cloudstack/config.hcl2spec.go +++ b/builder/cloudstack/config.hcl2spec.go @@ -20,6 +20,7 @@ type FlatConfig struct { HTTPPortMin *int `mapstructure:"http_port_min" cty:"http_port_min" hcl:"http_port_min"` HTTPPortMax *int `mapstructure:"http_port_max" cty:"http_port_max" hcl:"http_port_max"` HTTPAddress *string `mapstructure:"http_bind_address" cty:"http_bind_address" hcl:"http_bind_address"` + HTTPInterface *string `mapstructure:"http_interface" undocumented:"true" cty:"http_interface" hcl:"http_interface"` Type *string `mapstructure:"communicator" cty:"communicator" hcl:"communicator"` PauseBeforeConnect *string `mapstructure:"pause_before_connecting" cty:"pause_before_connecting" hcl:"pause_before_connecting"` SSHHost *string `mapstructure:"ssh_host" cty:"ssh_host" hcl:"ssh_host"` @@ -132,6 +133,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "http_port_min": &hcldec.AttrSpec{Name: "http_port_min", Type: cty.Number, Required: false}, "http_port_max": &hcldec.AttrSpec{Name: "http_port_max", Type: cty.Number, Required: false}, "http_bind_address": &hcldec.AttrSpec{Name: "http_bind_address", Type: cty.String, Required: false}, + "http_interface": &hcldec.AttrSpec{Name: "http_interface", Type: cty.String, Required: false}, "communicator": &hcldec.AttrSpec{Name: "communicator", Type: cty.String, Required: false}, "pause_before_connecting": &hcldec.AttrSpec{Name: "pause_before_connecting", Type: cty.String, Required: false}, "ssh_host": &hcldec.AttrSpec{Name: "ssh_host", Type: cty.String, Required: false}, diff --git a/builder/docker/artifact_import.go b/builder/docker/artifact_import.go index c626a9df3..a53c0a52b 100644 --- a/builder/docker/artifact_import.go +++ b/builder/docker/artifact_import.go @@ -30,19 +30,22 @@ func (a *ImportArtifact) Id() string { } func (a *ImportArtifact) String() string { - tags := a.StateData["docker_tags"] - if tags == nil { - return fmt.Sprintf("Imported Docker image: %s", a.Id()) - } - cast := tags.([]interface{}) - names := []string{} - for _, name := range cast { - if n, ok := name.(string); ok { - names = append(names, n) + var tags []string + switch t := a.StateData["docker_tags"].(type) { + case []string: + tags = t + case []interface{}: + for _, name := range t { + if n, ok := name.(string); ok { + tags = append(tags, n) + } } } - return fmt.Sprintf("Imported Docker image: %s with tags %s", - a.Id(), strings.Join(names, " ")) + if len(tags) > 0 { + return fmt.Sprintf("Imported Docker image: %s with tags %s", + a.Id(), strings.Join(tags, " ")) + } + return fmt.Sprintf("Imported Docker image: %s", a.Id()) } func (a *ImportArtifact) State(name string) interface{} { diff --git a/builder/docker/builder.go b/builder/docker/builder.go index 3b6ae22f5..a3f807da4 100644 --- a/builder/docker/builder.go +++ b/builder/docker/builder.go @@ -5,6 +5,7 @@ import ( "log" "github.com/hashicorp/hcl/v2/hcldec" + "github.com/hashicorp/packer/builder" "github.com/hashicorp/packer/common" "github.com/hashicorp/packer/helper/communicator" "github.com/hashicorp/packer/helper/multistep" @@ -29,7 +30,9 @@ func (b *Builder) Prepare(raws ...interface{}) ([]string, []string, error) { return nil, warnings, errs } - return nil, warnings, nil + return []string{ + "ImageSha256", + }, warnings, nil } func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) { @@ -44,6 +47,16 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack } log.Printf("[DEBUG] Docker version: %s", version.String()) + // Setup the state bag and initial state for the steps + state := new(multistep.BasicStateBag) + state.Put("config", &b.config) + state.Put("hook", hook) + state.Put("ui", ui) + generatedData := &builder.GeneratedData{State: state} + + // Setup the driver that will talk to Docker + state.Put("driver", driver) + steps := []multistep.Step{ &StepTempDir{}, &StepPull{}, @@ -67,7 +80,11 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack log.Print("[DEBUG] Container will be discarded") } else if b.config.Commit { log.Print("[DEBUG] Container will be committed") - steps = append(steps, new(StepCommit)) + steps = append(steps, + new(StepCommit), + &StepSetGeneratedData{ // Adds ImageSha256 variable available after StepCommit + GeneratedData: generatedData, + }) } else if b.config.ExportPath != "" { log.Printf("[DEBUG] Container will be exported to %s", b.config.ExportPath) steps = append(steps, new(StepExport)) @@ -75,15 +92,6 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack return nil, errArtifactNotUsed } - // Setup the state bag and initial state for the steps - state := new(multistep.BasicStateBag) - state.Put("config", &b.config) - state.Put("hook", hook) - state.Put("ui", ui) - - // Setup the driver that will talk to Docker - state.Put("driver", driver) - // Run! b.runner = common.NewRunner(steps, b.config.PackerConfig, ui) b.runner.Run(ctx, state) diff --git a/builder/docker/driver.go b/builder/docker/driver.go index 816c49f1a..43effdf8e 100644 --- a/builder/docker/driver.go +++ b/builder/docker/driver.go @@ -26,6 +26,9 @@ type Driver interface { // for external access. IPAddress(id string) (string, error) + // Sha256 returns the sha256 id of the image + Sha256(id string) (string, error) + // Login. This will lock the driver from performing another Login // until Logout is called. Therefore, any users MUST call Logout. Login(repo, username, password string) error diff --git a/builder/docker/driver_docker.go b/builder/docker/driver_docker.go index 10e78c7d3..ba5693b91 100644 --- a/builder/docker/driver_docker.go +++ b/builder/docker/driver_docker.go @@ -159,6 +159,23 @@ func (d *DockerDriver) IPAddress(id string) (string, error) { return strings.TrimSpace(stdout.String()), nil } +func (d *DockerDriver) Sha256(id string) (string, error) { + var stderr, stdout bytes.Buffer + cmd := exec.Command( + "docker", + "inspect", + "--format", + "{{ .Id }}", + id) + cmd.Stdout = &stdout + cmd.Stderr = &stderr + if err := cmd.Run(); err != nil { + return "", fmt.Errorf("Error: %s\n\nStderr: %s", err, stderr.String()) + } + + return strings.TrimSpace(stdout.String()), nil +} + func (d *DockerDriver) Login(repo, user, pass string) error { d.l.Lock() diff --git a/builder/docker/driver_mock.go b/builder/docker/driver_mock.go index 71af7f9a0..b4e3036f6 100644 --- a/builder/docker/driver_mock.go +++ b/builder/docker/driver_mock.go @@ -28,6 +28,11 @@ type MockDriver struct { IPAddressResult string IPAddressErr error + Sha256Called bool + Sha256Id string + Sha256Result string + Sha256Err error + KillCalled bool KillID string KillError error @@ -118,6 +123,12 @@ func (d *MockDriver) IPAddress(id string) (string, error) { return d.IPAddressResult, d.IPAddressErr } +func (d *MockDriver) Sha256(id string) (string, error) { + d.Sha256Called = true + d.Sha256Id = id + return d.Sha256Result, d.Sha256Err +} + func (d *MockDriver) Login(r, u, p string) error { d.LoginCalled = true d.LoginRepo = r diff --git a/builder/docker/step_set_generated_data.go b/builder/docker/step_set_generated_data.go new file mode 100644 index 000000000..5ab9df8b9 --- /dev/null +++ b/builder/docker/step_set_generated_data.go @@ -0,0 +1,30 @@ +package docker + +import ( + "context" + + "github.com/hashicorp/packer/builder" + "github.com/hashicorp/packer/helper/multistep" +) + +type StepSetGeneratedData struct { + GeneratedData *builder.GeneratedData +} + +func (s *StepSetGeneratedData) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { + driver := state.Get("driver").(Driver) + + sha256 := "ERR_IMAGE_SHA256_NOT_FOUND" + if imageId, ok := state.GetOk("image_id"); ok { + s256, err := driver.Sha256(imageId.(string)) + if err == nil { + sha256 = s256 + } + } + s.GeneratedData.Put("ImageSha256", sha256) + return multistep.ActionContinue +} + +func (s *StepSetGeneratedData) Cleanup(_ multistep.StateBag) { + // No cleanup... +} diff --git a/builder/docker/step_set_generated_data_test.go b/builder/docker/step_set_generated_data_test.go new file mode 100644 index 000000000..b1e5e2bea --- /dev/null +++ b/builder/docker/step_set_generated_data_test.go @@ -0,0 +1,51 @@ +package docker + +import ( + "context" + "testing" + + "github.com/hashicorp/packer/builder" + "github.com/hashicorp/packer/helper/multistep" +) + +func TestStepSetGeneratedData_Run(t *testing.T) { + state := testState(t) + step := new(StepSetGeneratedData) + step.GeneratedData = &builder.GeneratedData{State: state} + driver := state.Get("driver").(*MockDriver) + driver.Sha256Result = "80B3BB1B1696E73A9B19DEEF92F664F8979F948DF348088B61F9A3477655AF64" + state.Put("image_id", "12345") + + if action := step.Run(context.TODO(), state); action != multistep.ActionContinue { + t.Fatalf("Should not halt") + } + if !driver.Sha256Called { + t.Fatalf("driver.SHA256 should be called") + } + if driver.Sha256Id != "12345" { + t.Fatalf("driver.SHA256 got wrong image it: %s", driver.Sha256Id) + } + genData := state.Get("generated_data").(map[string]interface{}) + imgSha256 := genData["ImageSha256"].(string) + if imgSha256 != driver.Sha256Result { + t.Fatalf("Expected ImageSha256 to be %s but was %s", driver.Sha256Result, imgSha256) + } + + // Image ID not implement + state = testState(t) + step.GeneratedData = &builder.GeneratedData{State: state} + driver = state.Get("driver").(*MockDriver) + notImplementedMsg := "ERR_IMAGE_SHA256_NOT_FOUND" + + if action := step.Run(context.TODO(), state); action != multistep.ActionContinue { + t.Fatalf("Should not halt") + } + if driver.Sha256Called { + t.Fatalf("driver.SHA256 should not be called") + } + genData = state.Get("generated_data").(map[string]interface{}) + imgSha256 = genData["ImageSha256"].(string) + if imgSha256 != notImplementedMsg { + t.Fatalf("Expected ImageSha256 to be %s but was %s", notImplementedMsg, imgSha256) + } +} diff --git a/builder/googlecompute/driver_gce.go b/builder/googlecompute/driver_gce.go index 3fca1f6b1..ac60655e4 100644 --- a/builder/googlecompute/driver_gce.go +++ b/builder/googlecompute/driver_gce.go @@ -15,6 +15,7 @@ import ( "time" compute "google.golang.org/api/compute/v1" + "google.golang.org/api/option" oslogin "google.golang.org/api/oslogin/v1" "github.com/hashicorp/packer/common/retry" @@ -124,12 +125,12 @@ func NewDriverGCE(ui packer.Ui, p string, conf *jwt.Config, vaultOauth string) ( } log.Printf("[INFO] Instantiating GCE client...") - service, err := compute.New(client) + service, err := compute.NewService(context.TODO(), option.WithHTTPClient(client)) if err != nil { return nil, err } - osLoginService, err := oslogin.New(client) + osLoginService, err := oslogin.NewService(context.TODO(), option.WithHTTPClient(client)) if err != nil { return nil, err } diff --git a/builder/hyperv/common/config.go b/builder/hyperv/common/config.go index 53a3e9e8a..5ccd5d453 100644 --- a/builder/hyperv/common/config.go +++ b/builder/hyperv/common/config.go @@ -37,6 +37,7 @@ const ( type CommonConfig struct { common.FloppyConfig `mapstructure:",squash"` + common.CDConfig `mapstructure:",squash"` // The block size of the VHD to be created. // Recommended disk block size for Linux hyper-v guests is 1 MiB. This // defaults to "32" MiB. @@ -210,8 +211,8 @@ func (c *CommonConfig) Prepare(ctx *interpolate.Context, pc *common.PackerConfig } // Errors - floppyerrs := c.FloppyConfig.Prepare(ctx) - errs = append(errs, floppyerrs...) + errs = append(errs, c.FloppyConfig.Prepare(ctx)...) + errs = append(errs, c.CDConfig.Prepare(ctx)...) if c.GuestAdditionsMode == "" { if c.GuestAdditionsPath != "" { c.GuestAdditionsMode = "attach" diff --git a/builder/hyperv/common/step_mount_secondary_dvd_images.go b/builder/hyperv/common/step_mount_secondary_dvd_images.go index 4303f51f4..a6cbd7e6b 100644 --- a/builder/hyperv/common/step_mount_secondary_dvd_images.go +++ b/builder/hyperv/common/step_mount_secondary_dvd_images.go @@ -34,7 +34,17 @@ func (s *StepMountSecondaryDvdImages) Run(ctx context.Context, state multistep.S // For IDE, there are only 2 controllers (0,1) with 2 locations each (0,1) var dvdProperties []DvdControllerProperties - for _, isoPath := range s.IsoPaths { + isoPaths := s.IsoPaths + + // Add our custom CD, if it exists + cd_path, ok := state.Get("cd_path").(string) + if ok { + if cd_path != "" { + isoPaths = append(isoPaths, cd_path) + } + } + + for _, isoPath := range isoPaths { var properties DvdControllerProperties controllerNumber, controllerLocation, err := driver.CreateDvdDrive(vmName, isoPath, s.Generation) diff --git a/builder/hyperv/iso/builder.go b/builder/hyperv/iso/builder.go index 7af2ab1ba..25284b0b2 100644 --- a/builder/hyperv/iso/builder.go +++ b/builder/hyperv/iso/builder.go @@ -254,7 +254,10 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack GuestAdditionsPath: b.config.GuestAdditionsPath, Generation: b.config.Generation, }, - + &common.StepCreateCD{ + Files: b.config.CDConfig.CDFiles, + Label: b.config.CDConfig.CDLabel, + }, &hypervcommon.StepMountSecondaryDvdImages{ IsoPaths: b.config.SecondaryDvdImages, Generation: b.config.Generation, diff --git a/builder/hyperv/iso/builder.hcl2spec.go b/builder/hyperv/iso/builder.hcl2spec.go index 42a7b2c40..1af444494 100644 --- a/builder/hyperv/iso/builder.hcl2spec.go +++ b/builder/hyperv/iso/builder.hcl2spec.go @@ -20,6 +20,7 @@ type FlatConfig struct { HTTPPortMin *int `mapstructure:"http_port_min" cty:"http_port_min" hcl:"http_port_min"` HTTPPortMax *int `mapstructure:"http_port_max" cty:"http_port_max" hcl:"http_port_max"` HTTPAddress *string `mapstructure:"http_bind_address" cty:"http_bind_address" hcl:"http_bind_address"` + HTTPInterface *string `mapstructure:"http_interface" undocumented:"true" cty:"http_interface" hcl:"http_interface"` ISOChecksum *string `mapstructure:"iso_checksum" required:"true" cty:"iso_checksum" hcl:"iso_checksum"` RawSingleISOUrl *string `mapstructure:"iso_url" required:"true" cty:"iso_url" hcl:"iso_url"` ISOUrls []string `mapstructure:"iso_urls" cty:"iso_urls" hcl:"iso_urls"` @@ -79,6 +80,8 @@ type FlatConfig struct { FloppyFiles []string `mapstructure:"floppy_files" cty:"floppy_files" hcl:"floppy_files"` FloppyDirectories []string `mapstructure:"floppy_dirs" cty:"floppy_dirs" hcl:"floppy_dirs"` FloppyLabel *string `mapstructure:"floppy_label" cty:"floppy_label" hcl:"floppy_label"` + CDFiles []string `mapstructure:"cd_files" cty:"cd_files" hcl:"cd_files"` + CDLabel *string `mapstructure:"cd_label" cty:"cd_label" hcl:"cd_label"` DiskBlockSize *uint `mapstructure:"disk_block_size" required:"false" cty:"disk_block_size" hcl:"disk_block_size"` RamSize *uint `mapstructure:"memory" required:"false" cty:"memory" hcl:"memory"` SecondaryDvdImages []string `mapstructure:"secondary_iso_images" required:"false" cty:"secondary_iso_images" hcl:"secondary_iso_images"` @@ -136,6 +139,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "http_port_min": &hcldec.AttrSpec{Name: "http_port_min", Type: cty.Number, Required: false}, "http_port_max": &hcldec.AttrSpec{Name: "http_port_max", Type: cty.Number, Required: false}, "http_bind_address": &hcldec.AttrSpec{Name: "http_bind_address", Type: cty.String, Required: false}, + "http_interface": &hcldec.AttrSpec{Name: "http_interface", Type: cty.String, Required: false}, "iso_checksum": &hcldec.AttrSpec{Name: "iso_checksum", Type: cty.String, Required: false}, "iso_url": &hcldec.AttrSpec{Name: "iso_url", Type: cty.String, Required: false}, "iso_urls": &hcldec.AttrSpec{Name: "iso_urls", Type: cty.List(cty.String), Required: false}, @@ -195,6 +199,8 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "floppy_files": &hcldec.AttrSpec{Name: "floppy_files", Type: cty.List(cty.String), Required: false}, "floppy_dirs": &hcldec.AttrSpec{Name: "floppy_dirs", Type: cty.List(cty.String), Required: false}, "floppy_label": &hcldec.AttrSpec{Name: "floppy_label", Type: cty.String, Required: false}, + "cd_files": &hcldec.AttrSpec{Name: "cd_files", Type: cty.List(cty.String), Required: false}, + "cd_label": &hcldec.AttrSpec{Name: "cd_label", Type: cty.String, Required: false}, "disk_block_size": &hcldec.AttrSpec{Name: "disk_block_size", Type: cty.Number, Required: false}, "memory": &hcldec.AttrSpec{Name: "memory", Type: cty.Number, Required: false}, "secondary_iso_images": &hcldec.AttrSpec{Name: "secondary_iso_images", Type: cty.List(cty.String), Required: false}, diff --git a/builder/hyperv/vmcx/builder.go b/builder/hyperv/vmcx/builder.go index bcf7cb277..b99317695 100644 --- a/builder/hyperv/vmcx/builder.go +++ b/builder/hyperv/vmcx/builder.go @@ -294,7 +294,10 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack GuestAdditionsPath: b.config.GuestAdditionsPath, Generation: b.config.Generation, }, - + &common.StepCreateCD{ + Files: b.config.CDConfig.CDFiles, + Label: b.config.CDConfig.CDLabel, + }, &hypervcommon.StepMountSecondaryDvdImages{ IsoPaths: b.config.SecondaryDvdImages, Generation: b.config.Generation, diff --git a/builder/hyperv/vmcx/builder.hcl2spec.go b/builder/hyperv/vmcx/builder.hcl2spec.go index ff9806d9e..80f170200 100644 --- a/builder/hyperv/vmcx/builder.hcl2spec.go +++ b/builder/hyperv/vmcx/builder.hcl2spec.go @@ -20,6 +20,7 @@ type FlatConfig struct { HTTPPortMin *int `mapstructure:"http_port_min" cty:"http_port_min" hcl:"http_port_min"` HTTPPortMax *int `mapstructure:"http_port_max" cty:"http_port_max" hcl:"http_port_max"` HTTPAddress *string `mapstructure:"http_bind_address" cty:"http_bind_address" hcl:"http_bind_address"` + HTTPInterface *string `mapstructure:"http_interface" undocumented:"true" cty:"http_interface" hcl:"http_interface"` ISOChecksum *string `mapstructure:"iso_checksum" required:"true" cty:"iso_checksum" hcl:"iso_checksum"` RawSingleISOUrl *string `mapstructure:"iso_url" required:"true" cty:"iso_url" hcl:"iso_url"` ISOUrls []string `mapstructure:"iso_urls" cty:"iso_urls" hcl:"iso_urls"` @@ -79,6 +80,8 @@ type FlatConfig struct { FloppyFiles []string `mapstructure:"floppy_files" cty:"floppy_files" hcl:"floppy_files"` FloppyDirectories []string `mapstructure:"floppy_dirs" cty:"floppy_dirs" hcl:"floppy_dirs"` FloppyLabel *string `mapstructure:"floppy_label" cty:"floppy_label" hcl:"floppy_label"` + CDFiles []string `mapstructure:"cd_files" cty:"cd_files" hcl:"cd_files"` + CDLabel *string `mapstructure:"cd_label" cty:"cd_label" hcl:"cd_label"` DiskBlockSize *uint `mapstructure:"disk_block_size" required:"false" cty:"disk_block_size" hcl:"disk_block_size"` RamSize *uint `mapstructure:"memory" required:"false" cty:"memory" hcl:"memory"` SecondaryDvdImages []string `mapstructure:"secondary_iso_images" required:"false" cty:"secondary_iso_images" hcl:"secondary_iso_images"` @@ -138,6 +141,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "http_port_min": &hcldec.AttrSpec{Name: "http_port_min", Type: cty.Number, Required: false}, "http_port_max": &hcldec.AttrSpec{Name: "http_port_max", Type: cty.Number, Required: false}, "http_bind_address": &hcldec.AttrSpec{Name: "http_bind_address", Type: cty.String, Required: false}, + "http_interface": &hcldec.AttrSpec{Name: "http_interface", Type: cty.String, Required: false}, "iso_checksum": &hcldec.AttrSpec{Name: "iso_checksum", Type: cty.String, Required: false}, "iso_url": &hcldec.AttrSpec{Name: "iso_url", Type: cty.String, Required: false}, "iso_urls": &hcldec.AttrSpec{Name: "iso_urls", Type: cty.List(cty.String), Required: false}, @@ -197,6 +201,8 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "floppy_files": &hcldec.AttrSpec{Name: "floppy_files", Type: cty.List(cty.String), Required: false}, "floppy_dirs": &hcldec.AttrSpec{Name: "floppy_dirs", Type: cty.List(cty.String), Required: false}, "floppy_label": &hcldec.AttrSpec{Name: "floppy_label", Type: cty.String, Required: false}, + "cd_files": &hcldec.AttrSpec{Name: "cd_files", Type: cty.List(cty.String), Required: false}, + "cd_label": &hcldec.AttrSpec{Name: "cd_label", Type: cty.String, Required: false}, "disk_block_size": &hcldec.AttrSpec{Name: "disk_block_size", Type: cty.Number, Required: false}, "memory": &hcldec.AttrSpec{Name: "memory", Type: cty.Number, Required: false}, "secondary_iso_images": &hcldec.AttrSpec{Name: "secondary_iso_images", Type: cty.List(cty.String), Required: false}, diff --git a/builder/openstack/access_config.go b/builder/openstack/access_config.go index 87aee9f3b..0fe669666 100644 --- a/builder/openstack/access_config.go +++ b/builder/openstack/access_config.go @@ -3,16 +3,20 @@ package openstack import ( + "bytes" "crypto/tls" "crypto/x509" "fmt" + "io" "io/ioutil" + "net/http" "os" "github.com/gophercloud/gophercloud" "github.com/gophercloud/gophercloud/openstack" "github.com/gophercloud/utils/openstack/clientconfig" "github.com/hashicorp/go-cleanhttp" + "github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/template/interpolate" ) @@ -236,6 +240,15 @@ func (c *AccessConfig) Prepare(ctx *interpolate.Context) []error { return nil } +func (c *AccessConfig) enableDebug(ui packer.Ui) { + c.osClient.HTTPClient = http.Client{ + Transport: &DebugRoundTripper{ + ui: ui, + rt: c.osClient.HTTPClient.Transport, + }, + } +} + func (c *AccessConfig) computeV2Client() (*gophercloud.ServiceClient, error) { return openstack.NewComputeV2(c.osClient, gophercloud.EndpointOpts{ Region: c.Region, @@ -273,3 +286,49 @@ func (c *AccessConfig) getEndpointType() gophercloud.Availability { } return gophercloud.AvailabilityPublic } + +type DebugRoundTripper struct { + ui packer.Ui + rt http.RoundTripper + numReauthAttempts int +} + +// RoundTrip performs a round-trip HTTP request and logs relevant information about it. +func (drt *DebugRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) { + defer func() { + if request.Body != nil { + request.Body.Close() + } + }() + + var response *http.Response + var err error + + response, err = drt.rt.RoundTrip(request) + if response == nil { + return nil, err + } + + if response.StatusCode == http.StatusUnauthorized { + if drt.numReauthAttempts == 3 { + return response, fmt.Errorf("Tried to re-authenticate 3 times with no success.") + } + drt.numReauthAttempts++ + } + + drt.DebugMessage(fmt.Sprintf("Request %s %s %d", request.Method, request.URL, response.StatusCode)) + + if response.StatusCode >= 400 { + buf := bytes.NewBuffer([]byte{}) + body, _ := ioutil.ReadAll(io.TeeReader(response.Body, buf)) + drt.DebugMessage(fmt.Sprintf("Response Error: %+v\n", string(body))) + bufWithClose := ioutil.NopCloser(buf) + response.Body = bufWithClose + } + + return response, err +} + +func (drt *DebugRoundTripper) DebugMessage(message string) { + drt.ui.Message(fmt.Sprintf("[DEBUG] %s", message)) +} diff --git a/builder/openstack/builder.go b/builder/openstack/builder.go index 49267afef..432e0810f 100644 --- a/builder/openstack/builder.go +++ b/builder/openstack/builder.go @@ -71,6 +71,10 @@ func (b *Builder) Prepare(raws ...interface{}) ([]string, []string, error) { } func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) { + if b.config.PackerDebug { + b.config.enableDebug(ui) + } + computeClient, err := b.config.computeV2Client() if err != nil { return nil, fmt.Errorf("Error initializing compute client: %s", err) @@ -98,11 +102,13 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack DebugKeyPath: fmt.Sprintf("os_%s.pem", b.config.PackerBuildName), }, &StepSourceImageInfo{ - SourceImage: b.config.RunConfig.SourceImage, - SourceImageName: b.config.RunConfig.SourceImageName, - SourceImageOpts: b.config.RunConfig.sourceImageOpts, - SourceMostRecent: b.config.SourceImageFilters.MostRecent, - SourceProperties: b.config.SourceImageFilters.Filters.Properties, + SourceImage: b.config.RunConfig.SourceImage, + SourceImageName: b.config.RunConfig.SourceImageName, + ExternalSourceImageURL: b.config.RunConfig.ExternalSourceImageURL, + ExternalSourceImageFormat: b.config.RunConfig.ExternalSourceImageFormat, + SourceImageOpts: b.config.RunConfig.sourceImageOpts, + SourceMostRecent: b.config.SourceImageFilters.MostRecent, + SourceProperties: b.config.SourceImageFilters.Filters.Properties, }, &StepDiscoverNetwork{ Networks: b.config.Networks, diff --git a/builder/openstack/builder.hcl2spec.go b/builder/openstack/builder.hcl2spec.go index ee42025b9..7f8f50e99 100644 --- a/builder/openstack/builder.hcl2spec.go +++ b/builder/openstack/builder.hcl2spec.go @@ -95,6 +95,8 @@ type FlatConfig struct { SSHIPVersion *string `mapstructure:"ssh_ip_version" required:"false" cty:"ssh_ip_version" hcl:"ssh_ip_version"` SourceImage *string `mapstructure:"source_image" required:"true" cty:"source_image" hcl:"source_image"` SourceImageName *string `mapstructure:"source_image_name" required:"true" cty:"source_image_name" hcl:"source_image_name"` + ExternalSourceImageURL *string `mapstructure:"external_source_image_url" required:"true" cty:"external_source_image_url" hcl:"external_source_image_url"` + ExternalSourceImageFormat *string `mapstructure:"external_source_image_format" required:"false" cty:"external_source_image_format" hcl:"external_source_image_format"` SourceImageFilters *FlatImageFilter `mapstructure:"source_image_filter" required:"true" cty:"source_image_filter" hcl:"source_image_filter"` Flavor *string `mapstructure:"flavor" required:"true" cty:"flavor" hcl:"flavor"` AvailabilityZone *string `mapstructure:"availability_zone" required:"false" cty:"availability_zone" hcl:"availability_zone"` @@ -220,6 +222,8 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "ssh_ip_version": &hcldec.AttrSpec{Name: "ssh_ip_version", Type: cty.String, Required: false}, "source_image": &hcldec.AttrSpec{Name: "source_image", Type: cty.String, Required: false}, "source_image_name": &hcldec.AttrSpec{Name: "source_image_name", Type: cty.String, Required: false}, + "external_source_image_url": &hcldec.AttrSpec{Name: "external_source_image_url", Type: cty.String, Required: false}, + "external_source_image_format": &hcldec.AttrSpec{Name: "external_source_image_format", Type: cty.String, Required: false}, "source_image_filter": &hcldec.BlockSpec{TypeName: "source_image_filter", Nested: hcldec.ObjectSpec((*FlatImageFilter)(nil).HCL2Spec())}, "flavor": &hcldec.AttrSpec{Name: "flavor", Type: cty.String, Required: false}, "availability_zone": &hcldec.AttrSpec{Name: "availability_zone", Type: cty.String, Required: false}, diff --git a/builder/openstack/run_config.go b/builder/openstack/run_config.go index c03e55481..0625d264c 100644 --- a/builder/openstack/run_config.go +++ b/builder/openstack/run_config.go @@ -33,6 +33,11 @@ type RunConfig struct { // The name of the base image to use. This is an alternative way of // providing source_image and only either of them can be specified. SourceImageName string `mapstructure:"source_image_name" required:"true"` + // The URL of an external base image to use. This is an alternative way of + // providing source_image and only either of them can be specified. + ExternalSourceImageURL string `mapstructure:"external_source_image_url" required:"true"` + // The format of the external source image to use, e.g. qcow2, raw. + ExternalSourceImageFormat string `mapstructure:"external_source_image_format" required:"false"` // Filters used to populate filter options. Example: // // ```json @@ -247,10 +252,19 @@ func (c *RunConfig) Prepare(ctx *interpolate.Context) []error { } } - if c.SourceImage == "" && c.SourceImageName == "" && c.SourceImageFilters.Filters.Empty() { - errs = append(errs, errors.New("Either a source_image, a source_image_name, or source_image_filter must be specified")) - } else if len(c.SourceImage) > 0 && len(c.SourceImageName) > 0 { - errs = append(errs, errors.New("Only a source_image or a source_image_name can be specified, not both.")) + hasOnlySourceImage := len(c.SourceImage) > 0 && len(c.SourceImageName) == 0 && len(c.ExternalSourceImageURL) == 0 + hasOnlySourceImageName := len(c.SourceImageName) > 0 && len(c.SourceImage) == 0 && len(c.ExternalSourceImageURL) == 0 + hasOnlyExternalSourceImageURL := len(c.ExternalSourceImageURL) > 0 && len(c.SourceImage) == 0 && len(c.SourceImageName) == 0 + + if c.SourceImage == "" && c.SourceImageName == "" && c.ExternalSourceImageURL == "" && c.SourceImageFilters.Filters.Empty() { + errs = append(errs, errors.New("Either a source_image, a source_image_name, an external_source_image_url or source_image_filter must be specified")) + } else if !(hasOnlySourceImage || hasOnlySourceImageName || hasOnlyExternalSourceImageURL) { + errs = append(errs, errors.New("Only a source_image, a source_image_name or an external_source_image_url can be specified, not multiple.")) + } + + // if external_source_image_format is not set use qcow2 as default + if c.ExternalSourceImageFormat == "" { + c.ExternalSourceImageFormat = "qcow2" } if c.Flavor == "" { @@ -283,9 +297,9 @@ func (c *RunConfig) Prepare(ctx *interpolate.Context) []error { } } - // if neither ID or image name is provided outside the filter, build the - // filter - if len(c.SourceImage) == 0 && len(c.SourceImageName) == 0 { + // if neither ID, image name or external image URL is provided outside the filter, + // build the filter + if len(c.SourceImage) == 0 && len(c.SourceImageName) == 0 && len(c.ExternalSourceImageURL) == 0 { listOpts, filterErr := c.SourceImageFilters.Filters.Build() @@ -295,6 +309,11 @@ func (c *RunConfig) Prepare(ctx *interpolate.Context) []error { c.sourceImageOpts = *listOpts } + // if c.ExternalSourceImageURL is set use a generated source image name + if c.ExternalSourceImageURL != "" { + c.SourceImageName = fmt.Sprintf("packer_%s", uuid.TimeOrderedUUID()) + } + return errs } diff --git a/builder/openstack/run_config_test.go b/builder/openstack/run_config_test.go index bf08f209c..dc267076b 100644 --- a/builder/openstack/run_config_test.go +++ b/builder/openstack/run_config_test.go @@ -2,6 +2,7 @@ package openstack import ( "os" + "regexp" "testing" "github.com/gophercloud/gophercloud/openstack/imageservice/v2/images" @@ -132,6 +133,49 @@ func TestRunConfigPrepare_FloatingIPPoolCompat(t *testing.T) { } } +func TestRunConfigPrepare_ExternalSourceImageURL(t *testing.T) { + c := testRunConfig() + // test setting both ExternalSourceImageURL and SourceImage causes an error + c.ExternalSourceImageURL = "http://example.com/image.qcow2" + if err := c.Prepare(nil); len(err) != 1 { + t.Fatalf("err: %s", err) + } + + // test setting both ExternalSourceImageURL and SourceImageName causes an error + c.SourceImage = "" + c.SourceImageName = "abcd" + c.ExternalSourceImageURL = "http://example.com/image.qcow2" + if err := c.Prepare(nil); len(err) != 1 { + t.Fatalf("err: %s", err) + } + + // test neither setting SourceImage, SourceImageName or ExternalSourceImageURL causes an error + c.SourceImage = "" + c.SourceImageName = "" + c.ExternalSourceImageURL = "" + if err := c.Prepare(nil); len(err) != 1 { + t.Fatalf("err: %s", err) + } + + // test setting only ExternalSourceImageURL passes + c.SourceImage = "" + c.SourceImageName = "" + c.ExternalSourceImageURL = "http://example.com/image.qcow2" + if err := c.Prepare(nil); len(err) != 0 { + t.Fatalf("err: %s", err) + } + + // test default values + if c.ExternalSourceImageFormat != "qcow2" { + t.Fatalf("ExternalSourceImageFormat should have been set to default: qcow2") + } + + p := `packer_[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}` + if matches, _ := regexp.MatchString(p, c.SourceImageName); !matches { + t.Fatalf("invalid format for SourceImageName: %s", c.SourceImageName) + } +} + // This test case confirms that only allowed fields will be set to values // The checked values are non-nil for their target type func TestBuildImageFilter(t *testing.T) { diff --git a/builder/openstack/step_source_image_info.go b/builder/openstack/step_source_image_info.go index 4b40ea111..5344431fd 100644 --- a/builder/openstack/step_source_image_info.go +++ b/builder/openstack/step_source_image_info.go @@ -4,7 +4,9 @@ import ( "context" "fmt" "log" + "time" + "github.com/gophercloud/gophercloud/openstack/imageservice/v2/imageimport" "github.com/gophercloud/gophercloud/openstack/imageservice/v2/images" "github.com/gophercloud/gophercloud/pagination" "github.com/hashicorp/packer/helper/multistep" @@ -12,11 +14,13 @@ import ( ) type StepSourceImageInfo struct { - SourceImage string - SourceImageName string - SourceImageOpts images.ListOpts - SourceMostRecent bool - SourceProperties map[string]string + SourceImage string + SourceImageName string + ExternalSourceImageURL string + ExternalSourceImageFormat string + SourceImageOpts images.ListOpts + SourceMostRecent bool + SourceProperties map[string]string } func PropertiesSatisfied(image *images.Image, props *map[string]string) bool { @@ -33,12 +37,6 @@ func (s *StepSourceImageInfo) Run(ctx context.Context, state multistep.StateBag) config := state.Get("config").(*Config) ui := state.Get("ui").(packer.Ui) - if s.SourceImage != "" { - state.Put("source_image", s.SourceImage) - - return multistep.ActionContinue - } - client, err := config.imageV2Client() if err != nil { err := fmt.Errorf("error creating image client: %s", err) @@ -47,6 +45,70 @@ func (s *StepSourceImageInfo) Run(ctx context.Context, state multistep.StateBag) return multistep.ActionHalt } + if s.ExternalSourceImageURL != "" { + createOpts := images.CreateOpts{ + Name: s.SourceImageName, + ContainerFormat: "bare", + DiskFormat: s.ExternalSourceImageFormat, + Properties: map[string]string{ + "packer_external_source_image_url": s.ExternalSourceImageURL, + "packer_external_source_image_format": s.ExternalSourceImageFormat, + }, + } + + ui.Say("Creating image using external source image with name " + s.SourceImageName) + ui.Say("Using disk format " + s.ExternalSourceImageFormat) + image, err := images.Create(client, createOpts).Extract() + + if err != nil { + err := fmt.Errorf("Error creating source image: %s", err) + state.Put("error", err) + ui.Error(err.Error()) + return multistep.ActionHalt + } + + ui.Say("Created image with ID " + image.ID) + + importOpts := imageimport.CreateOpts{ + Name: imageimport.WebDownloadMethod, + URI: s.ExternalSourceImageURL, + } + + ui.Say("Importing External Source Image from URL " + s.ExternalSourceImageURL) + err = imageimport.Create(client, image.ID, importOpts).ExtractErr() + + if err != nil { + err := fmt.Errorf("Error importing source image: %s", err) + state.Put("error", err) + ui.Error(err.Error()) + return multistep.ActionHalt + } + + for image.Status != images.ImageStatusActive { + ui.Message("Image not Active, retrying in 10 seconds") + time.Sleep(10 * time.Second) + + img, err := images.Get(client, image.ID).Extract() + + if err != nil { + err := fmt.Errorf("Error querying image: %s", err) + state.Put("error", err) + ui.Error(err.Error()) + return multistep.ActionHalt + } + + image = img + } + + s.SourceImage = image.ID + } + + if s.SourceImage != "" { + state.Put("source_image", s.SourceImage) + + return multistep.ActionContinue + } + if s.SourceImageName != "" { s.SourceImageOpts = images.ListOpts{ Name: s.SourceImageName, @@ -117,5 +179,25 @@ func (s *StepSourceImageInfo) Run(ctx context.Context, state multistep.StateBag) } func (s *StepSourceImageInfo) Cleanup(state multistep.StateBag) { - // No cleanup required for backout + if s.ExternalSourceImageURL != "" { + config := state.Get("config").(*Config) + ui := state.Get("ui").(packer.Ui) + + client, err := config.imageV2Client() + if err != nil { + err := fmt.Errorf("error creating image client: %s", err) + state.Put("error", err) + ui.Error(err.Error()) + return + } + + ui.Say(fmt.Sprintf("Deleting temporary external source image: %s ...", s.SourceImageName)) + err = images.Delete(client, s.SourceImage).ExtractErr() + if err != nil { + err := fmt.Errorf("error cleaning up external source image: %s", err) + state.Put("error", err) + ui.Error(err.Error()) + return + } + } } diff --git a/builder/oracle/oci/config.go b/builder/oracle/oci/config.go index c6ca467e8..0b3eb9bff 100644 --- a/builder/oracle/oci/config.go +++ b/builder/oracle/oci/config.go @@ -1,4 +1,4 @@ -//go:generate mapstructure-to-hcl2 -type Config +//go:generate mapstructure-to-hcl2 -type Config,CreateVNICDetails package oci @@ -22,6 +22,19 @@ import ( ociauth "github.com/oracle/oci-go-sdk/common/auth" ) +type CreateVNICDetails struct { + // fields that can be specified under "create_vnic_details" + AssignPublicIp *bool `mapstructure:"assign_public_ip" required:"false"` + DefinedTags map[string]map[string]interface{} `mapstructure:"defined_tags" required:"false"` + DisplayName *string `mapstructure:"display_name" required:"false"` + FreeformTags map[string]string `mapstructure:"tags" required:"false"` + HostnameLabel *string `mapstructure:"hostname_label" required:"false"` + NsgIds []string `mapstructure:"nsg_ids" required:"false"` + PrivateIp *string `mapstructure:"private_ip" required:"false"` + SkipSourceDestCheck *bool `mapstructure:"skip_source_dest_check" required:"false"` + SubnetId *string `mapstructure:"subnet_id" required:"false"` +} + type Config struct { common.PackerConfig `mapstructure:",squash"` Comm communicator.Config `mapstructure:",squash"` @@ -56,14 +69,16 @@ type Config struct { CompartmentID string `mapstructure:"compartment_ocid"` // Image - BaseImageID string `mapstructure:"base_image_ocid"` - Shape string `mapstructure:"shape"` - ImageName string `mapstructure:"image_name"` + BaseImageID string `mapstructure:"base_image_ocid"` + ImageName string `mapstructure:"image_name"` + ImageCompartmentID string `mapstructure:"image_compartment_ocid"` // Instance InstanceName string `mapstructure:"instance_name"` InstanceTags map[string]string `mapstructure:"instance_tags"` InstanceDefinedTags map[string]map[string]interface{} `mapstructure:"instance_defined_tags"` + Shape string `mapstructure:"shape"` + BootVolumeSizeInGBs int64 `mapstructure:"disk_size"` // Metadata optionally contains custom metadata key/value pairs provided in the // configuration. While this can be used to set metadata["user_data"] the explicit @@ -77,7 +92,8 @@ type Config struct { UserDataFile string `mapstructure:"user_data_file"` // Networking - SubnetID string `mapstructure:"subnet_ocid"` + SubnetID string `mapstructure:"subnet_ocid"` + CreateVnicDetails CreateVNICDetails `mapstructure:"create_vnic_details"` // Tagging Tags map[string]string `mapstructure:"tags"` @@ -239,6 +255,10 @@ func (c *Config) Prepare(raws ...interface{}) error { c.CompartmentID = tenancyOCID } + if c.ImageCompartmentID == "" { + c.ImageCompartmentID = c.CompartmentID + } + if c.Shape == "" { errs = packer.MultiErrorAppend( errs, errors.New("'shape' must be specified")) @@ -312,6 +332,15 @@ func (c *Config) Prepare(raws ...interface{}) error { } } + // Set default boot volume size to 50 if not set + // Check if size set is allowed by OCI + if c.BootVolumeSizeInGBs == 0 { + c.BootVolumeSizeInGBs = 50 + } else if c.BootVolumeSizeInGBs < 50 || c.BootVolumeSizeInGBs > 16384 { + errs = packer.MultiErrorAppend( + errs, errors.New("'disk_size' must be between 50 and 16384 GBs")) + } + if errs != nil && len(errs.Errors) > 0 { return errs } diff --git a/builder/oracle/oci/config.hcl2spec.go b/builder/oracle/oci/config.hcl2spec.go index 7f5fe7d2a..647244f12 100644 --- a/builder/oracle/oci/config.hcl2spec.go +++ b/builder/oracle/oci/config.hcl2spec.go @@ -1,4 +1,4 @@ -// Code generated by "mapstructure-to-hcl2 -type Config"; DO NOT EDIT. +// Code generated by "mapstructure-to-hcl2 -type Config,CreateVNICDetails"; DO NOT EDIT. package oci import ( @@ -76,15 +76,18 @@ type FlatConfig struct { AvailabilityDomain *string `mapstructure:"availability_domain" cty:"availability_domain" hcl:"availability_domain"` CompartmentID *string `mapstructure:"compartment_ocid" cty:"compartment_ocid" hcl:"compartment_ocid"` BaseImageID *string `mapstructure:"base_image_ocid" cty:"base_image_ocid" hcl:"base_image_ocid"` - Shape *string `mapstructure:"shape" cty:"shape" hcl:"shape"` ImageName *string `mapstructure:"image_name" cty:"image_name" hcl:"image_name"` + ImageCompartmentID *string `mapstructure:"image_compartment_ocid" cty:"image_compartment_ocid" hcl:"image_compartment_ocid"` InstanceName *string `mapstructure:"instance_name" cty:"instance_name" hcl:"instance_name"` InstanceTags map[string]string `mapstructure:"instance_tags" cty:"instance_tags" hcl:"instance_tags"` InstanceDefinedTags map[string]map[string]interface{} `mapstructure:"instance_defined_tags" cty:"instance_defined_tags" hcl:"instance_defined_tags"` + Shape *string `mapstructure:"shape" cty:"shape" hcl:"shape"` + BootVolumeSizeInGBs *int64 `mapstructure:"disk_size" cty:"disk_size" hcl:"disk_size"` Metadata map[string]string `mapstructure:"metadata" cty:"metadata" hcl:"metadata"` UserData *string `mapstructure:"user_data" cty:"user_data" hcl:"user_data"` UserDataFile *string `mapstructure:"user_data_file" cty:"user_data_file" hcl:"user_data_file"` SubnetID *string `mapstructure:"subnet_ocid" cty:"subnet_ocid" hcl:"subnet_ocid"` + CreateVnicDetails *FlatCreateVNICDetails `mapstructure:"create_vnic_details" cty:"create_vnic_details" hcl:"create_vnic_details"` Tags map[string]string `mapstructure:"tags" cty:"tags" hcl:"tags"` DefinedTags map[string]map[string]interface{} `mapstructure:"defined_tags" cty:"defined_tags" hcl:"defined_tags"` } @@ -168,17 +171,59 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "availability_domain": &hcldec.AttrSpec{Name: "availability_domain", Type: cty.String, Required: false}, "compartment_ocid": &hcldec.AttrSpec{Name: "compartment_ocid", Type: cty.String, Required: false}, "base_image_ocid": &hcldec.AttrSpec{Name: "base_image_ocid", Type: cty.String, Required: false}, - "shape": &hcldec.AttrSpec{Name: "shape", Type: cty.String, Required: false}, "image_name": &hcldec.AttrSpec{Name: "image_name", Type: cty.String, Required: false}, + "image_compartment_ocid": &hcldec.AttrSpec{Name: "image_compartment_ocid", Type: cty.String, Required: false}, "instance_name": &hcldec.AttrSpec{Name: "instance_name", Type: cty.String, Required: false}, "instance_tags": &hcldec.AttrSpec{Name: "instance_tags", Type: cty.Map(cty.String), Required: false}, "instance_defined_tags": &hcldec.AttrSpec{Name: "instance_defined_tags", Type: cty.Map(cty.String), Required: false}, + "shape": &hcldec.AttrSpec{Name: "shape", Type: cty.String, Required: false}, + "disk_size": &hcldec.AttrSpec{Name: "disk_size", Type: cty.Number, Required: false}, "metadata": &hcldec.AttrSpec{Name: "metadata", Type: cty.Map(cty.String), Required: false}, "user_data": &hcldec.AttrSpec{Name: "user_data", Type: cty.String, Required: false}, "user_data_file": &hcldec.AttrSpec{Name: "user_data_file", Type: cty.String, Required: false}, "subnet_ocid": &hcldec.AttrSpec{Name: "subnet_ocid", Type: cty.String, Required: false}, + "create_vnic_details": &hcldec.BlockSpec{TypeName: "create_vnic_details", Nested: hcldec.ObjectSpec((*FlatCreateVNICDetails)(nil).HCL2Spec())}, "tags": &hcldec.AttrSpec{Name: "tags", Type: cty.Map(cty.String), Required: false}, "defined_tags": &hcldec.AttrSpec{Name: "defined_tags", Type: cty.Map(cty.String), Required: false}, } return s } + +// FlatCreateVNICDetails is an auto-generated flat version of CreateVNICDetails. +// Where the contents of a field with a `mapstructure:,squash` tag are bubbled up. +type FlatCreateVNICDetails struct { + AssignPublicIp *bool `mapstructure:"assign_public_ip" required:"false" cty:"assign_public_ip" hcl:"assign_public_ip"` + DefinedTags map[string]map[string]interface{} `mapstructure:"defined_tags" required:"false" cty:"defined_tags" hcl:"defined_tags"` + DisplayName *string `mapstructure:"display_name" required:"false" cty:"display_name" hcl:"display_name"` + FreeformTags map[string]string `mapstructure:"tags" required:"false" cty:"tags" hcl:"tags"` + HostnameLabel *string `mapstructure:"hostname_label" required:"false" cty:"hostname_label" hcl:"hostname_label"` + NsgIds []string `mapstructure:"nsg_ids" required:"false" cty:"nsg_ids" hcl:"nsg_ids"` + PrivateIp *string `mapstructure:"private_ip" required:"false" cty:"private_ip" hcl:"private_ip"` + SkipSourceDestCheck *bool `mapstructure:"skip_source_dest_check" required:"false" cty:"skip_source_dest_check" hcl:"skip_source_dest_check"` + SubnetId *string `mapstructure:"subnet_id" required:"false" cty:"subnet_id" hcl:"subnet_id"` +} + +// FlatMapstructure returns a new FlatCreateVNICDetails. +// FlatCreateVNICDetails is an auto-generated flat version of CreateVNICDetails. +// Where the contents a fields with a `mapstructure:,squash` tag are bubbled up. +func (*CreateVNICDetails) FlatMapstructure() interface{ HCL2Spec() map[string]hcldec.Spec } { + return new(FlatCreateVNICDetails) +} + +// HCL2Spec returns the hcl spec of a CreateVNICDetails. +// This spec is used by HCL to read the fields of CreateVNICDetails. +// The decoded values from this spec will then be applied to a FlatCreateVNICDetails. +func (*FlatCreateVNICDetails) HCL2Spec() map[string]hcldec.Spec { + s := map[string]hcldec.Spec{ + "assign_public_ip": &hcldec.AttrSpec{Name: "assign_public_ip", Type: cty.Bool, Required: false}, + "defined_tags": &hcldec.AttrSpec{Name: "defined_tags", Type: cty.Map(cty.String), Required: false}, + "display_name": &hcldec.AttrSpec{Name: "display_name", Type: cty.String, Required: false}, + "tags": &hcldec.AttrSpec{Name: "tags", Type: cty.Map(cty.String), Required: false}, + "hostname_label": &hcldec.AttrSpec{Name: "hostname_label", Type: cty.String, Required: false}, + "nsg_ids": &hcldec.AttrSpec{Name: "nsg_ids", Type: cty.List(cty.String), Required: false}, + "private_ip": &hcldec.AttrSpec{Name: "private_ip", Type: cty.String, Required: false}, + "skip_source_dest_check": &hcldec.AttrSpec{Name: "skip_source_dest_check", Type: cty.Bool, Required: false}, + "subnet_id": &hcldec.AttrSpec{Name: "subnet_id", Type: cty.String, Required: false}, + } + return s +} diff --git a/builder/oracle/oci/config_test.go b/builder/oracle/oci/config_test.go index 22ac18172..1026d8aed 100644 --- a/builder/oracle/oci/config_test.go +++ b/builder/oracle/oci/config_test.go @@ -21,7 +21,6 @@ func testConfig(accessConfFile *os.File) map[string]interface{} { // Image "base_image_ocid": "ocd1...", - "shape": "VM.Standard1.1", "image_name": "HelloWorld", // Networking @@ -36,6 +35,17 @@ func testConfig(accessConfFile *os.File) map[string]interface{} { "defined_tags": map[string]map[string]interface{}{ "namespace": {"key": "value"}, }, + + // Instance Details + "instance_name": "hello-world", + "instance_tags": map[string]string{ + "key": "value", + }, + "create_vnic_details": map[string]interface{}{ + "nsg_ids": []string{"ocd1..."}, + }, + "shape": "VM.Standard1.1", + "disk_size": 60, } } diff --git a/builder/oracle/oci/driver_oci.go b/builder/oracle/oci/driver_oci.go index 4605f3bca..3901a0bac 100644 --- a/builder/oracle/oci/driver_oci.go +++ b/builder/oracle/oci/driver_oci.go @@ -56,7 +56,6 @@ func (d *driverOCI) CreateInstance(ctx context.Context, publicKey string) (strin CompartmentId: &d.cfg.CompartmentID, DefinedTags: d.cfg.InstanceDefinedTags, FreeformTags: d.cfg.InstanceTags, - ImageId: &d.cfg.BaseImageID, Shape: &d.cfg.Shape, SubnetId: &d.cfg.SubnetID, Metadata: metadata, @@ -67,6 +66,27 @@ func (d *driverOCI) CreateInstance(ctx context.Context, publicKey string) (strin instanceDetails.DisplayName = &d.cfg.InstanceName } + // Pass VNIC details, if specified, to the instance + CreateVnicDetails := core.CreateVnicDetails{ + AssignPublicIp: d.cfg.CreateVnicDetails.AssignPublicIp, + DisplayName: d.cfg.CreateVnicDetails.DisplayName, + HostnameLabel: d.cfg.CreateVnicDetails.HostnameLabel, + NsgIds: d.cfg.CreateVnicDetails.NsgIds, + PrivateIp: d.cfg.CreateVnicDetails.PrivateIp, + SkipSourceDestCheck: d.cfg.CreateVnicDetails.SkipSourceDestCheck, + SubnetId: d.cfg.CreateVnicDetails.SubnetId, + DefinedTags: d.cfg.CreateVnicDetails.DefinedTags, + FreeformTags: d.cfg.CreateVnicDetails.FreeformTags, + } + + instanceDetails.CreateVnicDetails = &CreateVnicDetails + + // Create Source details which will be used to Launch Instance + instanceDetails.SourceDetails = core.InstanceSourceViaImageDetails{ + ImageId: &d.cfg.BaseImageID, + BootVolumeSizeInGBs: &d.cfg.BootVolumeSizeInGBs, + } + instance, err := d.computeClient.LaunchInstance(context.TODO(), core.LaunchInstanceRequest{LaunchInstanceDetails: instanceDetails}) if err != nil { @@ -79,7 +99,7 @@ func (d *driverOCI) CreateInstance(ctx context.Context, publicKey string) (strin // CreateImage creates a new custom image. func (d *driverOCI) CreateImage(ctx context.Context, id string) (core.Image, error) { res, err := d.computeClient.CreateImage(ctx, core.CreateImageRequest{CreateImageDetails: core.CreateImageDetails{ - CompartmentId: &d.cfg.CompartmentID, + CompartmentId: &d.cfg.ImageCompartmentID, InstanceId: &id, DisplayName: &d.cfg.ImageName, FreeformTags: d.cfg.Tags, diff --git a/builder/parallels/iso/builder.hcl2spec.go b/builder/parallels/iso/builder.hcl2spec.go index a3bf7cea4..39cffa855 100644 --- a/builder/parallels/iso/builder.hcl2spec.go +++ b/builder/parallels/iso/builder.hcl2spec.go @@ -20,6 +20,7 @@ type FlatConfig struct { HTTPPortMin *int `mapstructure:"http_port_min" cty:"http_port_min" hcl:"http_port_min"` HTTPPortMax *int `mapstructure:"http_port_max" cty:"http_port_max" hcl:"http_port_max"` HTTPAddress *string `mapstructure:"http_bind_address" cty:"http_bind_address" hcl:"http_bind_address"` + HTTPInterface *string `mapstructure:"http_interface" undocumented:"true" cty:"http_interface" hcl:"http_interface"` ISOChecksum *string `mapstructure:"iso_checksum" required:"true" cty:"iso_checksum" hcl:"iso_checksum"` RawSingleISOUrl *string `mapstructure:"iso_url" required:"true" cty:"iso_url" hcl:"iso_url"` ISOUrls []string `mapstructure:"iso_urls" cty:"iso_urls" hcl:"iso_urls"` @@ -123,6 +124,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "http_port_min": &hcldec.AttrSpec{Name: "http_port_min", Type: cty.Number, Required: false}, "http_port_max": &hcldec.AttrSpec{Name: "http_port_max", Type: cty.Number, Required: false}, "http_bind_address": &hcldec.AttrSpec{Name: "http_bind_address", Type: cty.String, Required: false}, + "http_interface": &hcldec.AttrSpec{Name: "http_interface", Type: cty.String, Required: false}, "iso_checksum": &hcldec.AttrSpec{Name: "iso_checksum", Type: cty.String, Required: false}, "iso_url": &hcldec.AttrSpec{Name: "iso_url", Type: cty.String, Required: false}, "iso_urls": &hcldec.AttrSpec{Name: "iso_urls", Type: cty.List(cty.String), Required: false}, diff --git a/builder/proxmox/common/bootcommand_driver.go b/builder/proxmox/common/bootcommand_driver.go index 372e34829..304db3ef4 100644 --- a/builder/proxmox/common/bootcommand_driver.go +++ b/builder/proxmox/common/bootcommand_driver.go @@ -2,6 +2,7 @@ package proxmox import ( "fmt" + "strings" "time" "unicode" @@ -10,23 +11,33 @@ import ( ) type proxmoxDriver struct { - client commandTyper - vmRef *proxmox.VmRef - specialMap map[string]string - runeMap map[rune]string - interval time.Duration + client commandTyper + vmRef *proxmox.VmRef + specialMap map[string]string + runeMap map[rune]string + interval time.Duration + specialBuffer []string + normalBuffer []string } func NewProxmoxDriver(c commandTyper, vmRef *proxmox.VmRef, interval time.Duration) *proxmoxDriver { // Mappings for packer shorthand to qemu qkeycodes sMap := map[string]string{ - "spacebar": "spc", - "bs": "backspace", - "del": "delete", - "return": "ret", - "enter": "ret", - "pageUp": "pgup", - "pageDown": "pgdn", + "spacebar": "spc", + "bs": "backspace", + "del": "delete", + "return": "ret", + "enter": "ret", + "pageUp": "pgup", + "pageDown": "pgdn", + "leftshift": "shift", + "rightshift": "shift", + "leftalt": "alt", + "rightalt": "alt_r", + "leftctrl": "ctrl", + "rightctrl": "ctrl_r", + "leftsuper": "meta_l", + "rightsuper": "meta_r", } // Mappings for runes that need to be translated to special qkeycodes // Taken from https://github.com/qemu/qemu/blob/master/pc-bios/keymaps/en-us @@ -78,18 +89,26 @@ func NewProxmoxDriver(c commandTyper, vmRef *proxmox.VmRef, interval time.Durati } func (p *proxmoxDriver) SendKey(key rune, action bootcommand.KeyAction) error { - if special, ok := p.runeMap[key]; ok { - return p.send(special) + switch action.String() { + case "Press": + if special, ok := p.runeMap[key]; ok { + return p.send(special) + } + var keys string + if unicode.IsUpper(key) { + keys = fmt.Sprintf("shift-%c", unicode.ToLower(key)) + } else { + keys = fmt.Sprintf("%c", key) + } + return p.send(keys) + case "On": + key := fmt.Sprintf("%c", key) + p.normalBuffer = addKeyToBuffer(p.normalBuffer, key) + case "Off": + key := fmt.Sprintf("%c", key) + p.normalBuffer = removeKeyFromBuffer(p.normalBuffer, key) } - - var keys string - if unicode.IsUpper(key) { - keys = fmt.Sprintf("shift-%c", unicode.ToLower(key)) - } else { - keys = fmt.Sprintf("%c", key) - } - - return p.send(keys) + return nil } func (p *proxmoxDriver) SendSpecial(special string, action bootcommand.KeyAction) error { @@ -97,18 +116,48 @@ func (p *proxmoxDriver) SendSpecial(special string, action bootcommand.KeyAction if replacement, ok := p.specialMap[special]; ok { keys = replacement } - - return p.send(keys) + switch action.String() { + case "Press": + return p.send(keys) + case "On": + p.specialBuffer = addKeyToBuffer(p.specialBuffer, keys) + case "Off": + p.specialBuffer = removeKeyFromBuffer(p.specialBuffer, keys) + } + return nil } -func (p *proxmoxDriver) send(keys string) error { - err := p.client.Sendkey(p.vmRef, keys) +func (p *proxmoxDriver) send(key string) error { + keys := append(p.specialBuffer, p.normalBuffer...) + keys = append(keys, key) + keyEventString := bufferToKeyEvent(keys) + err := p.client.Sendkey(p.vmRef, keyEventString) if err != nil { return err } - time.Sleep(p.interval) return nil } func (p *proxmoxDriver) Flush() error { return nil } + +func bufferToKeyEvent(keys []string) string { + return strings.Join(keys, "-") +} +func addKeyToBuffer(buffer []string, key string) []string { + for _, value := range buffer { + if value == key { + return buffer + } + } + return append(buffer, key) +} +func removeKeyFromBuffer(buffer []string, key string) []string { + for index, value := range buffer { + if value == key { + buffer[index] = buffer[len(buffer)-1] + return buffer[:len(buffer)-1] + } + } + return buffer +} diff --git a/builder/proxmox/common/builder.go b/builder/proxmox/common/builder.go index 74b44a883..1d33249b7 100644 --- a/builder/proxmox/common/builder.go +++ b/builder/proxmox/common/builder.go @@ -131,16 +131,32 @@ func commHost(host string) func(state multistep.StateBag) (string, error) { // Reads the first non-loopback interface's IP address from the VM. // qemu-guest-agent package must be installed on the VM func getVMIP(state multistep.StateBag) (string, error) { - c := state.Get("proxmoxClient").(*proxmox.Client) + client := state.Get("proxmoxClient").(*proxmox.Client) + config := state.Get("config").(*Config) vmRef := state.Get("vmRef").(*proxmox.VmRef) - ifs, err := c.GetVmAgentNetworkInterfaces(vmRef) + ifs, err := client.GetVmAgentNetworkInterfaces(vmRef) if err != nil { return "", err } - // TODO: Do something smarter here? Allow specifying interface? Or address family? - // For now, just go for first non-loopback + if config.VMInterface != "" { + for _, iface := range ifs { + if config.VMInterface != iface.Name { + continue + } + + for _, addr := range iface.IPAddresses { + if addr.IsLoopback() { + continue + } + return addr.String(), nil + } + return "", fmt.Errorf("Interface %s only has loopback addresses", config.VMInterface) + } + return "", fmt.Errorf("Interface %s not found in VM", config.VMInterface) + } + for _, iface := range ifs { for _, addr := range iface.IPAddresses { if addr.IsLoopback() { diff --git a/builder/proxmox/common/config.go b/builder/proxmox/common/config.go index ceeb19a1f..8b4801310 100644 --- a/builder/proxmox/common/config.go +++ b/builder/proxmox/common/config.go @@ -58,6 +58,11 @@ type Config struct { CloudInit bool `mapstructure:"cloud_init"` CloudInitStoragePool string `mapstructure:"cloud_init_storage_pool"` + shouldUploadISO bool + + AdditionalISOFiles []storageConfig `mapstructure:"additional_iso_files"` + VMInterface string `mapstructure:"vm_interface"` + Ctx interpolate.Context `mapstructure:",squash",mapstructure-to-hcl2:"skip"` } @@ -76,6 +81,7 @@ type diskConfig struct { Size string `mapstructure:"disk_size"` CacheMode string `mapstructure:"cache_mode"` DiskFormat string `mapstructure:"format"` + IOThread bool `mapstructure:"io_thread"` } type vgaConfig struct { Type string `mapstructure:"type"` @@ -172,6 +178,17 @@ func (c *Config) Prepare(upper interface{}, raws ...interface{}) ([]string, []st log.Printf("Disk %d cache mode not set, using default 'none'", idx) c.Disks[idx].CacheMode = "none" } + if c.Disks[idx].IOThread { + // io thread is only supported by virtio-scsi-single controller + if c.SCSIController != "virtio-scsi-single" { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("io thread option requires virtio-scsi-single controller")) + } else { + // ... and only for virtio and scsi disks + if !(c.Disks[idx].Type == "scsi" || c.Disks[idx].Type == "virtio") { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("io thread option requires scsi or a virtio disk")) + } + } + } // For any storage pool types which aren't in rxStorageTypes in proxmox-api/proxmox/config_qemu.go:890 // (currently zfspool|lvm|rbd|cephfs), the format parameter is mandatory. Make sure this is still up to date // when updating the vendored code! diff --git a/builder/proxmox/common/step_start_vm.go b/builder/proxmox/common/step_start_vm.go index 5631dfa07..9b8a2b0f9 100644 --- a/builder/proxmox/common/step_start_vm.go +++ b/builder/proxmox/common/step_start_vm.go @@ -133,6 +133,10 @@ func generateProxmoxDisks(disks []diskConfig) proxmox.QemuDevices { setDeviceParamIfDefined(devs[idx], "storage_type", disks[idx].StoragePoolType) setDeviceParamIfDefined(devs[idx], "cache", disks[idx].CacheMode) setDeviceParamIfDefined(devs[idx], "format", disks[idx].DiskFormat) + + if devs[idx]["type"] == "scsi" || devs[idx]["type"] == "virtio" { + setDeviceParamIfDefined(devs[idx], "iothread", strconv.FormatBool(disks[idx].IOThread)) + } } return devs } diff --git a/builder/proxmox/common/step_type_boot_command.go b/builder/proxmox/common/step_type_boot_command.go index 1a557eb43..17c1ec962 100644 --- a/builder/proxmox/common/step_type_boot_command.go +++ b/builder/proxmox/common/step_type_boot_command.go @@ -53,14 +53,20 @@ func (s *stepTypeBootCommand) Run(ctx context.Context, state multistep.StateBag) return multistep.ActionHalt } } - - httpIP, err := hostIP() - if err != nil { - err := fmt.Errorf("Failed to determine host IP: %s", err) - state.Put("error", err) - ui.Error(err.Error()) - return multistep.ActionHalt + var httpIP string + var err error + if c.HTTPAddress != "0.0.0.0" { + httpIP = c.HTTPAddress + } else { + httpIP, err = hostIP(c.HTTPInterface) + if err != nil { + err := fmt.Errorf("Failed to determine host IP: %s", err) + state.Put("error", err) + ui.Error(err.Error()) + return multistep.ActionHalt + } } + state.Put("http_ip", httpIP) s.Ctx.Data = &bootCommandTemplateData{ HTTPIP: httpIP, @@ -97,12 +103,25 @@ func (s *stepTypeBootCommand) Run(ctx context.Context, state multistep.StateBag) func (*stepTypeBootCommand) Cleanup(multistep.StateBag) {} -func hostIP() (string, error) { - addrs, err := net.InterfaceAddrs() - if err != nil { - return "", err - } +func hostIP(ifname string) (string, error) { + var addrs []net.Addr + var err error + if ifname != "" { + iface, err := net.InterfaceByName(ifname) + if err != nil { + return "", err + } + addrs, err = iface.Addrs() + if err != nil { + return "", err + } + } else { + addrs, err = net.InterfaceAddrs() + if err != nil { + return "", err + } + } for _, addr := range addrs { if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { if ipnet.IP.To4() != nil { @@ -110,6 +129,5 @@ func hostIP() (string, error) { } } } - return "", errors.New("No host IP found") } diff --git a/builder/proxmox/common/step_type_boot_command_test.go b/builder/proxmox/common/step_type_boot_command_test.go index 88034753a..c713e9cca 100644 --- a/builder/proxmox/common/step_type_boot_command_test.go +++ b/builder/proxmox/common/step_type_boot_command_test.go @@ -52,6 +52,34 @@ func TestTypeBootCommand(t *testing.T) { expectedKeysSent: "shift-hellospcshift-worldspc2dot0fooshift-1barshift-2baz", expectedAction: multistep.ActionContinue, }, + { + name: "holding and releasing keys", + builderConfig: &Config{BootConfig: bootcommand.BootConfig{BootCommand: []string{"helloworld"}}}, + expectCallSendkey: true, + expectedKeysSent: "shift-hshift-eshift-lshift-lshift-oshift-alt_r-wshift-alt_r-oshift-alt_r-rshift-alt_r-lshift-alt_r-d", + expectedAction: multistep.ActionContinue, + }, + { + name: "holding multiple alphabetical keys and shift", + builderConfig: &Config{BootConfig: bootcommand.BootConfig{BootCommand: []string{"n"}}}, + expectCallSendkey: true, + expectedKeysSent: "shift-c-n", + expectedAction: multistep.ActionContinue, + }, + { + name: "noop keystrokes", + builderConfig: &Config{BootConfig: bootcommand.BootConfig{BootCommand: []string{""}}}, + expectCallSendkey: true, + expectedKeysSent: "", + expectedAction: multistep.ActionContinue, + }, + { + name: "noop keystrokes mixed", + builderConfig: &Config{BootConfig: bootcommand.BootConfig{BootCommand: []string{"h"}}}, + expectCallSendkey: true, + expectedKeysSent: "shift-h", + expectedAction: multistep.ActionContinue, + }, { name: "without boot command sendkey should not be called", builderConfig: &Config{BootConfig: bootcommand.BootConfig{BootCommand: []string{}}}, diff --git a/builder/proxmox/iso/config_test.go b/builder/proxmox/iso/config_test.go index 836436422..f9b575fc8 100644 --- a/builder/proxmox/iso/config_test.go +++ b/builder/proxmox/iso/config_test.go @@ -110,3 +110,112 @@ func TestBasicExampleFromDocsIsValid(t *testing.T) { t.Errorf("Expected CloudInit to be false, got %t", b.config.CloudInit) } } + +func TestAgentSetToFalse(t *testing.T) { + cfg := mandatoryConfig(t) + cfg["qemu_agent"] = false + + var c Config + warn, err := c.Prepare(cfg) + if err != nil { + t.Fatal(err, warn) + } + + if c.Agent != false { + t.Errorf("Expected Agent to be false, got %t", c.Agent) + } +} + +func TestPacketQueueSupportForNetworkAdapters(t *testing.T) { + drivertests := []struct { + expectedToFail bool + model string + }{ + {expectedToFail: false, model: "virtio"}, + {expectedToFail: true, model: "e1000"}, + {expectedToFail: true, model: "e1000-82540em"}, + {expectedToFail: true, model: "e1000-82544gc"}, + {expectedToFail: true, model: "e1000-82545em"}, + {expectedToFail: true, model: "i82551"}, + {expectedToFail: true, model: "i82557b"}, + {expectedToFail: true, model: "i82559er"}, + {expectedToFail: true, model: "ne2k_isa"}, + {expectedToFail: true, model: "ne2k_pci"}, + {expectedToFail: true, model: "pcnet"}, + {expectedToFail: true, model: "rtl8139"}, + {expectedToFail: true, model: "vmxnet3"}, + } + + for _, tt := range drivertests { + device := make(map[string]interface{}) + device["bridge"] = "vmbr0" + device["model"] = tt.model + device["packet_queues"] = 2 + + devices := make([]map[string]interface{}, 0) + devices = append(devices, device) + + cfg := mandatoryConfig(t) + cfg["network_adapters"] = devices + + var c Config + _, err := c.Prepare(cfg) + + if tt.expectedToFail == true && err == nil { + t.Error("expected config preparation to fail, but no error occured") + } + + if tt.expectedToFail == false && err != nil { + t.Errorf("expected config preparation to succeed, but %s", err.Error()) + } + } +} + +func TestHardDiskControllerIOThreadSupport(t *testing.T) { + drivertests := []struct { + expectedToFail bool + controller string + disk_type string + }{ + // io thread is only supported by virtio-scsi-single controller + // and only for virtio and scsi disks + {expectedToFail: false, controller: "virtio-scsi-single", disk_type: "scsi"}, + {expectedToFail: false, controller: "virtio-scsi-single", disk_type: "virtio"}, + {expectedToFail: true, controller: "virtio-scsi-single", disk_type: "sata"}, + {expectedToFail: true, controller: "lsi", disk_type: "scsi"}, + {expectedToFail: true, controller: "lsi53c810", disk_type: "virtio"}, + } + + for _, tt := range drivertests { + nic := make(map[string]interface{}) + nic["bridge"] = "vmbr0" + + nics := make([]map[string]interface{}, 0) + nics = append(nics, nic) + + disk := make(map[string]interface{}) + disk["type"] = tt.disk_type + disk["io_thread"] = true + disk["storage_pool"] = "local-lvm" + disk["storage_pool_type"] = "lvm" + + disks := make([]map[string]interface{}, 0) + disks = append(disks, disk) + + cfg := mandatoryConfig(t) + cfg["network_adapters"] = nics + cfg["disks"] = disks + cfg["scsi_controller"] = tt.controller + + var c Config + _, err := c.Prepare(cfg) + + if tt.expectedToFail == true && err == nil { + t.Error("expected config preparation to fail, but no error occured") + } + + if tt.expectedToFail == false && err != nil { + t.Errorf("expected config preparation to succeed, but %s", err.Error()) + } + } +} diff --git a/builder/qemu/builder.go b/builder/qemu/builder.go index 23d6d29fe..d52a74222 100644 --- a/builder/qemu/builder.go +++ b/builder/qemu/builder.go @@ -1,6 +1,3 @@ -//go:generate struct-markdown -//go:generate mapstructure-to-hcl2 -type Config - package qemu import ( @@ -11,561 +8,26 @@ import ( "os" "os/exec" "path/filepath" - "regexp" - "runtime" - "strings" "github.com/hashicorp/hcl/v2/hcldec" "github.com/hashicorp/packer/common" - "github.com/hashicorp/packer/common/bootcommand" - "github.com/hashicorp/packer/common/shutdowncommand" "github.com/hashicorp/packer/helper/communicator" - "github.com/hashicorp/packer/helper/config" "github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/packer" - "github.com/hashicorp/packer/template/interpolate" ) const BuilderId = "transcend.qemu" -var accels = map[string]struct{}{ - "none": {}, - "kvm": {}, - "tcg": {}, - "xen": {}, - "hax": {}, - "hvf": {}, - "whpx": {}, -} - -var diskInterface = map[string]bool{ - "ide": true, - "scsi": true, - "virtio": true, - "virtio-scsi": true, -} - -var diskCache = map[string]bool{ - "writethrough": true, - "writeback": true, - "none": true, - "unsafe": true, - "directsync": true, -} - -var diskDiscard = map[string]bool{ - "unmap": true, - "ignore": true, -} - -var diskDZeroes = map[string]bool{ - "unmap": true, - "on": true, - "off": true, -} - type Builder struct { config Config runner multistep.Runner } -type Config struct { - common.PackerConfig `mapstructure:",squash"` - common.HTTPConfig `mapstructure:",squash"` - common.ISOConfig `mapstructure:",squash"` - bootcommand.VNCConfig `mapstructure:",squash"` - shutdowncommand.ShutdownConfig `mapstructure:",squash"` - CommConfig CommConfig `mapstructure:",squash"` - common.FloppyConfig `mapstructure:",squash"` - // Use iso from provided url. Qemu must support - // curl block device. This defaults to `false`. - ISOSkipCache bool `mapstructure:"iso_skip_cache" required:"false"` - // The accelerator type to use when running the VM. - // This may be `none`, `kvm`, `tcg`, `hax`, `hvf`, `whpx`, or `xen`. The appropriate - // software must have already been installed on your build machine to use the - // accelerator you specified. When no accelerator is specified, Packer will try - // to use `kvm` if it is available but will default to `tcg` otherwise. - // - // ~> The `hax` accelerator has issues attaching CDROM ISOs. This is an - // upstream issue which can be tracked - // [here](https://github.com/intel/haxm/issues/20). - // - // ~> The `hvf` and `whpx` accelerator are new and experimental as of - // [QEMU 2.12.0](https://wiki.qemu.org/ChangeLog/2.12#Host_support). - // You may encounter issues unrelated to Packer when using these. You may need to - // add [ "-global", "virtio-pci.disable-modern=on" ] to `qemuargs` depending on the - // guest operating system. - // - // ~> For `whpx`, note that [Stefan Weil's QEMU for Windows distribution](https://qemu.weilnetz.de/w64/) - // does not include WHPX support and users may need to compile or source a - // build of QEMU for Windows themselves with WHPX support. - Accelerator string `mapstructure:"accelerator" required:"false"` - // Additional disks to create. Uses `vm_name` as the disk name template and - // appends `-#` where `#` is the position in the array. `#` starts at 1 since 0 - // is the default disk. Each string represents the disk image size in bytes. - // Optional suffixes 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' - // (gigabyte, 1024M), 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' - // (exabyte, 1024P) are supported. 'b' is ignored. Per qemu-img documentation. - // Each additional disk uses the same disk parameters as the default disk. - // Unset by default. - AdditionalDiskSize []string `mapstructure:"disk_additional_size" required:"false"` - // The number of cpus to use when building the VM. - // The default is `1` CPU. - CpuCount int `mapstructure:"cpus" required:"false"` - // The interface to use for the disk. Allowed values include any of `ide`, - // `scsi`, `virtio` or `virtio-scsi`^\*. Note also that any boot commands - // or kickstart type scripts must have proper adjustments for resulting - // device names. The Qemu builder uses `virtio` by default. - // - // ^\* Please be aware that use of the `scsi` disk interface has been - // disabled by Red Hat due to a bug described - // [here](https://bugzilla.redhat.com/show_bug.cgi?id=1019220). If you are - // running Qemu on RHEL or a RHEL variant such as CentOS, you *must* choose - // one of the other listed interfaces. Using the `scsi` interface under - // these circumstances will cause the build to fail. - DiskInterface string `mapstructure:"disk_interface" required:"false"` - // The size in bytes of the hard disk of the VM. Suffix with the first - // letter of common byte types. Use "k" or "K" for kilobytes, "M" for - // megabytes, G for gigabytes, and T for terabytes. If no value is provided - // for disk_size, Packer uses a default of `40960M` (40 GB). If a disk_size - // number is provided with no units, Packer will default to Megabytes. - DiskSize string `mapstructure:"disk_size" required:"false"` - // The cache mode to use for disk. Allowed values include any of - // `writethrough`, `writeback`, `none`, `unsafe` or `directsync`. By - // default, this is set to `writeback`. - DiskCache string `mapstructure:"disk_cache" required:"false"` - // The discard mode to use for disk. Allowed values - // include any of unmap or ignore. By default, this is set to ignore. - DiskDiscard string `mapstructure:"disk_discard" required:"false"` - // The detect-zeroes mode to use for disk. - // Allowed values include any of unmap, on or off. Defaults to off. - // When the value is "off" we don't set the flag in the qemu command, so that - // Packer still works with old versions of QEMU that don't have this option. - DetectZeroes string `mapstructure:"disk_detect_zeroes" required:"false"` - // Packer compacts the QCOW2 image using - // qemu-img convert. Set this option to true to disable compacting. - // Defaults to false. - SkipCompaction bool `mapstructure:"skip_compaction" required:"false"` - // Apply compression to the QCOW2 disk file - // using qemu-img convert. Defaults to false. - DiskCompression bool `mapstructure:"disk_compression" required:"false"` - // Either `qcow2` or `raw`, this specifies the output format of the virtual - // machine image. This defaults to `qcow2`. - Format string `mapstructure:"format" required:"false"` - // Packer defaults to building QEMU virtual machines by - // launching a GUI that shows the console of the machine being built. When this - // value is set to `true`, the machine will start without a console. - // - // You can still see the console if you make a note of the VNC display - // number chosen, and then connect using `vncviewer -Shared :` - Headless bool `mapstructure:"headless" required:"false"` - // Packer defaults to building from an ISO file, this parameter controls - // whether the ISO URL supplied is actually a bootable QEMU image. When - // this value is set to `true`, the machine will either clone the source or - // use it as a backing file (if `use_backing_file` is `true`); then, it - // will resize the image according to `disk_size` and boot it. - DiskImage bool `mapstructure:"disk_image" required:"false"` - // Only applicable when disk_image is true - // and format is qcow2, set this option to true to create a new QCOW2 - // file that uses the file located at iso_url as a backing file. The new file - // will only contain blocks that have changed compared to the backing file, so - // enabling this option can significantly reduce disk usage. - UseBackingFile bool `mapstructure:"use_backing_file" required:"false"` - // The type of machine emulation to use. Run your qemu binary with the - // flags `-machine help` to list available types for your system. This - // defaults to `pc`. - MachineType string `mapstructure:"machine_type" required:"false"` - // The amount of memory to use when building the VM - // in megabytes. This defaults to 512 megabytes. - MemorySize int `mapstructure:"memory" required:"false"` - // The driver to use for the network interface. Allowed values `ne2k_pci`, - // `i82551`, `i82557b`, `i82559er`, `rtl8139`, `e1000`, `pcnet`, `virtio`, - // `virtio-net`, `virtio-net-pci`, `usb-net`, `i82559a`, `i82559b`, - // `i82559c`, `i82550`, `i82562`, `i82557a`, `i82557c`, `i82801`, - // `vmxnet3`, `i82558a` or `i82558b`. The Qemu builder uses `virtio-net` by - // default. - NetDevice string `mapstructure:"net_device" required:"false"` - // Connects the network to this bridge instead of using the user mode - // networking. - // - // **NB** This bridge must already exist. You can use the `virbr0` bridge - // as created by vagrant-libvirt. - // - // **NB** This will automatically enable the QMP socket (see QMPEnable). - // - // **NB** This only works in Linux based OSes. - NetBridge string `mapstructure:"net_bridge" required:"false"` - // This is the path to the directory where the - // resulting virtual machine will be created. This may be relative or absolute. - // If relative, the path is relative to the working directory when packer - // is executed. This directory must not exist or be empty prior to running - // the builder. By default this is output-BUILDNAME where "BUILDNAME" is the - // name of the build. - OutputDir string `mapstructure:"output_directory" required:"false"` - // Allows complete control over the qemu command line (though not, at this - // time, qemu-img). Each array of strings makes up a command line switch - // that overrides matching default switch/value pairs. Any value specified - // as an empty string is ignored. All values after the switch are - // concatenated with no separator. - // - // ~> **Warning:** The qemu command line allows extreme flexibility, so - // beware of conflicting arguments causing failures of your run. For - // instance, using --no-acpi could break the ability to send power signal - // type commands (e.g., shutdown -P now) to the virtual machine, thus - // preventing proper shutdown. To see the defaults, look in the packer.log - // file and search for the qemu-system-x86 command. The arguments are all - // printed for review. - // - // The following shows a sample usage: - // - // In JSON: - // ```json - // "qemuargs": [ - // [ "-m", "1024M" ], - // [ "--no-acpi", "" ], - // [ - // "-netdev", - // "user,id=mynet0,", - // "hostfwd=hostip:hostport-guestip:guestport", - // "" - // ], - // [ "-device", "virtio-net,netdev=mynet0" ] - // ] - // ``` - // - // In HCL2: - // ```hcl - // qemuargs = [ - // [ "-m", "1024M" ], - // [ "--no-acpi", "" ], - // [ - // "-netdev", - // "user,id=mynet0,", - // "hostfwd=hostip:hostport-guestip:guestport", - // "" - // ], - // [ "-device", "virtio-net,netdev=mynet0" ] - // ] - // ``` - // - // would produce the following (not including other defaults supplied by - // the builder and not otherwise conflicting with the qemuargs): - // - // ```text - // qemu-system-x86 -m 1024m --no-acpi -netdev - // user,id=mynet0,hostfwd=hostip:hostport-guestip:guestport -device - // virtio-net,netdev=mynet0" - // ``` - // - // ~> **Windows Users:** [QEMU for Windows](https://qemu.weilnetz.de/) - // builds are available though an environmental variable does need to be - // set for QEMU for Windows to redirect stdout to the console instead of - // stdout.txt. - // - // The following shows the environment variable that needs to be set for - // Windows QEMU support: - // - // ```text - // setx SDL_STDIO_REDIRECT=0 - // ``` - // - // You can also use the `SSHHostPort` template variable to produce a packer - // template that can be invoked by `make` in parallel: - // - // In JSON: - // ```json - // "qemuargs": [ - // [ "-netdev", "user,hostfwd=tcp::{{ .SSHHostPort }}-:22,id=forward"], - // [ "-device", "virtio-net,netdev=forward,id=net0"] - // ] - // ``` - // - // In HCL2: - // ```hcl - // qemuargs = [ - // [ "-netdev", "user,hostfwd=tcp::{{ .SSHHostPort }}-:22,id=forward"], - // [ "-device", "virtio-net,netdev=forward,id=net0"] - // ] - // - // `make -j 3 my-awesome-packer-templates` spawns 3 packer processes, each - // of which will bind to their own SSH port as determined by each process. - // This will also work with WinRM, just change the port forward in - // `qemuargs` to map to WinRM's default port of `5985` or whatever value - // you have the service set to listen on. - // - // This is a template engine and allows access to the following variables: - // `{{ .HTTPIP }}`, `{{ .HTTPPort }}`, `{{ .HTTPDir }}`, - // `{{ .OutputDir }}`, `{{ .Name }}`, and `{{ .SSHHostPort }}` - QemuArgs [][]string `mapstructure:"qemuargs" required:"false"` - // The name of the Qemu binary to look for. This - // defaults to qemu-system-x86_64, but may need to be changed for - // some platforms. For example qemu-kvm, or qemu-system-i386 may be a - // better choice for some systems. - QemuBinary string `mapstructure:"qemu_binary" required:"false"` - // Enable QMP socket. Location is specified by `qmp_socket_path`. Defaults - // to false. - QMPEnable bool `mapstructure:"qmp_enable" required:"false"` - // QMP Socket Path when `qmp_enable` is true. Defaults to - // `output_directory`/`vm_name`.monitor. - QMPSocketPath string `mapstructure:"qmp_socket_path" required:"false"` - // If true, do not pass a -display option - // to qemu, allowing it to choose the default. This may be needed when running - // under macOS, and getting errors about sdl not being available. - UseDefaultDisplay bool `mapstructure:"use_default_display" required:"false"` - // What QEMU -display option to use. Defaults to gtk, use none to not pass the - // -display option allowing QEMU to choose the default. This may be needed when - // running under macOS, and getting errors about sdl not being available. - Display string `mapstructure:"display" required:"false"` - // The IP address that should be - // binded to for VNC. By default packer will use 127.0.0.1 for this. If you - // wish to bind to all interfaces use 0.0.0.0. - VNCBindAddress string `mapstructure:"vnc_bind_address" required:"false"` - // Whether or not to set a password on the VNC server. This option - // automatically enables the QMP socket. See `qmp_socket_path`. Defaults to - // `false`. - VNCUsePassword bool `mapstructure:"vnc_use_password" required:"false"` - // The minimum and maximum port - // to use for VNC access to the virtual machine. The builder uses VNC to type - // the initial boot_command. Because Packer generally runs in parallel, - // Packer uses a randomly chosen port in this range that appears available. By - // default this is 5900 to 6000. The minimum and maximum ports are inclusive. - VNCPortMin int `mapstructure:"vnc_port_min" required:"false"` - VNCPortMax int `mapstructure:"vnc_port_max"` - // This is the name of the image (QCOW2 or IMG) file for - // the new virtual machine. By default this is packer-BUILDNAME, where - // "BUILDNAME" is the name of the build. Currently, no file extension will be - // used unless it is specified in this option. - VMName string `mapstructure:"vm_name" required:"false"` - // The interface to use for the CDROM device which contains the ISO image. - // Allowed values include any of `ide`, `scsi`, `virtio` or - // `virtio-scsi`. The Qemu builder uses `virtio` by default. - // Some ARM64 images require `virtio-scsi`. - CDROMInterface string `mapstructure:"cdrom_interface" required:"false"` - - // TODO(mitchellh): deprecate - RunOnce bool `mapstructure:"run_once"` - - ctx interpolate.Context -} - func (b *Builder) ConfigSpec() hcldec.ObjectSpec { return b.config.FlatMapstructure().HCL2Spec() } func (b *Builder) Prepare(raws ...interface{}) ([]string, []string, error) { - err := config.Decode(&b.config, &config.DecodeOpts{ - Interpolate: true, - InterpolateContext: &b.config.ctx, - InterpolateFilter: &interpolate.RenderFilter{ - Exclude: []string{ - "boot_command", - "qemuargs", - }, - }, - }, raws...) - if err != nil { - return nil, nil, err - } - - var errs *packer.MultiError - warnings := make([]string, 0) - errs = packer.MultiErrorAppend(errs, b.config.ShutdownConfig.Prepare(&b.config.ctx)...) - - if b.config.DiskSize == "" || b.config.DiskSize == "0" { - b.config.DiskSize = "40960M" - } else { - // Make sure supplied disk size is valid - // (digits, plus an optional valid unit character). e.g. 5000, 40G, 1t - re := regexp.MustCompile(`^[\d]+(b|k|m|g|t){0,1}$`) - matched := re.MatchString(strings.ToLower(b.config.DiskSize)) - if !matched { - errs = packer.MultiErrorAppend(errs, fmt.Errorf("Invalid disk size.")) - } else { - // Okay, it's valid -- if it doesn't alreay have a suffix, then - // append "M" as the default unit. - re = regexp.MustCompile(`^[\d]+$`) - matched = re.MatchString(strings.ToLower(b.config.DiskSize)) - if matched { - // Needs M added. - b.config.DiskSize = fmt.Sprintf("%sM", b.config.DiskSize) - } - } - } - - if b.config.DiskCache == "" { - b.config.DiskCache = "writeback" - } - - if b.config.DiskDiscard == "" { - b.config.DiskDiscard = "ignore" - } - - if b.config.DetectZeroes == "" { - b.config.DetectZeroes = "off" - } - - if b.config.Accelerator == "" { - if runtime.GOOS == "windows" { - b.config.Accelerator = "tcg" - } else { - // /dev/kvm is a kernel module that may be loaded if kvm is - // installed and the host supports VT-x extensions. To make sure - // this will actually work we need to os.Open() it. If os.Open fails - // the kernel module was not installed or loaded correctly. - if fp, err := os.Open("/dev/kvm"); err != nil { - b.config.Accelerator = "tcg" - } else { - fp.Close() - b.config.Accelerator = "kvm" - } - } - log.Printf("use detected accelerator: %s", b.config.Accelerator) - } else { - log.Printf("use specified accelerator: %s", b.config.Accelerator) - } - - if b.config.MachineType == "" { - b.config.MachineType = "pc" - } - - if b.config.OutputDir == "" { - b.config.OutputDir = fmt.Sprintf("output-%s", b.config.PackerBuildName) - } - - if b.config.QemuBinary == "" { - b.config.QemuBinary = "qemu-system-x86_64" - } - - if b.config.MemorySize < 10 { - log.Printf("MemorySize %d is too small, using default: 512", b.config.MemorySize) - b.config.MemorySize = 512 - } - - if b.config.CpuCount < 1 { - log.Printf("CpuCount %d too small, using default: 1", b.config.CpuCount) - b.config.CpuCount = 1 - } - - if b.config.VNCBindAddress == "" { - b.config.VNCBindAddress = "127.0.0.1" - } - - if b.config.VNCPortMin == 0 { - b.config.VNCPortMin = 5900 - } - - if b.config.VNCPortMax == 0 { - b.config.VNCPortMax = 6000 - } - - if b.config.VMName == "" { - b.config.VMName = fmt.Sprintf("packer-%s", b.config.PackerBuildName) - } - - if b.config.Format == "" { - b.config.Format = "qcow2" - } - - errs = packer.MultiErrorAppend(errs, b.config.FloppyConfig.Prepare(&b.config.ctx)...) - errs = packer.MultiErrorAppend(errs, b.config.VNCConfig.Prepare(&b.config.ctx)...) - - if b.config.NetDevice == "" { - b.config.NetDevice = "virtio-net" - } - - if b.config.DiskInterface == "" { - b.config.DiskInterface = "virtio" - } - - if b.config.ISOSkipCache { - b.config.ISOChecksum = "none" - } - isoWarnings, isoErrs := b.config.ISOConfig.Prepare(&b.config.ctx) - warnings = append(warnings, isoWarnings...) - errs = packer.MultiErrorAppend(errs, isoErrs...) - - errs = packer.MultiErrorAppend(errs, b.config.HTTPConfig.Prepare(&b.config.ctx)...) - commConfigWarnings, es := b.config.CommConfig.Prepare(&b.config.ctx) - if len(es) > 0 { - errs = packer.MultiErrorAppend(errs, es...) - } - warnings = append(warnings, commConfigWarnings...) - - if !(b.config.Format == "qcow2" || b.config.Format == "raw") { - errs = packer.MultiErrorAppend( - errs, errors.New("invalid format, only 'qcow2' or 'raw' are allowed")) - } - - if b.config.Format != "qcow2" { - b.config.SkipCompaction = true - b.config.DiskCompression = false - } - - if b.config.UseBackingFile && !(b.config.DiskImage && b.config.Format == "qcow2") { - errs = packer.MultiErrorAppend( - errs, errors.New("use_backing_file can only be enabled for QCOW2 images and when disk_image is true")) - } - - if b.config.DiskImage && len(b.config.AdditionalDiskSize) > 0 { - errs = packer.MultiErrorAppend( - errs, errors.New("disk_additional_size can only be used when disk_image is false")) - } - - if _, ok := accels[b.config.Accelerator]; !ok { - errs = packer.MultiErrorAppend( - errs, errors.New("invalid accelerator, only 'kvm', 'tcg', 'xen', 'hax', 'hvf', 'whpx', or 'none' are allowed")) - } - - if _, ok := diskInterface[b.config.DiskInterface]; !ok { - errs = packer.MultiErrorAppend( - errs, errors.New("unrecognized disk interface type")) - } - - if _, ok := diskCache[b.config.DiskCache]; !ok { - errs = packer.MultiErrorAppend( - errs, errors.New("unrecognized disk cache type")) - } - - if _, ok := diskDiscard[b.config.DiskDiscard]; !ok { - errs = packer.MultiErrorAppend( - errs, errors.New("unrecognized disk discard type")) - } - - if _, ok := diskDZeroes[b.config.DetectZeroes]; !ok { - errs = packer.MultiErrorAppend( - errs, errors.New("unrecognized disk detect zeroes setting")) - } - - if !b.config.PackerForce { - if _, err := os.Stat(b.config.OutputDir); err == nil { - errs = packer.MultiErrorAppend( - errs, - fmt.Errorf("Output directory '%s' already exists. It must not exist.", b.config.OutputDir)) - } - } - - if b.config.VNCPortMin > b.config.VNCPortMax { - errs = packer.MultiErrorAppend( - errs, fmt.Errorf("vnc_port_min must be less than vnc_port_max")) - } - - if b.config.NetBridge != "" && runtime.GOOS != "linux" { - errs = packer.MultiErrorAppend( - errs, fmt.Errorf("net_bridge is only supported in Linux based OSes")) - } - - if b.config.NetBridge != "" || b.config.VNCUsePassword { - b.config.QMPEnable = true - } - - if b.config.QMPEnable && b.config.QMPSocketPath == "" { - socketName := fmt.Sprintf("%s.monitor", b.config.VMName) - b.config.QMPSocketPath = filepath.Join(b.config.OutputDir, socketName) - } - - if b.config.QemuArgs == nil { - b.config.QemuArgs = make([][]string, 0) - } - - if errs != nil && len(errs.Errors) > 0 { + warnings, errs := b.config.Prepare(raws...) + if errs != nil { return nil, warnings, errs } @@ -579,15 +41,6 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack return nil, fmt.Errorf("Failed creating Qemu driver: %s", err) } - steprun := &stepRun{} - if !b.config.DiskImage { - steprun.BootDrive = "once=d" - steprun.Message = "Starting VM, booting from CD-ROM" - } else { - steprun.BootDrive = "c" - steprun.Message = "Starting VM, booting disk image" - } - steps := []multistep.Step{} if !b.config.ISOSkipCache { steps = append(steps, &common.StepDownload{ @@ -597,14 +50,12 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack ResultKey: "iso_path", TargetPath: b.config.TargetPath, Url: b.config.ISOUrls, - }, - ) + }) } else { steps = append(steps, &stepSetISO{ ResultKey: "iso_path", Url: b.config.ISOUrls, - }, - ) + }) } steps = append(steps, new(stepPrepareOutputDir), @@ -613,9 +64,37 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack Directories: b.config.FloppyConfig.FloppyDirectories, Label: b.config.FloppyConfig.FloppyLabel, }, - new(stepCreateDisk), - new(stepCopyDisk), - new(stepResizeDisk), + &common.StepCreateCD{ + Files: b.config.CDConfig.CDFiles, + Label: b.config.CDConfig.CDLabel, + }, + &stepCreateDisk{ + AdditionalDiskSize: b.config.AdditionalDiskSize, + DiskImage: b.config.DiskImage, + DiskSize: b.config.DiskSize, + Format: b.config.Format, + OutputDir: b.config.OutputDir, + UseBackingFile: b.config.UseBackingFile, + VMName: b.config.VMName, + QemuImgArgs: b.config.QemuImgArgs, + }, + &stepCopyDisk{ + DiskImage: b.config.DiskImage, + Format: b.config.Format, + OutputDir: b.config.OutputDir, + UseBackingFile: b.config.UseBackingFile, + VMName: b.config.VMName, + }, + &stepResizeDisk{ + DiskCompression: b.config.DiskCompression, + DiskImage: b.config.DiskImage, + Format: b.config.Format, + OutputDir: b.config.OutputDir, + SkipResizeDisk: b.config.SkipResizeDisk, + VMName: b.config.VMName, + DiskSize: b.config.DiskSize, + QemuImgArgs: b.config.QemuImgArgs, + }, new(stepHTTPIPDiscover), &common.StepHTTPServer{ HTTPDir: b.config.HTTPDir, @@ -623,58 +102,43 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack HTTPPortMax: b.config.HTTPPortMax, HTTPAddress: b.config.HTTPAddress, }, - ) - - if b.config.CommConfig.Comm.Type != "none" && b.config.NetBridge == "" { - steps = append(steps, - new(stepPortForward), - ) - } - - steps = append(steps, + &stepPortForward{ + CommunicatorType: b.config.CommConfig.Comm.Type, + NetBridge: b.config.NetBridge, + }, new(stepConfigureVNC), - steprun, + &stepRun{ + DiskImage: b.config.DiskImage, + }, &stepConfigureQMP{ QMPSocketPath: b.config.QMPSocketPath, }, &stepTypeBootCommand{}, - ) - - if b.config.CommConfig.Comm.Type != "none" && b.config.NetBridge != "" { - steps = append(steps, - &stepWaitGuestAddress{ - timeout: b.config.CommConfig.Comm.SSHTimeout, - }, - ) - } - - if b.config.CommConfig.Comm.Type != "none" { - steps = append(steps, - &communicator.StepConnect{ - Config: &b.config.CommConfig.Comm, - Host: commHost(b.config.CommConfig.Comm.Host()), - SSHConfig: b.config.CommConfig.Comm.SSHConfigFunc(), - SSHPort: commPort, - WinRMPort: commPort, - }, - ) - } - - steps = append(steps, + &stepWaitGuestAddress{ + CommunicatorType: b.config.CommConfig.Comm.Type, + NetBridge: b.config.NetBridge, + timeout: b.config.CommConfig.Comm.SSHTimeout, + }, + &communicator.StepConnect{ + Config: &b.config.CommConfig.Comm, + Host: commHost(b.config.CommConfig.Comm.Host()), + SSHConfig: b.config.CommConfig.Comm.SSHConfigFunc(), + SSHPort: commPort, + WinRMPort: commPort, + }, new(common.StepProvision), - ) - - steps = append(steps, &common.StepCleanupTempKeys{ Comm: &b.config.CommConfig.Comm, }, - ) - steps = append(steps, new(stepShutdown), - ) - - steps = append(steps, - new(stepConvertDisk), + &stepConvertDisk{ + DiskCompression: b.config.DiskCompression, + Format: b.config.Format, + OutputDir: b.config.OutputDir, + SkipCompaction: b.config.SkipCompaction, + VMName: b.config.VMName, + QemuImgArgs: b.config.QemuImgArgs, + }, ) // Setup the state bag diff --git a/builder/qemu/builder_test.go b/builder/qemu/builder_test.go index 3eb243abb..2efb1f612 100644 --- a/builder/qemu/builder_test.go +++ b/builder/qemu/builder_test.go @@ -1,56 +1,11 @@ package qemu import ( - "fmt" - "io/ioutil" - "os" - "path/filepath" - "reflect" "testing" - "time" "github.com/hashicorp/packer/packer" ) -var testPem = ` ------BEGIN RSA PRIVATE KEY----- -MIIEpQIBAAKCAQEAxd4iamvrwRJvtNDGQSIbNvvIQN8imXTRWlRY62EvKov60vqu -hh+rDzFYAIIzlmrJopvOe0clqmi3mIP9dtkjPFrYflq52a2CF5q+BdwsJXuRHbJW -LmStZUwW1khSz93DhvhmK50nIaczW63u4EO/jJb3xj+wxR1Nkk9bxi3DDsYFt8SN -AzYx9kjlEYQ/+sI4/ATfmdV9h78SVotjScupd9KFzzi76gWq9gwyCBLRynTUWlyD -2UOfJRkOvhN6/jKzvYfVVwjPSfA9IMuooHdScmC4F6KBKJl/zf/zETM0XyzIDNmH -uOPbCiljq2WoRM+rY6ET84EO0kVXbfx8uxUsqQIDAQABAoIBAQCkPj9TF0IagbM3 -5BSs/CKbAWS4dH/D4bPlxx4IRCNirc8GUg+MRb04Xz0tLuajdQDqeWpr6iLZ0RKV -BvreLF+TOdV7DNQ4XE4gSdJyCtCaTHeort/aordL3l0WgfI7mVk0L/yfN1PEG4YG -E9q1TYcyrB3/8d5JwIkjabxERLglCcP+geOEJp+QijbvFIaZR/n2irlKW4gSy6ko -9B0fgUnhkHysSg49ChHQBPQ+o5BbpuLrPDFMiTPTPhdfsvGGcyCGeqfBA56oHcSF -K02Fg8OM+Bd1lb48LAN9nWWY4WbwV+9bkN3Ym8hO4c3a/Dxf2N7LtAQqWZzFjvM3 -/AaDvAgBAoGBAPLD+Xn1IYQPMB2XXCXfOuJewRY7RzoVWvMffJPDfm16O7wOiW5+ -2FmvxUDayk4PZy6wQMzGeGKnhcMMZTyaq2g/QtGfrvy7q1Lw2fB1VFlVblvqhoJa -nMJojjC4zgjBkXMHsRLeTmgUKyGs+fdFbfI6uejBnnf+eMVUMIdJ+6I9AoGBANCn -kWO9640dttyXURxNJ3lBr2H3dJOkmD6XS+u+LWqCSKQe691Y/fZ/ZL0Oc4Mhy7I6 -hsy3kDQ5k2V0fkaNODQIFJvUqXw2pMewUk8hHc9403f4fe9cPrL12rQ8WlQw4yoC -v2B61vNczCCUDtGxlAaw8jzSRaSI5s6ax3K7enbdAoGBAJB1WYDfA2CoAQO6y9Sl -b07A/7kQ8SN5DbPaqrDrBdJziBQxukoMJQXJeGFNUFD/DXFU5Fp2R7C86vXT7HIR -v6m66zH+CYzOx/YE6EsUJms6UP9VIVF0Rg/RU7teXQwM01ZV32LQ8mswhTH20o/3 -uqMHmxUMEhZpUMhrfq0isyApAoGAe1UxGTXfj9AqkIVYylPIq2HqGww7+jFmVEj1 -9Wi6S6Sq72ffnzzFEPkIQL/UA4TsdHMnzsYKFPSbbXLIWUeMGyVTmTDA5c0e5XIR -lPhMOKCAzv8w4VUzMnEkTzkFY5JqFCD/ojW57KvDdNZPVB+VEcdxyAW6aKELXMAc -eHLc1nkCgYEApm/motCTPN32nINZ+Vvywbv64ZD+gtpeMNP3CLrbe1X9O+H52AXa -1jCoOldWR8i2bs2NVPcKZgdo6fFULqE4dBX7Te/uYEIuuZhYLNzRO1IKU/YaqsXG -3bfQ8hKYcSnTfE0gPtLDnqCIxTocaGLSHeG3TH9fTw+dA8FvWpUztI4= ------END RSA PRIVATE KEY----- -` - -func testConfig() map[string]interface{} { - return map[string]interface{}{ - "iso_checksum": "md5:0B0F137F17AC10944716020B018F8126", - "iso_url": "http://www.google.com/", - "ssh_username": "foo", - packer.BuildNameConfigKey: "foo", - } -} - func TestBuilder_ImplementsBuilder(t *testing.T) { var raw interface{} raw = &Builder{} @@ -58,601 +13,3 @@ func TestBuilder_ImplementsBuilder(t *testing.T) { t.Error("Builder must implement builder.") } } - -func TestBuilderPrepare_Defaults(t *testing.T) { - var b Builder - config := testConfig() - _, warns, err := b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("should not have error: %s", err) - } - - if b.config.OutputDir != "output-foo" { - t.Errorf("bad output dir: %s", b.config.OutputDir) - } - - if b.config.CommConfig.HostPortMin != 2222 { - t.Errorf("bad min ssh host port: %d", b.config.CommConfig.HostPortMin) - } - - if b.config.CommConfig.HostPortMax != 4444 { - t.Errorf("bad max ssh host port: %d", b.config.CommConfig.HostPortMax) - } - - if b.config.CommConfig.Comm.SSHPort != 22 { - t.Errorf("bad ssh port: %d", b.config.CommConfig.Comm.SSHPort) - } - - if b.config.VMName != "packer-foo" { - t.Errorf("bad vm name: %s", b.config.VMName) - } - - if b.config.Format != "qcow2" { - t.Errorf("bad format: %s", b.config.Format) - } -} - -func TestBuilderPrepare_VNCBindAddress(t *testing.T) { - var b Builder - config := testConfig() - - // Test a default boot_wait - delete(config, "vnc_bind_address") - _, warns, err := b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("err: %s", err) - } - - if b.config.VNCBindAddress != "127.0.0.1" { - t.Fatalf("bad value: %s", b.config.VNCBindAddress) - } -} - -func TestBuilderPrepare_DiskCompaction(t *testing.T) { - var b Builder - config := testConfig() - - // Bad - config["skip_compaction"] = false - config["disk_compression"] = true - config["format"] = "img" - _, warns, err := b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err == nil { - t.Fatal("should have error") - } - if b.config.SkipCompaction != true { - t.Fatalf("SkipCompaction should be true") - } - if b.config.DiskCompression != false { - t.Fatalf("DiskCompression should be false") - } - - // Good - config["skip_compaction"] = false - config["disk_compression"] = true - config["format"] = "qcow2" - b = Builder{} - _, warns, err = b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("should not have error: %s", err) - } - if b.config.SkipCompaction != false { - t.Fatalf("SkipCompaction should be false") - } - if b.config.DiskCompression != true { - t.Fatalf("DiskCompression should be true") - } -} - -func TestBuilderPrepare_DiskSize(t *testing.T) { - type testcase struct { - InputSize string - OutputSize string - ErrExpected bool - } - - testCases := []testcase{ - {"", "40960M", false}, // not provided - {"12345", "12345M", false}, // no unit given, defaults to M - {"12345x", "12345x", true}, // invalid unit - {"12345T", "12345T", false}, // terabytes - {"12345b", "12345b", false}, // bytes get preserved when set. - {"60000M", "60000M", false}, // Original test case - } - for _, tc := range testCases { - // Set input disk size - var b Builder - config := testConfig() - delete(config, "disk_size") - config["disk_size"] = tc.InputSize - - _, warns, err := b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if (err == nil) == tc.ErrExpected { - t.Fatalf("bad: error when providing disk size %s; Err expected: %t; err recieved: %v", tc.InputSize, tc.ErrExpected, err) - } - - if b.config.DiskSize != tc.OutputSize { - t.Fatalf("bad size: received: %s but expected %s", b.config.DiskSize, tc.OutputSize) - } - } -} - -func TestBuilderPrepare_AdditionalDiskSize(t *testing.T) { - var b Builder - config := testConfig() - - config["disk_additional_size"] = []string{"1M"} - config["disk_image"] = true - _, warns, err := b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err == nil { - t.Fatalf("should have error") - } - - delete(config, "disk_image") - config["disk_additional_size"] = []string{"1M"} - b = Builder{} - _, warns, err = b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("should not have error: %s", err) - } - - if b.config.AdditionalDiskSize[0] != "1M" { - t.Fatalf("bad size: %s", b.config.AdditionalDiskSize) - } -} - -func TestBuilderPrepare_Format(t *testing.T) { - var b Builder - config := testConfig() - - // Bad - config["format"] = "illegal value" - _, warns, err := b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err == nil { - t.Fatal("should have error") - } - - // Good - config["format"] = "qcow2" - b = Builder{} - _, warns, err = b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("should not have error: %s", err) - } - - // Good - config["format"] = "raw" - b = Builder{} - _, warns, err = b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("should not have error: %s", err) - } -} - -func TestBuilderPrepare_UseBackingFile(t *testing.T) { - var b Builder - config := testConfig() - - config["use_backing_file"] = true - - // Bad: iso_url is not a disk_image - config["disk_image"] = false - config["format"] = "qcow2" - b = Builder{} - _, warns, err := b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err == nil { - t.Fatal("should have error") - } - - // Bad: format is not 'qcow2' - config["disk_image"] = true - config["format"] = "raw" - b = Builder{} - _, warns, err = b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err == nil { - t.Fatal("should have error") - } - - // Good: iso_url is a disk image and format is 'qcow2' - config["disk_image"] = true - config["format"] = "qcow2" - b = Builder{} - _, warns, err = b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("should not have error: %s", err) - } -} - -func TestBuilderPrepare_FloppyFiles(t *testing.T) { - var b Builder - config := testConfig() - - delete(config, "floppy_files") - _, warns, err := b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("bad err: %s", err) - } - - if len(b.config.FloppyFiles) != 0 { - t.Fatalf("bad: %#v", b.config.FloppyFiles) - } - - floppies_path := "../../common/test-fixtures/floppies" - config["floppy_files"] = []string{fmt.Sprintf("%s/bar.bat", floppies_path), fmt.Sprintf("%s/foo.ps1", floppies_path)} - b = Builder{} - _, warns, err = b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("should not have error: %s", err) - } - - expected := []string{fmt.Sprintf("%s/bar.bat", floppies_path), fmt.Sprintf("%s/foo.ps1", floppies_path)} - if !reflect.DeepEqual(b.config.FloppyFiles, expected) { - t.Fatalf("bad: %#v", b.config.FloppyFiles) - } -} - -func TestBuilderPrepare_InvalidFloppies(t *testing.T) { - var b Builder - config := testConfig() - config["floppy_files"] = []string{"nonexistent.bat", "nonexistent.ps1"} - b = Builder{} - _, _, errs := b.Prepare(config) - if errs == nil { - t.Fatalf("Nonexistent floppies should trigger multierror") - } - - if len(errs.(*packer.MultiError).Errors) != 2 { - t.Fatalf("Multierror should work and report 2 errors") - } -} - -func TestBuilderPrepare_InvalidKey(t *testing.T) { - var b Builder - config := testConfig() - - // Add a random key - config["i_should_not_be_valid"] = true - _, warns, err := b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err == nil { - t.Fatal("should have error") - } -} - -func TestBuilderPrepare_OutputDir(t *testing.T) { - var b Builder - config := testConfig() - - // Test with existing dir - dir, err := ioutil.TempDir("", "packer") - if err != nil { - t.Fatalf("err: %s", err) - } - defer os.RemoveAll(dir) - - config["output_directory"] = dir - b = Builder{} - _, warns, err := b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err == nil { - t.Fatal("should have error") - } - - // Test with a good one - config["output_directory"] = "i-hope-i-dont-exist" - b = Builder{} - _, warns, err = b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("should not have error: %s", err) - } -} - -func TestBuilderPrepare_ShutdownTimeout(t *testing.T) { - var b Builder - config := testConfig() - - // Test with a bad value - config["shutdown_timeout"] = "this is not good" - _, warns, err := b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err == nil { - t.Fatal("should have error") - } - - // Test with a good one - config["shutdown_timeout"] = "5s" - b = Builder{} - _, warns, err = b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("should not have error: %s", err) - } -} - -func TestBuilderPrepare_SSHHostPort(t *testing.T) { - var b Builder - config := testConfig() - - // Bad - config["host_port_min"] = 1000 - config["host_port_max"] = 500 - b = Builder{} - _, warns, err := b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err == nil { - t.Fatal("should have error") - } - - // Bad - config["host_port_min"] = -500 - b = Builder{} - _, warns, err = b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err == nil { - t.Fatal("should have error") - } - - // Good - config["host_port_min"] = 500 - config["host_port_max"] = 1000 - b = Builder{} - _, warns, err = b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("should not have error: %s", err) - } -} - -func TestBuilderPrepare_SSHPrivateKey(t *testing.T) { - var b Builder - config := testConfig() - - config["ssh_private_key_file"] = "" - b = Builder{} - _, warns, err := b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("should not have error: %s", err) - } - - config["ssh_private_key_file"] = "/i/dont/exist" - b = Builder{} - _, warns, err = b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err == nil { - t.Fatal("should have error") - } - - // Test bad contents - tf, err := ioutil.TempFile("", "packer") - if err != nil { - t.Fatalf("err: %s", err) - } - defer os.Remove(tf.Name()) - defer tf.Close() - - if _, err := tf.Write([]byte("HELLO!")); err != nil { - t.Fatalf("err: %s", err) - } - - config["ssh_private_key_file"] = tf.Name() - b = Builder{} - _, warns, err = b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err == nil { - t.Fatal("should have error") - } - - // Test good contents - tf.Seek(0, 0) - tf.Truncate(0) - tf.Write([]byte(testPem)) - config["ssh_private_key_file"] = tf.Name() - b = Builder{} - _, warns, err = b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("err: %s", err) - } -} - -func TestBuilderPrepare_SSHWaitTimeout(t *testing.T) { - var b Builder - config := testConfig() - - // Test a default boot_wait - delete(config, "ssh_timeout") - _, warns, err := b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("err: %s", err) - } - - // Test with a bad value - config["ssh_timeout"] = "this is not good" - b = Builder{} - _, warns, err = b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err == nil { - t.Fatal("should have error") - } - - // Test with a good one - config["ssh_timeout"] = "5s" - b = Builder{} - _, warns, err = b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("should not have error: %s", err) - } -} - -func TestBuilderPrepare_QemuArgs(t *testing.T) { - var b Builder - config := testConfig() - - // Test with empty - delete(config, "qemuargs") - _, warns, err := b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("err: %s", err) - } - - if !reflect.DeepEqual(b.config.QemuArgs, [][]string{}) { - t.Fatalf("bad: %#v", b.config.QemuArgs) - } - - // Test with a good one - config["qemuargs"] = [][]interface{}{ - {"foo", "bar", "baz"}, - } - - b = Builder{} - _, warns, err = b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("should not have error: %s", err) - } - - expected := [][]string{ - {"foo", "bar", "baz"}, - } - - if !reflect.DeepEqual(b.config.QemuArgs, expected) { - t.Fatalf("bad: %#v", b.config.QemuArgs) - } -} - -func TestBuilderPrepare_VNCPassword(t *testing.T) { - var b Builder - config := testConfig() - - config["vnc_use_password"] = true - config["output_directory"] = "not-a-real-directory" - b = Builder{} - _, warns, err := b.Prepare(config) - if len(warns) > 0 { - t.Fatalf("bad: %#v", warns) - } - if err != nil { - t.Fatalf("should not have error: %s", err) - } - - expected := filepath.Join("not-a-real-directory", "packer-foo.monitor") - if !reflect.DeepEqual(b.config.QMPSocketPath, expected) { - t.Fatalf("Bad QMP socket Path: %s", b.config.QMPSocketPath) - } -} - -func TestCommConfigPrepare_BackwardsCompatibility(t *testing.T) { - var b Builder - config := testConfig() - hostPortMin := 1234 - hostPortMax := 4321 - sshTimeout := 2 * time.Minute - - config["ssh_wait_timeout"] = sshTimeout - config["ssh_host_port_min"] = hostPortMin - config["ssh_host_port_max"] = hostPortMax - - _, warns, err := b.Prepare(config) - if len(warns) == 0 { - t.Fatalf("should have deprecation warn") - } - if err != nil { - t.Fatalf("should not have error: %s", err) - } - - if b.config.CommConfig.Comm.SSHTimeout != sshTimeout { - t.Fatalf("SSHTimeout should be %s for backwards compatibility, but it was %s", sshTimeout.String(), b.config.CommConfig.Comm.SSHTimeout.String()) - } - - if b.config.CommConfig.HostPortMin != hostPortMin { - t.Fatalf("HostPortMin should be %d for backwards compatibility, but it was %d", hostPortMin, b.config.CommConfig.HostPortMin) - } - - if b.config.CommConfig.HostPortMax != hostPortMax { - t.Fatalf("HostPortMax should be %d for backwards compatibility, but it was %d", hostPortMax, b.config.CommConfig.HostPortMax) - } -} diff --git a/builder/qemu/config.go b/builder/qemu/config.go new file mode 100644 index 000000000..826b2edef --- /dev/null +++ b/builder/qemu/config.go @@ -0,0 +1,619 @@ +//go:generate struct-markdown +//go:generate mapstructure-to-hcl2 -type Config,QemuImgArgs + +package qemu + +import ( + "errors" + "fmt" + "log" + "os" + "path/filepath" + "regexp" + "runtime" + "strings" + + "github.com/hashicorp/packer/common" + "github.com/hashicorp/packer/common/bootcommand" + "github.com/hashicorp/packer/common/shutdowncommand" + "github.com/hashicorp/packer/helper/config" + "github.com/hashicorp/packer/packer" + "github.com/hashicorp/packer/template/interpolate" +) + +var accels = map[string]struct{}{ + "none": {}, + "kvm": {}, + "tcg": {}, + "xen": {}, + "hax": {}, + "hvf": {}, + "whpx": {}, +} + +var diskInterface = map[string]bool{ + "ide": true, + "scsi": true, + "virtio": true, + "virtio-scsi": true, +} + +var diskCache = map[string]bool{ + "writethrough": true, + "writeback": true, + "none": true, + "unsafe": true, + "directsync": true, +} + +var diskDiscard = map[string]bool{ + "unmap": true, + "ignore": true, +} + +var diskDZeroes = map[string]bool{ + "unmap": true, + "on": true, + "off": true, +} + +type QemuImgArgs struct { + Convert []string `mapstructure:"convert" required:"false"` + Create []string `mapstructure:"create" required:"false"` + Resize []string `mapstructure:"resize" required:"false"` +} + +type Config struct { + common.PackerConfig `mapstructure:",squash"` + common.HTTPConfig `mapstructure:",squash"` + common.ISOConfig `mapstructure:",squash"` + bootcommand.VNCConfig `mapstructure:",squash"` + shutdowncommand.ShutdownConfig `mapstructure:",squash"` + CommConfig CommConfig `mapstructure:",squash"` + common.FloppyConfig `mapstructure:",squash"` + common.CDConfig `mapstructure:",squash"` + // Use iso from provided url. Qemu must support + // curl block device. This defaults to `false`. + ISOSkipCache bool `mapstructure:"iso_skip_cache" required:"false"` + // The accelerator type to use when running the VM. + // This may be `none`, `kvm`, `tcg`, `hax`, `hvf`, `whpx`, or `xen`. The appropriate + // software must have already been installed on your build machine to use the + // accelerator you specified. When no accelerator is specified, Packer will try + // to use `kvm` if it is available but will default to `tcg` otherwise. + // + // ~> The `hax` accelerator has issues attaching CDROM ISOs. This is an + // upstream issue which can be tracked + // [here](https://github.com/intel/haxm/issues/20). + // + // ~> The `hvf` and `whpx` accelerator are new and experimental as of + // [QEMU 2.12.0](https://wiki.qemu.org/ChangeLog/2.12#Host_support). + // You may encounter issues unrelated to Packer when using these. You may need to + // add [ "-global", "virtio-pci.disable-modern=on" ] to `qemuargs` depending on the + // guest operating system. + // + // ~> For `whpx`, note that [Stefan Weil's QEMU for Windows distribution](https://qemu.weilnetz.de/w64/) + // does not include WHPX support and users may need to compile or source a + // build of QEMU for Windows themselves with WHPX support. + Accelerator string `mapstructure:"accelerator" required:"false"` + // Additional disks to create. Uses `vm_name` as the disk name template and + // appends `-#` where `#` is the position in the array. `#` starts at 1 since 0 + // is the default disk. Each string represents the disk image size in bytes. + // Optional suffixes 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' + // (gigabyte, 1024M), 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' + // (exabyte, 1024P) are supported. 'b' is ignored. Per qemu-img documentation. + // Each additional disk uses the same disk parameters as the default disk. + // Unset by default. + AdditionalDiskSize []string `mapstructure:"disk_additional_size" required:"false"` + // The number of cpus to use when building the VM. + // The default is `1` CPU. + CpuCount int `mapstructure:"cpus" required:"false"` + // The interface to use for the disk. Allowed values include any of `ide`, + // `scsi`, `virtio` or `virtio-scsi`^\*. Note also that any boot commands + // or kickstart type scripts must have proper adjustments for resulting + // device names. The Qemu builder uses `virtio` by default. + // + // ^\* Please be aware that use of the `scsi` disk interface has been + // disabled by Red Hat due to a bug described + // [here](https://bugzilla.redhat.com/show_bug.cgi?id=1019220). If you are + // running Qemu on RHEL or a RHEL variant such as CentOS, you *must* choose + // one of the other listed interfaces. Using the `scsi` interface under + // these circumstances will cause the build to fail. + DiskInterface string `mapstructure:"disk_interface" required:"false"` + // The size in bytes of the hard disk of the VM. Suffix with the first + // letter of common byte types. Use "k" or "K" for kilobytes, "M" for + // megabytes, G for gigabytes, and T for terabytes. If no value is provided + // for disk_size, Packer uses a default of `40960M` (40 GB). If a disk_size + // number is provided with no units, Packer will default to Megabytes. + DiskSize string `mapstructure:"disk_size" required:"false"` + // Packer resizes the QCOW2 image using + // qemu-img resize. Set this option to true to disable resizing. + // Defaults to false. + SkipResizeDisk bool `mapstructure:"skip_resize_disk" required:"false"` + // The cache mode to use for disk. Allowed values include any of + // `writethrough`, `writeback`, `none`, `unsafe` or `directsync`. By + // default, this is set to `writeback`. + DiskCache string `mapstructure:"disk_cache" required:"false"` + // The discard mode to use for disk. Allowed values + // include any of unmap or ignore. By default, this is set to ignore. + DiskDiscard string `mapstructure:"disk_discard" required:"false"` + // The detect-zeroes mode to use for disk. + // Allowed values include any of unmap, on or off. Defaults to off. + // When the value is "off" we don't set the flag in the qemu command, so that + // Packer still works with old versions of QEMU that don't have this option. + DetectZeroes string `mapstructure:"disk_detect_zeroes" required:"false"` + // Packer compacts the QCOW2 image using + // qemu-img convert. Set this option to true to disable compacting. + // Defaults to false. + SkipCompaction bool `mapstructure:"skip_compaction" required:"false"` + // Apply compression to the QCOW2 disk file + // using qemu-img convert. Defaults to false. + DiskCompression bool `mapstructure:"disk_compression" required:"false"` + // Either `qcow2` or `raw`, this specifies the output format of the virtual + // machine image. This defaults to `qcow2`. Due to a long-standing bug with + // `qemu-img convert` on OSX, sometimes the qemu-img convert call will + // create a corrupted image. If this is an issue for you, make sure that the + // the output format matches the input file's format, and Packer will + // perform a simple copy operation instead. See + // https://bugs.launchpad.net/qemu/+bug/1776920 for more details. + Format string `mapstructure:"format" required:"false"` + // Packer defaults to building QEMU virtual machines by + // launching a GUI that shows the console of the machine being built. When this + // value is set to `true`, the machine will start without a console. + // + // You can still see the console if you make a note of the VNC display + // number chosen, and then connect using `vncviewer -Shared :` + Headless bool `mapstructure:"headless" required:"false"` + // Packer defaults to building from an ISO file, this parameter controls + // whether the ISO URL supplied is actually a bootable QEMU image. When + // this value is set to `true`, the machine will either clone the source or + // use it as a backing file (if `use_backing_file` is `true`); then, it + // will resize the image according to `disk_size` and boot it. + DiskImage bool `mapstructure:"disk_image" required:"false"` + // Only applicable when disk_image is true + // and format is qcow2, set this option to true to create a new QCOW2 + // file that uses the file located at iso_url as a backing file. The new file + // will only contain blocks that have changed compared to the backing file, so + // enabling this option can significantly reduce disk usage. If true, Packer + // will force the `skip_compaction` also to be true as well to skip disk + // conversion which would render the backing file feature useless. + UseBackingFile bool `mapstructure:"use_backing_file" required:"false"` + // The type of machine emulation to use. Run your qemu binary with the + // flags `-machine help` to list available types for your system. This + // defaults to `pc`. + MachineType string `mapstructure:"machine_type" required:"false"` + // The amount of memory to use when building the VM + // in megabytes. This defaults to 512 megabytes. + MemorySize int `mapstructure:"memory" required:"false"` + // The driver to use for the network interface. Allowed values `ne2k_pci`, + // `i82551`, `i82557b`, `i82559er`, `rtl8139`, `e1000`, `pcnet`, `virtio`, + // `virtio-net`, `virtio-net-pci`, `usb-net`, `i82559a`, `i82559b`, + // `i82559c`, `i82550`, `i82562`, `i82557a`, `i82557c`, `i82801`, + // `vmxnet3`, `i82558a` or `i82558b`. The Qemu builder uses `virtio-net` by + // default. + NetDevice string `mapstructure:"net_device" required:"false"` + // Connects the network to this bridge instead of using the user mode + // networking. + // + // **NB** This bridge must already exist. You can use the `virbr0` bridge + // as created by vagrant-libvirt. + // + // **NB** This will automatically enable the QMP socket (see QMPEnable). + // + // **NB** This only works in Linux based OSes. + NetBridge string `mapstructure:"net_bridge" required:"false"` + // This is the path to the directory where the + // resulting virtual machine will be created. This may be relative or absolute. + // If relative, the path is relative to the working directory when packer + // is executed. This directory must not exist or be empty prior to running + // the builder. By default this is output-BUILDNAME where "BUILDNAME" is the + // name of the build. + OutputDir string `mapstructure:"output_directory" required:"false"` + // Allows complete control over the qemu command line (though not, at this + // time, qemu-img). Each array of strings makes up a command line switch + // that overrides matching default switch/value pairs. Any value specified + // as an empty string is ignored. All values after the switch are + // concatenated with no separator. + // + // ~> **Warning:** The qemu command line allows extreme flexibility, so + // beware of conflicting arguments causing failures of your run. For + // instance, using --no-acpi could break the ability to send power signal + // type commands (e.g., shutdown -P now) to the virtual machine, thus + // preventing proper shutdown. To see the defaults, look in the packer.log + // file and search for the qemu-system-x86 command. The arguments are all + // printed for review. + // + // The following shows a sample usage: + // + // In JSON: + // ```json + // "qemuargs": [ + // [ "-m", "1024M" ], + // [ "--no-acpi", "" ], + // [ + // "-netdev", + // "user,id=mynet0,", + // "hostfwd=hostip:hostport-guestip:guestport", + // "" + // ], + // [ "-device", "virtio-net,netdev=mynet0" ] + // ] + // ``` + // + // In HCL2: + // ```hcl + // qemuargs = [ + // [ "-m", "1024M" ], + // [ "--no-acpi", "" ], + // [ + // "-netdev", + // "user,id=mynet0,", + // "hostfwd=hostip:hostport-guestip:guestport", + // "" + // ], + // [ "-device", "virtio-net,netdev=mynet0" ] + // ] + // ``` + // + // would produce the following (not including other defaults supplied by + // the builder and not otherwise conflicting with the qemuargs): + // + // ```text + // qemu-system-x86 -m 1024m --no-acpi -netdev + // user,id=mynet0,hostfwd=hostip:hostport-guestip:guestport -device + // virtio-net,netdev=mynet0" + // ``` + // + // ~> **Windows Users:** [QEMU for Windows](https://qemu.weilnetz.de/) + // builds are available though an environmental variable does need to be + // set for QEMU for Windows to redirect stdout to the console instead of + // stdout.txt. + // + // The following shows the environment variable that needs to be set for + // Windows QEMU support: + // + // ```text + // setx SDL_STDIO_REDIRECT=0 + // ``` + // + // You can also use the `SSHHostPort` template variable to produce a packer + // template that can be invoked by `make` in parallel: + // + // In JSON: + // ```json + // "qemuargs": [ + // [ "-netdev", "user,hostfwd=tcp::{{ .SSHHostPort }}-:22,id=forward"], + // [ "-device", "virtio-net,netdev=forward,id=net0"] + // ] + // ``` + // + // In HCL2: + // ```hcl + // qemuargs = [ + // [ "-netdev", "user,hostfwd=tcp::{{ .SSHHostPort }}-:22,id=forward"], + // [ "-device", "virtio-net,netdev=forward,id=net0"] + // ] + // + // `make -j 3 my-awesome-packer-templates` spawns 3 packer processes, each + // of which will bind to their own SSH port as determined by each process. + // This will also work with WinRM, just change the port forward in + // `qemuargs` to map to WinRM's default port of `5985` or whatever value + // you have the service set to listen on. + // + // This is a template engine and allows access to the following variables: + // `{{ .HTTPIP }}`, `{{ .HTTPPort }}`, `{{ .HTTPDir }}`, + // `{{ .OutputDir }}`, `{{ .Name }}`, and `{{ .SSHHostPort }}` + QemuArgs [][]string `mapstructure:"qemuargs" required:"false"` + // A map of custom arguments to pass to qemu-img commands, where the key + // is the subcommand, and the values are lists of strings for each flag. + // Example: + // + // In JSON: + // ```json + // { + // "qemu_img_args": { + // "convert": ["-o", "preallocation=full"], + // "resize": ["-foo", "bar"] + // } + // ``` + // Please note + // that unlike qemuargs, these commands are not split into switch-value + // sub-arrays, because the basic elements in qemu-img calls are unlikely + // to need an actual override. + // The arguments will be constructed as follows: + // - Convert: + // Default is `qemu-img convert -O $format $sourcepath $targetpath`. Adding + // arguments ["-foo", "bar"] to qemu_img_args.convert will change this to + // `qemu-img convert -foo bar -O $format $sourcepath $targetpath` + // - Create: + // Default is `create -f $format $targetpath $size`. Adding arguments + // ["-foo", "bar"] to qemu_img_args.create will change this to + // "create -f qcow2 -foo bar target.qcow2 1234M" + // - Resize: + // Default is `qemu-img resize -f $format $sourcepath $size`. Adding + // arguments ["-foo", "bar"] to qemu_img_args.resize will change this to + // `qemu-img resize -f $format -foo bar $sourcepath $size` + QemuImgArgs QemuImgArgs `mapstructure:"qemu_img_args" required:"false"` + // The name of the Qemu binary to look for. This + // defaults to qemu-system-x86_64, but may need to be changed for + // some platforms. For example qemu-kvm, or qemu-system-i386 may be a + // better choice for some systems. + QemuBinary string `mapstructure:"qemu_binary" required:"false"` + // Enable QMP socket. Location is specified by `qmp_socket_path`. Defaults + // to false. + QMPEnable bool `mapstructure:"qmp_enable" required:"false"` + // QMP Socket Path when `qmp_enable` is true. Defaults to + // `output_directory`/`vm_name`.monitor. + QMPSocketPath string `mapstructure:"qmp_socket_path" required:"false"` + // If true, do not pass a -display option + // to qemu, allowing it to choose the default. This may be needed when running + // under macOS, and getting errors about sdl not being available. + UseDefaultDisplay bool `mapstructure:"use_default_display" required:"false"` + // What QEMU -display option to use. Defaults to gtk, use none to not pass the + // -display option allowing QEMU to choose the default. This may be needed when + // running under macOS, and getting errors about sdl not being available. + Display string `mapstructure:"display" required:"false"` + // The IP address that should be + // binded to for VNC. By default packer will use 127.0.0.1 for this. If you + // wish to bind to all interfaces use 0.0.0.0. + VNCBindAddress string `mapstructure:"vnc_bind_address" required:"false"` + // Whether or not to set a password on the VNC server. This option + // automatically enables the QMP socket. See `qmp_socket_path`. Defaults to + // `false`. + VNCUsePassword bool `mapstructure:"vnc_use_password" required:"false"` + // The minimum and maximum port + // to use for VNC access to the virtual machine. The builder uses VNC to type + // the initial boot_command. Because Packer generally runs in parallel, + // Packer uses a randomly chosen port in this range that appears available. By + // default this is 5900 to 6000. The minimum and maximum ports are inclusive. + VNCPortMin int `mapstructure:"vnc_port_min" required:"false"` + VNCPortMax int `mapstructure:"vnc_port_max"` + // This is the name of the image (QCOW2 or IMG) file for + // the new virtual machine. By default this is packer-BUILDNAME, where + // "BUILDNAME" is the name of the build. Currently, no file extension will be + // used unless it is specified in this option. + VMName string `mapstructure:"vm_name" required:"false"` + // The interface to use for the CDROM device which contains the ISO image. + // Allowed values include any of `ide`, `scsi`, `virtio` or + // `virtio-scsi`. The Qemu builder uses `virtio` by default. + // Some ARM64 images require `virtio-scsi`. + CDROMInterface string `mapstructure:"cdrom_interface" required:"false"` + + // TODO(mitchellh): deprecate + RunOnce bool `mapstructure:"run_once"` + + ctx interpolate.Context +} + +func (c *Config) Prepare(raws ...interface{}) ([]string, error) { + err := config.Decode(c, &config.DecodeOpts{ + Interpolate: true, + InterpolateContext: &c.ctx, + InterpolateFilter: &interpolate.RenderFilter{ + Exclude: []string{ + "boot_command", + "qemuargs", + }, + }, + }, raws...) + if err != nil { + return nil, err + } + + // Accumulate any errors and warnings + var errs *packer.MultiError + warnings := make([]string, 0) + + errs = packer.MultiErrorAppend(errs, c.ShutdownConfig.Prepare(&c.ctx)...) + + if c.DiskSize == "" || c.DiskSize == "0" { + c.DiskSize = "40960M" + } else { + // Make sure supplied disk size is valid + // (digits, plus an optional valid unit character). e.g. 5000, 40G, 1t + re := regexp.MustCompile(`^[\d]+(b|k|m|g|t){0,1}$`) + matched := re.MatchString(strings.ToLower(c.DiskSize)) + if !matched { + errs = packer.MultiErrorAppend(errs, fmt.Errorf("Invalid disk size.")) + } else { + // Okay, it's valid -- if it doesn't alreay have a suffix, then + // append "M" as the default unit. + re = regexp.MustCompile(`^[\d]+$`) + matched = re.MatchString(strings.ToLower(c.DiskSize)) + if matched { + // Needs M added. + c.DiskSize = fmt.Sprintf("%sM", c.DiskSize) + } + } + } + + if c.DiskCache == "" { + c.DiskCache = "writeback" + } + + if c.DiskDiscard == "" { + c.DiskDiscard = "ignore" + } + + if c.DetectZeroes == "" { + c.DetectZeroes = "off" + } + + if c.Accelerator == "" { + if runtime.GOOS == "windows" { + c.Accelerator = "tcg" + } else { + // /dev/kvm is a kernel module that may be loaded if kvm is + // installed and the host supports VT-x extensions. To make sure + // this will actually work we need to os.Open() it. If os.Open fails + // the kernel module was not installed or loaded correctly. + if fp, err := os.Open("/dev/kvm"); err != nil { + c.Accelerator = "tcg" + } else { + fp.Close() + c.Accelerator = "kvm" + } + } + log.Printf("use detected accelerator: %s", c.Accelerator) + } else { + log.Printf("use specified accelerator: %s", c.Accelerator) + } + + if c.MachineType == "" { + c.MachineType = "pc" + } + + if c.OutputDir == "" { + c.OutputDir = fmt.Sprintf("output-%s", c.PackerBuildName) + } + + if c.QemuBinary == "" { + c.QemuBinary = "qemu-system-x86_64" + } + + if c.MemorySize < 10 { + log.Printf("MemorySize %d is too small, using default: 512", c.MemorySize) + c.MemorySize = 512 + } + + if c.CpuCount < 1 { + log.Printf("CpuCount %d too small, using default: 1", c.CpuCount) + c.CpuCount = 1 + } + + if c.VNCBindAddress == "" { + c.VNCBindAddress = "127.0.0.1" + } + + if c.VNCPortMin == 0 { + c.VNCPortMin = 5900 + } + + if c.VNCPortMax == 0 { + c.VNCPortMax = 6000 + } + + if c.VMName == "" { + c.VMName = fmt.Sprintf("packer-%s", c.PackerBuildName) + } + + if c.Format == "" { + c.Format = "qcow2" + } + + errs = packer.MultiErrorAppend(errs, c.FloppyConfig.Prepare(&c.ctx)...) + errs = packer.MultiErrorAppend(errs, c.CDConfig.Prepare(&c.ctx)...) + errs = packer.MultiErrorAppend(errs, c.VNCConfig.Prepare(&c.ctx)...) + + if c.NetDevice == "" { + c.NetDevice = "virtio-net" + } + + if c.DiskInterface == "" { + c.DiskInterface = "virtio" + } + + if c.ISOSkipCache { + c.ISOChecksum = "none" + } + isoWarnings, isoErrs := c.ISOConfig.Prepare(&c.ctx) + warnings = append(warnings, isoWarnings...) + errs = packer.MultiErrorAppend(errs, isoErrs...) + + errs = packer.MultiErrorAppend(errs, c.HTTPConfig.Prepare(&c.ctx)...) + commConfigWarnings, es := c.CommConfig.Prepare(&c.ctx) + if len(es) > 0 { + errs = packer.MultiErrorAppend(errs, es...) + } + warnings = append(warnings, commConfigWarnings...) + + if !(c.Format == "qcow2" || c.Format == "raw") { + errs = packer.MultiErrorAppend( + errs, errors.New("invalid format, only 'qcow2' or 'raw' are allowed")) + } + + if c.Format != "qcow2" { + c.SkipCompaction = true + c.DiskCompression = false + } + + if c.UseBackingFile { + c.SkipCompaction = true + if !(c.DiskImage && c.Format == "qcow2") { + errs = packer.MultiErrorAppend( + errs, errors.New("use_backing_file can only be enabled for QCOW2 images and when disk_image is true")) + } + } + + if c.DiskImage && len(c.AdditionalDiskSize) > 0 { + errs = packer.MultiErrorAppend( + errs, errors.New("disk_additional_size can only be used when disk_image is false")) + } + + if c.SkipResizeDisk && !(c.DiskImage) { + errs = packer.MultiErrorAppend( + errs, errors.New("skip_resize_disk can only be used when disk_image is true")) + } + + if _, ok := accels[c.Accelerator]; !ok { + errs = packer.MultiErrorAppend( + errs, errors.New("invalid accelerator, only 'kvm', 'tcg', 'xen', 'hax', 'hvf', 'whpx', or 'none' are allowed")) + } + + if _, ok := diskInterface[c.DiskInterface]; !ok { + errs = packer.MultiErrorAppend( + errs, errors.New("unrecognized disk interface type")) + } + + if _, ok := diskCache[c.DiskCache]; !ok { + errs = packer.MultiErrorAppend( + errs, errors.New("unrecognized disk cache type")) + } + + if _, ok := diskDiscard[c.DiskDiscard]; !ok { + errs = packer.MultiErrorAppend( + errs, errors.New("unrecognized disk discard type")) + } + + if _, ok := diskDZeroes[c.DetectZeroes]; !ok { + errs = packer.MultiErrorAppend( + errs, errors.New("unrecognized disk detect zeroes setting")) + } + + if !c.PackerForce { + if _, err := os.Stat(c.OutputDir); err == nil { + errs = packer.MultiErrorAppend( + errs, + fmt.Errorf("Output directory '%s' already exists. It must not exist.", c.OutputDir)) + } + } + + if c.VNCPortMin > c.VNCPortMax { + errs = packer.MultiErrorAppend( + errs, fmt.Errorf("vnc_port_min must be less than vnc_port_max")) + } + + if c.NetBridge != "" && runtime.GOOS != "linux" { + errs = packer.MultiErrorAppend( + errs, fmt.Errorf("net_bridge is only supported in Linux based OSes")) + } + + if c.NetBridge != "" || c.VNCUsePassword { + c.QMPEnable = true + } + + if c.QMPEnable && c.QMPSocketPath == "" { + socketName := fmt.Sprintf("%s.monitor", c.VMName) + c.QMPSocketPath = filepath.Join(c.OutputDir, socketName) + } + + if c.QemuArgs == nil { + c.QemuArgs = make([][]string, 0) + } + + if errs != nil && len(errs.Errors) > 0 { + return warnings, errs + } + + return warnings, nil + +} diff --git a/builder/qemu/builder.hcl2spec.go b/builder/qemu/config.hcl2spec.go similarity index 91% rename from builder/qemu/builder.hcl2spec.go rename to builder/qemu/config.hcl2spec.go index 74cd2f6ca..cda5b683e 100644 --- a/builder/qemu/builder.hcl2spec.go +++ b/builder/qemu/config.hcl2spec.go @@ -1,4 +1,4 @@ -// Code generated by "mapstructure-to-hcl2 -type Config"; DO NOT EDIT. +// Code generated by "mapstructure-to-hcl2 -type Config,QemuImgArgs"; DO NOT EDIT. package qemu import ( @@ -20,6 +20,7 @@ type FlatConfig struct { HTTPPortMin *int `mapstructure:"http_port_min" cty:"http_port_min" hcl:"http_port_min"` HTTPPortMax *int `mapstructure:"http_port_max" cty:"http_port_max" hcl:"http_port_max"` HTTPAddress *string `mapstructure:"http_bind_address" cty:"http_bind_address" hcl:"http_bind_address"` + HTTPInterface *string `mapstructure:"http_interface" undocumented:"true" cty:"http_interface" hcl:"http_interface"` ISOChecksum *string `mapstructure:"iso_checksum" required:"true" cty:"iso_checksum" hcl:"iso_checksum"` RawSingleISOUrl *string `mapstructure:"iso_url" required:"true" cty:"iso_url" hcl:"iso_url"` ISOUrls []string `mapstructure:"iso_urls" cty:"iso_urls" hcl:"iso_urls"` @@ -87,12 +88,15 @@ type FlatConfig struct { FloppyFiles []string `mapstructure:"floppy_files" cty:"floppy_files" hcl:"floppy_files"` FloppyDirectories []string `mapstructure:"floppy_dirs" cty:"floppy_dirs" hcl:"floppy_dirs"` FloppyLabel *string `mapstructure:"floppy_label" cty:"floppy_label" hcl:"floppy_label"` + CDFiles []string `mapstructure:"cd_files" cty:"cd_files" hcl:"cd_files"` + CDLabel *string `mapstructure:"cd_label" cty:"cd_label" hcl:"cd_label"` ISOSkipCache *bool `mapstructure:"iso_skip_cache" required:"false" cty:"iso_skip_cache" hcl:"iso_skip_cache"` Accelerator *string `mapstructure:"accelerator" required:"false" cty:"accelerator" hcl:"accelerator"` AdditionalDiskSize []string `mapstructure:"disk_additional_size" required:"false" cty:"disk_additional_size" hcl:"disk_additional_size"` CpuCount *int `mapstructure:"cpus" required:"false" cty:"cpus" hcl:"cpus"` DiskInterface *string `mapstructure:"disk_interface" required:"false" cty:"disk_interface" hcl:"disk_interface"` DiskSize *string `mapstructure:"disk_size" required:"false" cty:"disk_size" hcl:"disk_size"` + SkipResizeDisk *bool `mapstructure:"skip_resize_disk" required:"false" cty:"skip_resize_disk" hcl:"skip_resize_disk"` DiskCache *string `mapstructure:"disk_cache" required:"false" cty:"disk_cache" hcl:"disk_cache"` DiskDiscard *string `mapstructure:"disk_discard" required:"false" cty:"disk_discard" hcl:"disk_discard"` DetectZeroes *string `mapstructure:"disk_detect_zeroes" required:"false" cty:"disk_detect_zeroes" hcl:"disk_detect_zeroes"` @@ -108,6 +112,7 @@ type FlatConfig struct { NetBridge *string `mapstructure:"net_bridge" required:"false" cty:"net_bridge" hcl:"net_bridge"` OutputDir *string `mapstructure:"output_directory" required:"false" cty:"output_directory" hcl:"output_directory"` QemuArgs [][]string `mapstructure:"qemuargs" required:"false" cty:"qemuargs" hcl:"qemuargs"` + QemuImgArgs *FlatQemuImgArgs `mapstructure:"qemu_img_args" required:"false" cty:"qemu_img_args" hcl:"qemu_img_args"` QemuBinary *string `mapstructure:"qemu_binary" required:"false" cty:"qemu_binary" hcl:"qemu_binary"` QMPEnable *bool `mapstructure:"qmp_enable" required:"false" cty:"qmp_enable" hcl:"qmp_enable"` QMPSocketPath *string `mapstructure:"qmp_socket_path" required:"false" cty:"qmp_socket_path" hcl:"qmp_socket_path"` @@ -145,6 +150,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "http_port_min": &hcldec.AttrSpec{Name: "http_port_min", Type: cty.Number, Required: false}, "http_port_max": &hcldec.AttrSpec{Name: "http_port_max", Type: cty.Number, Required: false}, "http_bind_address": &hcldec.AttrSpec{Name: "http_bind_address", Type: cty.String, Required: false}, + "http_interface": &hcldec.AttrSpec{Name: "http_interface", Type: cty.String, Required: false}, "iso_checksum": &hcldec.AttrSpec{Name: "iso_checksum", Type: cty.String, Required: false}, "iso_url": &hcldec.AttrSpec{Name: "iso_url", Type: cty.String, Required: false}, "iso_urls": &hcldec.AttrSpec{Name: "iso_urls", Type: cty.List(cty.String), Required: false}, @@ -212,12 +218,15 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "floppy_files": &hcldec.AttrSpec{Name: "floppy_files", Type: cty.List(cty.String), Required: false}, "floppy_dirs": &hcldec.AttrSpec{Name: "floppy_dirs", Type: cty.List(cty.String), Required: false}, "floppy_label": &hcldec.AttrSpec{Name: "floppy_label", Type: cty.String, Required: false}, + "cd_files": &hcldec.AttrSpec{Name: "cd_files", Type: cty.List(cty.String), Required: false}, + "cd_label": &hcldec.AttrSpec{Name: "cd_label", Type: cty.String, Required: false}, "iso_skip_cache": &hcldec.AttrSpec{Name: "iso_skip_cache", Type: cty.Bool, Required: false}, "accelerator": &hcldec.AttrSpec{Name: "accelerator", Type: cty.String, Required: false}, "disk_additional_size": &hcldec.AttrSpec{Name: "disk_additional_size", Type: cty.List(cty.String), Required: false}, "cpus": &hcldec.AttrSpec{Name: "cpus", Type: cty.Number, Required: false}, "disk_interface": &hcldec.AttrSpec{Name: "disk_interface", Type: cty.String, Required: false}, "disk_size": &hcldec.AttrSpec{Name: "disk_size", Type: cty.String, Required: false}, + "skip_resize_disk": &hcldec.AttrSpec{Name: "skip_resize_disk", Type: cty.Bool, Required: false}, "disk_cache": &hcldec.AttrSpec{Name: "disk_cache", Type: cty.String, Required: false}, "disk_discard": &hcldec.AttrSpec{Name: "disk_discard", Type: cty.String, Required: false}, "disk_detect_zeroes": &hcldec.AttrSpec{Name: "disk_detect_zeroes", Type: cty.String, Required: false}, @@ -233,6 +242,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "net_bridge": &hcldec.AttrSpec{Name: "net_bridge", Type: cty.String, Required: false}, "output_directory": &hcldec.AttrSpec{Name: "output_directory", Type: cty.String, Required: false}, "qemuargs": &hcldec.AttrSpec{Name: "qemuargs", Type: cty.List(cty.List(cty.String)), Required: false}, + "qemu_img_args": &hcldec.BlockSpec{TypeName: "qemu_img_args", Nested: hcldec.ObjectSpec((*FlatQemuImgArgs)(nil).HCL2Spec())}, "qemu_binary": &hcldec.AttrSpec{Name: "qemu_binary", Type: cty.String, Required: false}, "qmp_enable": &hcldec.AttrSpec{Name: "qmp_enable", Type: cty.Bool, Required: false}, "qmp_socket_path": &hcldec.AttrSpec{Name: "qmp_socket_path", Type: cty.String, Required: false}, @@ -248,3 +258,30 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { } return s } + +// FlatQemuImgArgs is an auto-generated flat version of QemuImgArgs. +// Where the contents of a field with a `mapstructure:,squash` tag are bubbled up. +type FlatQemuImgArgs struct { + Convert []string `mapstructure:"convert" required:"false" cty:"convert" hcl:"convert"` + Create []string `mapstructure:"create" required:"false" cty:"create" hcl:"create"` + Resize []string `mapstructure:"resize" required:"false" cty:"resize" hcl:"resize"` +} + +// FlatMapstructure returns a new FlatQemuImgArgs. +// FlatQemuImgArgs is an auto-generated flat version of QemuImgArgs. +// Where the contents a fields with a `mapstructure:,squash` tag are bubbled up. +func (*QemuImgArgs) FlatMapstructure() interface{ HCL2Spec() map[string]hcldec.Spec } { + return new(FlatQemuImgArgs) +} + +// HCL2Spec returns the hcl spec of a QemuImgArgs. +// This spec is used by HCL to read the fields of QemuImgArgs. +// The decoded values from this spec will then be applied to a FlatQemuImgArgs. +func (*FlatQemuImgArgs) HCL2Spec() map[string]hcldec.Spec { + s := map[string]hcldec.Spec{ + "convert": &hcldec.AttrSpec{Name: "convert", Type: cty.List(cty.String), Required: false}, + "create": &hcldec.AttrSpec{Name: "create", Type: cty.List(cty.String), Required: false}, + "resize": &hcldec.AttrSpec{Name: "resize", Type: cty.List(cty.String), Required: false}, + } + return s +} diff --git a/builder/qemu/config_test.go b/builder/qemu/config_test.go new file mode 100644 index 000000000..bd94d6eb8 --- /dev/null +++ b/builder/qemu/config_test.go @@ -0,0 +1,694 @@ +package qemu + +import ( + "fmt" + "io/ioutil" + "os" + "path/filepath" + "reflect" + "testing" + "time" + + "github.com/hashicorp/packer/packer" + "github.com/stretchr/testify/assert" +) + +var testPem = ` +-----BEGIN RSA PRIVATE KEY----- +MIIEpQIBAAKCAQEAxd4iamvrwRJvtNDGQSIbNvvIQN8imXTRWlRY62EvKov60vqu +hh+rDzFYAIIzlmrJopvOe0clqmi3mIP9dtkjPFrYflq52a2CF5q+BdwsJXuRHbJW +LmStZUwW1khSz93DhvhmK50nIaczW63u4EO/jJb3xj+wxR1Nkk9bxi3DDsYFt8SN +AzYx9kjlEYQ/+sI4/ATfmdV9h78SVotjScupd9KFzzi76gWq9gwyCBLRynTUWlyD +2UOfJRkOvhN6/jKzvYfVVwjPSfA9IMuooHdScmC4F6KBKJl/zf/zETM0XyzIDNmH +uOPbCiljq2WoRM+rY6ET84EO0kVXbfx8uxUsqQIDAQABAoIBAQCkPj9TF0IagbM3 +5BSs/CKbAWS4dH/D4bPlxx4IRCNirc8GUg+MRb04Xz0tLuajdQDqeWpr6iLZ0RKV +BvreLF+TOdV7DNQ4XE4gSdJyCtCaTHeort/aordL3l0WgfI7mVk0L/yfN1PEG4YG +E9q1TYcyrB3/8d5JwIkjabxERLglCcP+geOEJp+QijbvFIaZR/n2irlKW4gSy6ko +9B0fgUnhkHysSg49ChHQBPQ+o5BbpuLrPDFMiTPTPhdfsvGGcyCGeqfBA56oHcSF +K02Fg8OM+Bd1lb48LAN9nWWY4WbwV+9bkN3Ym8hO4c3a/Dxf2N7LtAQqWZzFjvM3 +/AaDvAgBAoGBAPLD+Xn1IYQPMB2XXCXfOuJewRY7RzoVWvMffJPDfm16O7wOiW5+ +2FmvxUDayk4PZy6wQMzGeGKnhcMMZTyaq2g/QtGfrvy7q1Lw2fB1VFlVblvqhoJa +nMJojjC4zgjBkXMHsRLeTmgUKyGs+fdFbfI6uejBnnf+eMVUMIdJ+6I9AoGBANCn +kWO9640dttyXURxNJ3lBr2H3dJOkmD6XS+u+LWqCSKQe691Y/fZ/ZL0Oc4Mhy7I6 +hsy3kDQ5k2V0fkaNODQIFJvUqXw2pMewUk8hHc9403f4fe9cPrL12rQ8WlQw4yoC +v2B61vNczCCUDtGxlAaw8jzSRaSI5s6ax3K7enbdAoGBAJB1WYDfA2CoAQO6y9Sl +b07A/7kQ8SN5DbPaqrDrBdJziBQxukoMJQXJeGFNUFD/DXFU5Fp2R7C86vXT7HIR +v6m66zH+CYzOx/YE6EsUJms6UP9VIVF0Rg/RU7teXQwM01ZV32LQ8mswhTH20o/3 +uqMHmxUMEhZpUMhrfq0isyApAoGAe1UxGTXfj9AqkIVYylPIq2HqGww7+jFmVEj1 +9Wi6S6Sq72ffnzzFEPkIQL/UA4TsdHMnzsYKFPSbbXLIWUeMGyVTmTDA5c0e5XIR +lPhMOKCAzv8w4VUzMnEkTzkFY5JqFCD/ojW57KvDdNZPVB+VEcdxyAW6aKELXMAc +eHLc1nkCgYEApm/motCTPN32nINZ+Vvywbv64ZD+gtpeMNP3CLrbe1X9O+H52AXa +1jCoOldWR8i2bs2NVPcKZgdo6fFULqE4dBX7Te/uYEIuuZhYLNzRO1IKU/YaqsXG +3bfQ8hKYcSnTfE0gPtLDnqCIxTocaGLSHeG3TH9fTw+dA8FvWpUztI4= +-----END RSA PRIVATE KEY----- +` + +func testConfig() map[string]interface{} { + return map[string]interface{}{ + "iso_checksum": "md5:0B0F137F17AC10944716020B018F8126", + "iso_url": "http://www.google.com/", + "ssh_username": "foo", + packer.BuildNameConfigKey: "foo", + } +} + +func TestBuilderPrepare_Defaults(t *testing.T) { + var c Config + config := testConfig() + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("should not have error: %s", err) + } + + if c.OutputDir != "output-foo" { + t.Errorf("bad output dir: %s", c.OutputDir) + } + + if c.CommConfig.HostPortMin != 2222 { + t.Errorf("bad min ssh host port: %d", c.CommConfig.HostPortMin) + } + + if c.CommConfig.HostPortMax != 4444 { + t.Errorf("bad max ssh host port: %d", c.CommConfig.HostPortMax) + } + + if c.CommConfig.Comm.SSHPort != 22 { + t.Errorf("bad ssh port: %d", c.CommConfig.Comm.SSHPort) + } + + if c.VMName != "packer-foo" { + t.Errorf("bad vm name: %s", c.VMName) + } + + if c.Format != "qcow2" { + t.Errorf("bad format: %s", c.Format) + } +} + +func TestBuilderPrepare_VNCBindAddress(t *testing.T) { + var c Config + config := testConfig() + + // Test a default boot_wait + delete(config, "vnc_bind_address") + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("err: %s", err) + } + + if c.VNCBindAddress != "127.0.0.1" { + t.Fatalf("bad value: %s", c.VNCBindAddress) + } +} + +func TestBuilderPrepare_DiskCompaction(t *testing.T) { + var c Config + config := testConfig() + + // Bad + config["skip_compaction"] = false + config["disk_compression"] = true + config["format"] = "img" + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err == nil { + t.Fatal("should have error") + } + if c.SkipCompaction != true { + t.Fatalf("SkipCompaction should be true") + } + if c.DiskCompression != false { + t.Fatalf("DiskCompression should be false") + } + + // Good + config["skip_compaction"] = false + config["disk_compression"] = true + config["format"] = "qcow2" + c = Config{} + warns, err = c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("should not have error: %s", err) + } + if c.SkipCompaction != false { + t.Fatalf("SkipCompaction should be false") + } + if c.DiskCompression != true { + t.Fatalf("DiskCompression should be true") + } +} + +func TestBuilderPrepare_DiskSize(t *testing.T) { + type testcase struct { + InputSize string + OutputSize string + ErrExpected bool + } + + testCases := []testcase{ + {"", "40960M", false}, // not provided + {"12345", "12345M", false}, // no unit given, defaults to M + {"12345x", "12345x", true}, // invalid unit + {"12345T", "12345T", false}, // terabytes + {"12345b", "12345b", false}, // bytes get preserved when set. + {"60000M", "60000M", false}, // Original test case + } + for _, tc := range testCases { + // Set input disk size + var c Config + config := testConfig() + delete(config, "disk_size") + config["disk_size"] = tc.InputSize + + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if (err == nil) == tc.ErrExpected { + t.Fatalf("bad: error when providing disk size %s; Err expected: %t; err recieved: %v", tc.InputSize, tc.ErrExpected, err) + } + + if c.DiskSize != tc.OutputSize { + t.Fatalf("bad size: received: %s but expected %s", c.DiskSize, tc.OutputSize) + } + } +} + +func TestBuilderPrepare_AdditionalDiskSize(t *testing.T) { + var c Config + config := testConfig() + + config["disk_additional_size"] = []string{"1M"} + config["disk_image"] = true + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err == nil { + t.Fatalf("should have error") + } + + delete(config, "disk_image") + config["disk_additional_size"] = []string{"1M"} + c = Config{} + warns, err = c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("should not have error: %s", err) + } + + if c.AdditionalDiskSize[0] != "1M" { + t.Fatalf("bad size: %s", c.AdditionalDiskSize) + } +} + +func TestBuilderPrepare_Format(t *testing.T) { + var c Config + config := testConfig() + + // Bad + config["format"] = "illegal value" + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err == nil { + t.Fatal("should have error") + } + + // Good + config["format"] = "qcow2" + c = Config{} + warns, err = c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("should not have error: %s", err) + } + + // Good + config["format"] = "raw" + c = Config{} + warns, err = c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("should not have error: %s", err) + } +} + +func TestBuilderPrepare_UseBackingFile(t *testing.T) { + var c Config + config := testConfig() + + config["use_backing_file"] = true + + // Bad: iso_url is not a disk_image + config["disk_image"] = false + config["format"] = "qcow2" + c = Config{} + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err == nil { + t.Fatal("should have error") + } + + // Bad: format is not 'qcow2' + config["disk_image"] = true + config["format"] = "raw" + c = Config{} + warns, err = c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err == nil { + t.Fatal("should have error") + } + + // Good: iso_url is a disk image and format is 'qcow2' + config["disk_image"] = true + config["format"] = "qcow2" + c = Config{} + warns, err = c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("should not have error: %s", err) + } +} + +func TestBuilderPrepare_SkipResizeDisk(t *testing.T) { + config := testConfig() + config["skip_resize_disk"] = true + config["disk_image"] = false + + var c Config + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Errorf("unexpected warns when calling prepare with skip_resize_disk set to true: %#v", warns) + } + if err == nil { + t.Errorf("setting skip_resize_disk to true when disk_image is false should have error") + } +} + +func TestBuilderPrepare_FloppyFiles(t *testing.T) { + var c Config + config := testConfig() + + delete(config, "floppy_files") + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("bad err: %s", err) + } + + if len(c.FloppyFiles) != 0 { + t.Fatalf("bad: %#v", c.FloppyFiles) + } + + floppies_path := "../../common/test-fixtures/floppies" + config["floppy_files"] = []string{fmt.Sprintf("%s/bar.bat", floppies_path), fmt.Sprintf("%s/foo.ps1", floppies_path)} + c = Config{} + warns, err = c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("should not have error: %s", err) + } + + expected := []string{fmt.Sprintf("%s/bar.bat", floppies_path), fmt.Sprintf("%s/foo.ps1", floppies_path)} + if !reflect.DeepEqual(c.FloppyFiles, expected) { + t.Fatalf("bad: %#v", c.FloppyFiles) + } +} + +func TestBuilderPrepare_InvalidFloppies(t *testing.T) { + var c Config + config := testConfig() + config["floppy_files"] = []string{"nonexistent.bat", "nonexistent.ps1"} + c = Config{} + _, errs := c.Prepare(config) + if errs == nil { + t.Fatalf("Nonexistent floppies should trigger multierror") + } + + if len(errs.(*packer.MultiError).Errors) != 2 { + t.Fatalf("Multierror should work and report 2 errors") + } +} + +func TestBuilderPrepare_InvalidKey(t *testing.T) { + var c Config + config := testConfig() + + // Add a random key + config["i_should_not_be_valid"] = true + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err == nil { + t.Fatal("should have error") + } +} + +func TestBuilderPrepare_OutputDir(t *testing.T) { + var c Config + config := testConfig() + + // Test with existing dir + dir, err := ioutil.TempDir("", "packer") + if err != nil { + t.Fatalf("err: %s", err) + } + defer os.RemoveAll(dir) + + config["output_directory"] = dir + c = Config{} + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err == nil { + t.Fatal("should have error") + } + + // Test with a good one + config["output_directory"] = "i-hope-i-dont-exist" + c = Config{} + warns, err = c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("should not have error: %s", err) + } +} + +func TestBuilderPrepare_ShutdownTimeout(t *testing.T) { + var c Config + config := testConfig() + + // Test with a bad value + config["shutdown_timeout"] = "this is not good" + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err == nil { + t.Fatal("should have error") + } + + // Test with a good one + config["shutdown_timeout"] = "5s" + c = Config{} + warns, err = c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("should not have error: %s", err) + } +} + +func TestBuilderPrepare_SSHHostPort(t *testing.T) { + var c Config + config := testConfig() + + // Bad + config["host_port_min"] = 1000 + config["host_port_max"] = 500 + c = Config{} + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err == nil { + t.Fatal("should have error") + } + + // Bad + config["host_port_min"] = -500 + c = Config{} + warns, err = c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err == nil { + t.Fatal("should have error") + } + + // Good + config["host_port_min"] = 500 + config["host_port_max"] = 1000 + c = Config{} + warns, err = c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("should not have error: %s", err) + } +} + +func TestBuilderPrepare_SSHPrivateKey(t *testing.T) { + var c Config + config := testConfig() + + config["ssh_private_key_file"] = "" + c = Config{} + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("should not have error: %s", err) + } + + config["ssh_private_key_file"] = "/i/dont/exist" + c = Config{} + warns, err = c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err == nil { + t.Fatal("should have error") + } + + // Test bad contents + tf, err := ioutil.TempFile("", "packer") + if err != nil { + t.Fatalf("err: %s", err) + } + defer os.Remove(tf.Name()) + defer tf.Close() + + if _, err := tf.Write([]byte("HELLO!")); err != nil { + t.Fatalf("err: %s", err) + } + + config["ssh_private_key_file"] = tf.Name() + c = Config{} + warns, err = c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err == nil { + t.Fatal("should have error") + } + + // Test good contents + if _, err := tf.Seek(0, 0); err != nil { + t.Fatalf("errorf getting key") + } + if err := tf.Truncate(0); err != nil { + t.Fatalf("errorf getting key") + } + if _, err := tf.Write([]byte(testPem)); err != nil { + t.Fatalf("errorf getting key") + } + config["ssh_private_key_file"] = tf.Name() + c = Config{} + warns, err = c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("err: %s", err) + } +} + +func TestBuilderPrepare_SSHWaitTimeout(t *testing.T) { + var c Config + config := testConfig() + + // Test a default boot_wait + delete(config, "ssh_timeout") + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("err: %s", err) + } + + // Test with a bad value + config["ssh_timeout"] = "this is not good" + c = Config{} + warns, err = c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err == nil { + t.Fatal("should have error") + } + + // Test with a good one + config["ssh_timeout"] = "5s" + c = Config{} + warns, err = c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("should not have error: %s", err) + } +} + +func TestBuilderPrepare_QemuArgs(t *testing.T) { + var c Config + config := testConfig() + + // Test with empty + delete(config, "qemuargs") + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("err: %s", err) + } + + if !reflect.DeepEqual(c.QemuArgs, [][]string{}) { + t.Fatalf("bad: %#v", c.QemuArgs) + } + + // Test with a good one + config["qemuargs"] = [][]interface{}{ + {"foo", "bar", "baz"}, + } + + c = Config{} + warns, err = c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("should not have error: %s", err) + } + + expected := [][]string{ + {"foo", "bar", "baz"}, + } + + if !reflect.DeepEqual(c.QemuArgs, expected) { + t.Fatalf("bad: %#v", c.QemuArgs) + } +} + +func TestBuilderPrepare_VNCPassword(t *testing.T) { + var c Config + config := testConfig() + config["vnc_use_password"] = true + config["output_directory"] = "not-a-real-directory" + + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("should not have error: %s", err) + } + + expected := filepath.Join("not-a-real-directory", "packer-foo.monitor") + if !reflect.DeepEqual(c.QMPSocketPath, expected) { + t.Fatalf("Bad QMP socket Path: %s", c.QMPSocketPath) + } +} + +func TestCommConfigPrepare_BackwardsCompatibility(t *testing.T) { + var c Config + config := testConfig() + hostPortMin := 1234 + hostPortMax := 4321 + sshTimeout := 2 * time.Minute + + config["ssh_wait_timeout"] = sshTimeout + config["ssh_host_port_min"] = hostPortMin + config["ssh_host_port_max"] = hostPortMax + + warns, err := c.Prepare(config) + if len(warns) == 0 { + t.Fatalf("should have deprecation warn") + } + if err != nil { + t.Fatalf("should not have error: %s", err) + } + + if c.CommConfig.Comm.SSHTimeout != sshTimeout { + t.Fatalf("SSHTimeout should be %s for backwards compatibility, but it was %s", sshTimeout.String(), c.CommConfig.Comm.SSHTimeout.String()) + } + + if c.CommConfig.HostPortMin != hostPortMin { + t.Fatalf("HostPortMin should be %d for backwards compatibility, but it was %d", hostPortMin, c.CommConfig.HostPortMin) + } + + if c.CommConfig.HostPortMax != hostPortMax { + t.Fatalf("HostPortMax should be %d for backwards compatibility, but it was %d", hostPortMax, c.CommConfig.HostPortMax) + } +} + +func TestBuilderPrepare_LoadQemuImgArgs(t *testing.T) { + var c Config + config := testConfig() + config["qemu_img_args"] = map[string][]string{ + "convert": []string{"-o", "preallocation=full"}, + "resize": []string{"-foo", "bar"}, + "create": []string{"-baz", "bang"}, + } + warns, err := c.Prepare(config) + if len(warns) > 0 { + t.Fatalf("bad: %#v", warns) + } + if err != nil { + t.Fatalf("should not have error: %s", err) + } + assert.Equal(t, []string{"-o", "preallocation=full"}, + c.QemuImgArgs.Convert, "Convert args not loaded properly") + assert.Equal(t, []string{"-foo", "bar"}, + c.QemuImgArgs.Resize, "Resize args not loaded properly") + assert.Equal(t, []string{"-baz", "bang"}, + c.QemuImgArgs.Create, "Create args not loaded properly") +} diff --git a/builder/qemu/driver.go b/builder/qemu/driver.go index 000c0b915..d4b600c11 100644 --- a/builder/qemu/driver.go +++ b/builder/qemu/driver.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "log" + "os" "os/exec" "regexp" "strings" @@ -22,6 +23,10 @@ type DriverCancelCallback func(state multistep.StateBag) bool // A driver is able to talk to qemu-system-x86_64 and perform certain // operations with it. type Driver interface { + // Copy bypasses qemu-img convert and directly copies an image + // that doesn't need converting. + Copy(string, string) error + // Stop stops a running machine, forcefully. Stop() error @@ -65,6 +70,33 @@ func (d *QemuDriver) Stop() error { return nil } +func (d *QemuDriver) Copy(sourceName, targetName string) error { + source, err := os.Open(sourceName) + if err != nil { + err = fmt.Errorf("Error opening iso for copy: %s", err) + return err + } + defer source.Close() + + // Create will truncate an existing file + target, err := os.Create(targetName) + if err != nil { + err = fmt.Errorf("Error creating hard drive in output dir: %s", err) + return err + } + defer target.Close() + + log.Printf("Copying %s to %s", source.Name(), target.Name()) + bytes, err := io.Copy(target, source) + if err != nil { + err = fmt.Errorf("Error copying iso to output dir: %s", err) + return err + } + log.Printf(fmt.Sprintf("Copied %d bytes", bytes)) + + return nil +} + func (d *QemuDriver) Qemu(qemuArgs ...string) error { d.lock.Lock() defer d.lock.Unlock() diff --git a/builder/qemu/driver_mock.go b/builder/qemu/driver_mock.go new file mode 100644 index 000000000..7fa1a7df7 --- /dev/null +++ b/builder/qemu/driver_mock.go @@ -0,0 +1,74 @@ +package qemu + +import "sync" + +type DriverMock struct { + sync.Mutex + + CopyCalled bool + CopyErr error + + StopCalled bool + StopErr error + + QemuCalls [][]string + QemuErrs []error + + WaitForShutdownCalled bool + WaitForShutdownState bool + + QemuImgCalled bool + QemuImgCalls []string + QemuImgErrs []error + + VerifyCalled bool + VerifyErr error + + VersionCalled bool + VersionResult string + VersionErr error +} + +func (d *DriverMock) Copy(source, dst string) error { + d.CopyCalled = true + return d.CopyErr +} + +func (d *DriverMock) Stop() error { + d.StopCalled = true + return d.StopErr +} + +func (d *DriverMock) Qemu(args ...string) error { + d.QemuCalls = append(d.QemuCalls, args) + + if len(d.QemuErrs) >= len(d.QemuCalls) { + return d.QemuErrs[len(d.QemuCalls)-1] + } + return nil +} + +func (d *DriverMock) WaitForShutdown(cancelCh <-chan struct{}) bool { + d.WaitForShutdownCalled = true + return d.WaitForShutdownState +} + +func (d *DriverMock) QemuImg(args ...string) error { + d.QemuImgCalled = true + d.QemuImgCalls = append(d.QemuImgCalls, args...) + + if len(d.QemuImgErrs) >= len(d.QemuImgCalls) { + return d.QemuImgErrs[len(d.QemuImgCalls)-1] + } + return nil +} + +func (d *DriverMock) Verify() error { + d.VerifyCalled = true + return d.VerifyErr +} + +func (d *DriverMock) Version() (string, error) { + d.VersionCalled = true + return d.VersionResult, d.VersionErr +} diff --git a/builder/qemu/step_convert_disk.go b/builder/qemu/step_convert_disk.go index 249efb414..8e06cc821 100644 --- a/builder/qemu/step_convert_disk.go +++ b/builder/qemu/step_convert_disk.go @@ -17,37 +17,32 @@ import ( // This step converts the virtual disk that was used as the // hard drive for the virtual machine. -type stepConvertDisk struct{} +type stepConvertDisk struct { + DiskCompression bool + Format string + OutputDir string + SkipCompaction bool + VMName string + + QemuImgArgs QemuImgArgs +} func (s *stepConvertDisk) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { - config := state.Get("config").(*Config) driver := state.Get("driver").(Driver) - diskName := config.VMName ui := state.Get("ui").(packer.Ui) - if config.SkipCompaction && !config.DiskCompression { + diskName := s.VMName + + if s.SkipCompaction && !s.DiskCompression { return multistep.ActionContinue } name := diskName + ".convert" - sourcePath := filepath.Join(config.OutputDir, diskName) - targetPath := filepath.Join(config.OutputDir, name) + sourcePath := filepath.Join(s.OutputDir, diskName) + targetPath := filepath.Join(s.OutputDir, name) - command := []string{ - "convert", - } - - if config.DiskCompression { - command = append(command, "-c") - } - - command = append(command, []string{ - "-O", config.Format, - sourcePath, - targetPath, - }..., - ) + command := s.buildConvertCommand(sourcePath, targetPath) ui.Say("Converting hard drive...") // Retry the conversion a few times in case it takes the qemu process a @@ -90,4 +85,20 @@ func (s *stepConvertDisk) Run(ctx context.Context, state multistep.StateBag) mul return multistep.ActionContinue } +func (s *stepConvertDisk) buildConvertCommand(sourcePath, targetPath string) []string { + command := []string{"convert"} + + if s.DiskCompression { + command = append(command, "-c") + } + + // Add user-provided convert args + command = append(command, s.QemuImgArgs.Convert...) + + // Add format, and paths. + command = append(command, "-O", s.Format, sourcePath, targetPath) + + return command +} + func (s *stepConvertDisk) Cleanup(state multistep.StateBag) {} diff --git a/builder/qemu/step_convert_disk_test.go b/builder/qemu/step_convert_disk_test.go new file mode 100644 index 000000000..e6ff4b0c4 --- /dev/null +++ b/builder/qemu/step_convert_disk_test.go @@ -0,0 +1,52 @@ +package qemu + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_buildConvertCommand(t *testing.T) { + type testCase struct { + Step *stepConvertDisk + Expected []string + Reason string + } + testcases := []testCase{ + { + &stepConvertDisk{ + Format: "qcow2", + DiskCompression: false, + }, + []string{"convert", "-O", "qcow2", "source.qcow", "target.qcow2"}, + "Basic, happy path, no compression, no extra args", + }, + { + &stepConvertDisk{ + Format: "qcow2", + DiskCompression: true, + }, + []string{"convert", "-c", "-O", "qcow2", "source.qcow", "target.qcow2"}, + "Basic, happy path, with compression, no extra args", + }, + { + &stepConvertDisk{ + Format: "qcow2", + DiskCompression: true, + QemuImgArgs: QemuImgArgs{ + Convert: []string{"-o", "preallocation=full"}, + }, + }, + []string{"convert", "-c", "-o", "preallocation=full", "-O", "qcow2", "source.qcow", "target.qcow2"}, + "Basic, happy path, with compression, one set of extra args", + }, + } + + for _, tc := range testcases { + command := tc.Step.buildConvertCommand("source.qcow", "target.qcow2") + + assert.Equal(t, command, tc.Expected, + fmt.Sprintf("%s. Expected %#v", tc.Reason, tc.Expected)) + } +} diff --git a/builder/qemu/step_copy_disk.go b/builder/qemu/step_copy_disk.go index dc59ddb7d..28a091426 100644 --- a/builder/qemu/step_copy_disk.go +++ b/builder/qemu/step_copy_disk.go @@ -11,26 +11,42 @@ import ( // This step copies the virtual disk that will be used as the // hard drive for the virtual machine. -type stepCopyDisk struct{} +type stepCopyDisk struct { + DiskImage bool + Format string + OutputDir string + UseBackingFile bool + VMName string + + QemuImgArgs QemuImgArgs +} func (s *stepCopyDisk) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { - config := state.Get("config").(*Config) driver := state.Get("driver").(Driver) isoPath := state.Get("iso_path").(string) ui := state.Get("ui").(packer.Ui) - path := filepath.Join(config.OutputDir, config.VMName) + path := filepath.Join(s.OutputDir, s.VMName) - command := []string{ - "convert", - "-O", config.Format, - isoPath, - path, - } - - if !config.DiskImage || config.UseBackingFile { + if !s.DiskImage || s.UseBackingFile { return multistep.ActionContinue } + // isoPath extention is: + ext := filepath.Ext(isoPath) + if ext[1:] == s.Format { + ui.Message("File extension already matches desired output format. " + + "Skipping qemu-img convert step") + err := driver.Copy(isoPath, path) + if err != nil { + state.Put("error", err) + ui.Error(err.Error()) + return multistep.ActionHalt + } + return multistep.ActionContinue + } + + command := s.buildConvertCommand(isoPath, path) + ui.Say("Copying hard drive...") if err := driver.QemuImg(command...); err != nil { err := fmt.Errorf("Error creating hard drive: %s", err) @@ -42,4 +58,16 @@ func (s *stepCopyDisk) Run(ctx context.Context, state multistep.StateBag) multis return multistep.ActionContinue } +func (s *stepCopyDisk) buildConvertCommand(sourcePath, targetPath string) []string { + command := []string{"convert"} + + // Add user-provided convert args + command = append(command, s.QemuImgArgs.Convert...) + + // Add format, and paths. + command = append(command, "-O", s.Format, sourcePath, targetPath) + + return command +} + func (s *stepCopyDisk) Cleanup(state multistep.StateBag) {} diff --git a/builder/qemu/step_copy_disk_test.go b/builder/qemu/step_copy_disk_test.go new file mode 100644 index 000000000..b7241621e --- /dev/null +++ b/builder/qemu/step_copy_disk_test.go @@ -0,0 +1,122 @@ +package qemu + +import ( + "context" + "testing" + + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" + "github.com/stretchr/testify/assert" +) + +func copyTestState(t *testing.T, d *DriverMock) multistep.StateBag { + state := new(multistep.BasicStateBag) + state.Put("ui", packer.TestUi(t)) + state.Put("driver", d) + state.Put("iso_path", "example_source.qcow2") + + return state +} + +func Test_StepCopySkip(t *testing.T) { + testcases := []stepCopyDisk{ + stepCopyDisk{ + DiskImage: false, + UseBackingFile: false, + }, + stepCopyDisk{ + DiskImage: true, + UseBackingFile: true, + }, + stepCopyDisk{ + DiskImage: false, + UseBackingFile: true, + }, + } + + for _, tc := range testcases { + d := new(DriverMock) + state := copyTestState(t, d) + action := tc.Run(context.TODO(), state) + if action != multistep.ActionContinue { + t.Fatalf("Should have gotten an ActionContinue") + } + + if d.CopyCalled || d.QemuImgCalled { + t.Fatalf("Should have skipped step since DiskImage and UseBackingFile are not set") + } + } +} + +func Test_StepCopyCalled(t *testing.T) { + step := stepCopyDisk{ + DiskImage: true, + Format: "qcow2", + VMName: "output.qcow2", + } + + d := new(DriverMock) + state := copyTestState(t, d) + action := step.Run(context.TODO(), state) + if action != multistep.ActionContinue { + t.Fatalf("Should have gotten an ActionContinue") + } + + if !d.CopyCalled { + t.Fatalf("Should have copied since all extensions are qcow2") + } + if d.QemuImgCalled { + t.Fatalf("Should not have called qemu-img when formats match") + } +} + +func Test_StepQemuImgCalled(t *testing.T) { + step := stepCopyDisk{ + DiskImage: true, + Format: "raw", + VMName: "output.qcow2", + } + + d := new(DriverMock) + state := copyTestState(t, d) + action := step.Run(context.TODO(), state) + if action != multistep.ActionContinue { + t.Fatalf("Should have gotten an ActionContinue") + } + if d.CopyCalled { + t.Fatalf("Should not have copied since extensions don't match") + } + if !d.QemuImgCalled { + t.Fatalf("Should have called qemu-img since extensions don't match") + } +} + +func Test_StepQemuImgCalledWithExtraArgs(t *testing.T) { + step := &stepCopyDisk{ + DiskImage: true, + Format: "raw", + VMName: "output.qcow2", + QemuImgArgs: QemuImgArgs{ + Convert: []string{"-o", "preallocation=full"}, + }, + } + + d := new(DriverMock) + state := copyTestState(t, d) + action := step.Run(context.TODO(), state) + if action != multistep.ActionContinue { + t.Fatalf("Should have gotten an ActionContinue") + } + if d.CopyCalled { + t.Fatalf("Should not have copied since extensions don't match") + } + if !d.QemuImgCalled { + t.Fatalf("Should have called qemu-img since extensions don't match") + } + assert.Equal( + t, + d.QemuImgCalls, + []string{"convert", "-o", "preallocation=full", "-O", "raw", + "example_source.qcow2", "output.qcow2"}, + "should have added user extra args") +} diff --git a/builder/qemu/step_create_disk.go b/builder/qemu/step_create_disk.go index cc904f8fc..288bb02dc 100644 --- a/builder/qemu/step_create_disk.go +++ b/builder/qemu/step_create_disk.go @@ -12,15 +12,23 @@ import ( // This step creates the virtual disk that will be used as the // hard drive for the virtual machine. -type stepCreateDisk struct{} +type stepCreateDisk struct { + AdditionalDiskSize []string + DiskImage bool + DiskSize string + Format string + OutputDir string + UseBackingFile bool + VMName string + QemuImgArgs QemuImgArgs +} func (s *stepCreateDisk) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { - config := state.Get("config").(*Config) driver := state.Get("driver").(Driver) ui := state.Get("ui").(packer.Ui) - name := config.VMName + name := s.VMName - if config.DiskImage && !config.UseBackingFile { + if s.DiskImage && !s.UseBackingFile { return multistep.ActionContinue } @@ -28,12 +36,12 @@ func (s *stepCreateDisk) Run(ctx context.Context, state multistep.StateBag) mult ui.Say("Creating required virtual machine disks") // The 'main' or 'default' disk - diskFullPaths = append(diskFullPaths, filepath.Join(config.OutputDir, name)) - diskSizes = append(diskSizes, config.DiskSize) + diskFullPaths = append(diskFullPaths, filepath.Join(s.OutputDir, name)) + diskSizes = append(diskSizes, s.DiskSize) // Additional disks - if len(config.AdditionalDiskSize) > 0 { - for i, diskSize := range config.AdditionalDiskSize { - path := filepath.Join(config.OutputDir, fmt.Sprintf("%s-%d", name, i+1)) + if len(s.AdditionalDiskSize) > 0 { + for i, diskSize := range s.AdditionalDiskSize { + path := filepath.Join(s.OutputDir, fmt.Sprintf("%s-%d", name, i+1)) diskFullPaths = append(diskFullPaths, path) size := diskSize diskSizes = append(diskSizes, size) @@ -43,19 +51,8 @@ func (s *stepCreateDisk) Run(ctx context.Context, state multistep.StateBag) mult // Create all required disks for i, diskFullPath := range diskFullPaths { log.Printf("[INFO] Creating disk with Path: %s and Size: %s", diskFullPath, diskSizes[i]) - command := []string{ - "create", - "-f", config.Format, - } - if config.UseBackingFile && i == 0 { - isoPath := state.Get("iso_path").(string) - command = append(command, "-b", isoPath) - } - - command = append(command, - diskFullPath, - diskSizes[i]) + command := s.buildCreateCommand(diskFullPath, diskSizes[i], i, state) if err := driver.QemuImg(command...); err != nil { err := fmt.Errorf("Error creating hard drive: %s", err) @@ -71,4 +68,21 @@ func (s *stepCreateDisk) Run(ctx context.Context, state multistep.StateBag) mult return multistep.ActionContinue } +func (s *stepCreateDisk) buildCreateCommand(path string, size string, i int, state multistep.StateBag) []string { + command := []string{"create", "-f", s.Format} + + if s.UseBackingFile && i == 0 { + isoPath := state.Get("iso_path").(string) + command = append(command, "-b", isoPath) + } + + // add user-provided convert args + command = append(command, s.QemuImgArgs.Create...) + + // add target path and size. + command = append(command, path, size) + + return command +} + func (s *stepCreateDisk) Cleanup(state multistep.StateBag) {} diff --git a/builder/qemu/step_create_disk_test.go b/builder/qemu/step_create_disk_test.go new file mode 100644 index 000000000..22fa59283 --- /dev/null +++ b/builder/qemu/step_create_disk_test.go @@ -0,0 +1,80 @@ +package qemu + +import ( + "fmt" + "testing" + + "github.com/hashicorp/packer/helper/multistep" + "github.com/stretchr/testify/assert" +) + +func Test_buildCreateCommand(t *testing.T) { + type testCase struct { + Step *stepCreateDisk + I int + Expected []string + Reason string + } + testcases := []testCase{ + { + &stepCreateDisk{ + Format: "qcow2", + UseBackingFile: false, + }, + 0, + []string{"create", "-f", "qcow2", "target.qcow2", "1234M"}, + "Basic, happy path, no backing store, no extra args", + }, + { + &stepCreateDisk{ + Format: "qcow2", + UseBackingFile: true, + }, + 0, + []string{"create", "-f", "qcow2", "-b", "source.qcow2", "target.qcow2", "1234M"}, + "Basic, happy path, backing store, no extra args", + }, + { + &stepCreateDisk{ + Format: "qcow2", + UseBackingFile: true, + }, + 1, + []string{"create", "-f", "qcow2", "target.qcow2", "1234M"}, + "Basic, happy path, backing store set but not at first index, no extra args", + }, + { + &stepCreateDisk{ + Format: "qcow2", + UseBackingFile: true, + QemuImgArgs: QemuImgArgs{ + Create: []string{"-foo", "bar"}, + }, + }, + 0, + []string{"create", "-f", "qcow2", "-b", "source.qcow2", "-foo", "bar", "target.qcow2", "1234M"}, + "Basic, happy path, backing store set, extra args", + }, + { + &stepCreateDisk{ + Format: "qcow2", + UseBackingFile: true, + QemuImgArgs: QemuImgArgs{ + Create: []string{"-foo", "bar"}, + }, + }, + 1, + []string{"create", "-f", "qcow2", "-foo", "bar", "target.qcow2", "1234M"}, + "Basic, happy path, backing store set but not at first index, extra args", + }, + } + + for _, tc := range testcases { + state := new(multistep.BasicStateBag) + state.Put("iso_path", "source.qcow2") + command := tc.Step.buildCreateCommand("target.qcow2", "1234M", tc.I, state) + + assert.Equal(t, command, tc.Expected, + fmt.Sprintf("%s. Expected %#v", tc.Reason, tc.Expected)) + } +} diff --git a/builder/qemu/step_port_forward.go b/builder/qemu/step_port_forward.go index e4f24b691..ab5871fa2 100644 --- a/builder/qemu/step_port_forward.go +++ b/builder/qemu/step_port_forward.go @@ -13,6 +13,9 @@ import ( // This step adds a NAT port forwarding definition so that SSH or WinRM is available // on the guest machine. type stepPortForward struct { + CommunicatorType string + NetBridge string + l *net.Listener } @@ -20,6 +23,15 @@ func (s *stepPortForward) Run(ctx context.Context, state multistep.StateBag) mul config := state.Get("config").(*Config) ui := state.Get("ui").(packer.Ui) + if s.CommunicatorType == "none" { + ui.Message("No communicator is set; skipping port forwarding setup.") + return multistep.ActionContinue + } + if s.NetBridge != "" { + ui.Message("net_bridge is set; skipping port forwarding setup.") + return multistep.ActionContinue + } + commHostPort := config.CommConfig.Comm.Port() if config.CommConfig.SkipNatMapping { diff --git a/builder/qemu/step_resize_disk.go b/builder/qemu/step_resize_disk.go index 74949281b..09863e327 100644 --- a/builder/qemu/step_resize_disk.go +++ b/builder/qemu/step_resize_disk.go @@ -11,21 +11,26 @@ import ( // This step resizes the virtual disk that will be used as the // hard drive for the virtual machine. -type stepResizeDisk struct{} +type stepResizeDisk struct { + DiskCompression bool + DiskImage bool + Format string + OutputDir string + SkipResizeDisk bool + VMName string + DiskSize string + + QemuImgArgs QemuImgArgs +} func (s *stepResizeDisk) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { - config := state.Get("config").(*Config) driver := state.Get("driver").(Driver) ui := state.Get("ui").(packer.Ui) - path := filepath.Join(config.OutputDir, config.VMName) + path := filepath.Join(s.OutputDir, s.VMName) - command := []string{ - "resize", - "-f", config.Format, - path, - config.DiskSize, - } - if config.DiskImage == false { + command := s.buildResizeCommand(path) + + if s.DiskImage == false || s.SkipResizeDisk == true { return multistep.ActionContinue } @@ -40,4 +45,16 @@ func (s *stepResizeDisk) Run(ctx context.Context, state multistep.StateBag) mult return multistep.ActionContinue } +func (s *stepResizeDisk) buildResizeCommand(path string) []string { + command := []string{"resize", "-f", s.Format} + + // add user-provided convert args + command = append(command, s.QemuImgArgs.Resize...) + + // Add file and size + command = append(command, path, s.DiskSize) + + return command +} + func (s *stepResizeDisk) Cleanup(state multistep.StateBag) {} diff --git a/builder/qemu/step_resize_disk_test.go b/builder/qemu/step_resize_disk_test.go new file mode 100644 index 000000000..796ec20cb --- /dev/null +++ b/builder/qemu/step_resize_disk_test.go @@ -0,0 +1,77 @@ +package qemu + +import ( + "context" + "fmt" + "testing" + + "github.com/hashicorp/packer/helper/multistep" + "github.com/stretchr/testify/assert" +) + +func TestStepResizeDisk_Skips(t *testing.T) { + testConfigs := []*Config{ + &Config{ + DiskImage: false, + SkipResizeDisk: false, + }, + &Config{ + DiskImage: false, + SkipResizeDisk: true, + }, + } + for _, config := range testConfigs { + state := testState(t) + driver := state.Get("driver").(*DriverMock) + + state.Put("config", config) + step := new(stepResizeDisk) + + // Test the run + if action := step.Run(context.Background(), state); action != multistep.ActionContinue { + t.Fatalf("bad action: %#v", action) + } + if _, ok := state.GetOk("error"); ok { + t.Fatal("should NOT have error") + } + if len(driver.QemuImgCalls) > 0 { + t.Fatal("should NOT have called qemu-img") + } + } +} + +func Test_buildResizeCommand(t *testing.T) { + type testCase struct { + Step *stepResizeDisk + Expected []string + Reason string + } + testcases := []testCase{ + { + &stepResizeDisk{ + Format: "qcow2", + DiskSize: "1234M", + }, + []string{"resize", "-f", "qcow2", "source.qcow", "1234M"}, + "no extra args", + }, + { + &stepResizeDisk{ + Format: "qcow2", + DiskSize: "1234M", + QemuImgArgs: QemuImgArgs{ + Resize: []string{"-foo", "bar"}, + }, + }, + []string{"resize", "-f", "qcow2", "-foo", "bar", "source.qcow", "1234M"}, + "one set of extra args", + }, + } + + for _, tc := range testcases { + command := tc.Step.buildResizeCommand("source.qcow") + + assert.Equal(t, command, tc.Expected, + fmt.Sprintf("%s. Expected %#v", tc.Reason, tc.Expected)) + } +} diff --git a/builder/qemu/step_run.go b/builder/qemu/step_run.go index 5a3a2d708..d7f60d37f 100644 --- a/builder/qemu/step_run.go +++ b/builder/qemu/step_run.go @@ -15,8 +15,7 @@ import ( // stepRun runs the virtual machine type stepRun struct { - BootDrive string - Message string + DiskImage bool } type qemuArgsTemplateData struct { @@ -32,9 +31,17 @@ func (s *stepRun) Run(ctx context.Context, state multistep.StateBag) multistep.S driver := state.Get("driver").(Driver) ui := state.Get("ui").(packer.Ui) - ui.Say(s.Message) + // Run command is different depending whether we're booting from an + // installation CD or a pre-baked image + bootDrive := "once=d" + message := "Starting VM, booting from CD-ROM" + if s.DiskImage { + bootDrive = "c" + message = "Starting VM, booting disk image" + } + ui.Say(message) - command, err := getCommandArgs(s.BootDrive, state) + command, err := getCommandArgs(bootDrive, state) if err != nil { err := fmt.Errorf("Error processing QemuArgs: %s", err) ui.Error(err.Error()) @@ -73,12 +80,11 @@ func getCommandArgs(bootDrive string, state multistep.StateBag) ([]string, error var deviceArgs []string var driveArgs []string var commHostPort int - var vnc string - if !config.VNCUsePassword { - vnc = fmt.Sprintf("%s:%d", vncIP, vncPort-5900) - } else { - vnc = fmt.Sprintf("%s:%d,password", vncIP, vncPort-5900) + vncPort = vncPort - config.VNCPortMin + vnc := fmt.Sprintf("%s:%d", vncIP, vncPort) + if config.VNCUsePassword { + vnc = fmt.Sprintf("%s:%d,password", vncIP, vncPort) } if config.QMPEnable { @@ -191,14 +197,26 @@ func getCommandArgs(bootDrive string, state multistep.StateBag) ([]string, error } } + cdPaths := []string{} + // Add the installation CD to the run command if !config.DiskImage { + cdPaths = append(cdPaths, isoPath) + } + // Add our custom CD created from cd_files, if it exists + cdFilesPath, ok := state.Get("cd_path").(string) + if ok { + if cdFilesPath != "" { + cdPaths = append(cdPaths, cdFilesPath) + } + } + for i, cdPath := range cdPaths { if config.CDROMInterface == "" { - defaultArgs["-cdrom"] = isoPath + driveArgs = append(driveArgs, fmt.Sprintf("file=%s,index=%d,media=cdrom", cdPath, i)) } else if config.CDROMInterface == "virtio-scsi" { - driveArgs = append(driveArgs, fmt.Sprintf("file=%s,if=none,id=cdrom,media=cdrom", isoPath)) - deviceArgs = append(deviceArgs, "virtio-scsi-device", "scsi-cd,drive=cdrom") + driveArgs = append(driveArgs, fmt.Sprintf("file=%s,if=none,index=%d,id=cdrom%d,media=cdrom", cdPath, i, i)) + deviceArgs = append(deviceArgs, "virtio-scsi-device", fmt.Sprintf("scsi-cd,drive=cdrom%d", i)) } else { - driveArgs = append(driveArgs, fmt.Sprintf("file=%s,if=%s,id=cdrom,media=cdrom", isoPath, config.CDROMInterface)) + driveArgs = append(driveArgs, fmt.Sprintf("file=%s,if=%s,index=%d,id=cdrom%d,media=cdrom", cdPath, config.CDROMInterface, i, i)) } } @@ -229,7 +247,7 @@ func getCommandArgs(bootDrive string, state multistep.StateBag) ([]string, error inArgs := make(map[string][]string) if len(config.QemuArgs) > 0 { - ui.Say("Overriding defaults Qemu arguments with QemuArgs...") + ui.Say("Overriding default Qemu arguments with QemuArgs...") httpIp := state.Get("http_ip").(string) httpPort := state.Get("http_port").(int) diff --git a/builder/qemu/step_run_test.go b/builder/qemu/step_run_test.go new file mode 100644 index 000000000..1facfce12 --- /dev/null +++ b/builder/qemu/step_run_test.go @@ -0,0 +1,148 @@ +package qemu + +import ( + "fmt" + "testing" + + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" + "github.com/stretchr/testify/assert" +) + +func runTestState(t *testing.T, config *Config) multistep.StateBag { + state := new(multistep.BasicStateBag) + + state.Put("ui", packer.TestUi(t)) + state.Put("config", config) + + d := new(DriverMock) + d.VersionResult = "3.0.0" + state.Put("driver", d) + + state.Put("commHostPort", 5000) + state.Put("floppy_path", "fake_floppy_path") + state.Put("http_ip", "127.0.0.1") + state.Put("http_port", 1234) + state.Put("iso_path", "/path/to/test.iso") + state.Put("qemu_disk_paths", []string{}) + state.Put("vnc_port", 5905) + state.Put("vnc_password", "fake_vnc_password") + + return state +} + +func Test_getCommandArgs(t *testing.T) { + state := runTestState(t, &Config{}) + + args, err := getCommandArgs("", state) + if err != nil { + t.Fatalf("should not have an error getting args. Error: %s", err) + } + + expected := []string{ + "-display", "gtk", + "-m", "0M", + "-boot", "", + "-fda", "fake_floppy_path", + "-name", "", + "-netdev", "user,id=user.0,hostfwd=tcp::5000-:0", + "-vnc", ":5905", + "-machine", "type=,accel=", + "-device", ",netdev=user.0", + "-drive", "file=/path/to/test.iso,index=0,media=cdrom", + } + + assert.ElementsMatch(t, args, expected, "unexpected generated args") +} + +func Test_CDFilesPath(t *testing.T) { + // cd_path is set and DiskImage is false + state := runTestState(t, &Config{}) + state.Put("cd_path", "fake_cd_path.iso") + + args, err := getCommandArgs("", state) + if err != nil { + t.Fatalf("should not have an error getting args. Error: %s", err) + } + + expected := []string{ + "-display", "gtk", + "-m", "0M", + "-boot", "", + "-fda", "fake_floppy_path", + "-name", "", + "-netdev", "user,id=user.0,hostfwd=tcp::5000-:0", + "-vnc", ":5905", + "-machine", "type=,accel=", + "-device", ",netdev=user.0", + "-drive", "file=/path/to/test.iso,index=0,media=cdrom", + "-drive", "file=fake_cd_path.iso,index=1,media=cdrom", + } + + assert.ElementsMatch(t, args, expected, fmt.Sprintf("unexpected generated args: %#v", args)) + + // cd_path is set and DiskImage is true + config := &Config{ + DiskImage: true, + DiskInterface: "virtio-scsi", + } + state = runTestState(t, config) + state.Put("cd_path", "fake_cd_path.iso") + + args, err = getCommandArgs("c", state) + if err != nil { + t.Fatalf("should not have an error getting args. Error: %s", err) + } + + expected = []string{ + "-display", "gtk", + "-m", "0M", + "-boot", "c", + "-fda", "fake_floppy_path", + "-name", "", + "-netdev", "user,id=user.0,hostfwd=tcp::5000-:0", + "-vnc", ":5905", + "-machine", "type=,accel=", + "-device", ",netdev=user.0", + "-device", "virtio-scsi-pci,id=scsi0", + "-device", "scsi-hd,bus=scsi0.0,drive=drive0", + "-drive", "if=none,file=,id=drive0,cache=,discard=,format=,detect-zeroes=", + "-drive", "file=fake_cd_path.iso,index=0,media=cdrom", + } + + assert.ElementsMatch(t, args, expected, fmt.Sprintf("unexpected generated args: %#v", args)) +} + +func Test_OptionalConfigOptionsGetSet(t *testing.T) { + c := &Config{ + VNCUsePassword: true, + QMPEnable: true, + QMPSocketPath: "qmp_path", + VMName: "MyFancyName", + MachineType: "pc", + Accelerator: "hvf", + } + + state := runTestState(t, c) + + args, err := getCommandArgs("once=d", state) + if err != nil { + t.Fatalf("should not have an error getting args. Error: %s", err) + } + + expected := []string{ + "-display", "gtk", + "-m", "0M", + "-boot", "once=d", + "-fda", "fake_floppy_path", + "-name", "MyFancyName", + "-netdev", "user,id=user.0,hostfwd=tcp::5000-:0", + "-vnc", ":5905,password", + "-machine", "type=pc,accel=hvf", + "-device", ",netdev=user.0", + "-drive", "file=/path/to/test.iso,index=0,media=cdrom", + "-qmp", "unix:qmp_path,server,nowait", + } + + assert.ElementsMatch(t, args, expected, "password flag should be set, and d drive should be set.") +} diff --git a/builder/qemu/step_test.go b/builder/qemu/step_test.go new file mode 100644 index 000000000..4a782d1d4 --- /dev/null +++ b/builder/qemu/step_test.go @@ -0,0 +1,19 @@ +package qemu + +import ( + "bytes" + "testing" + + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" +) + +func testState(t *testing.T) multistep.StateBag { + state := new(multistep.BasicStateBag) + state.Put("driver", new(DriverMock)) + state.Put("ui", &packer.BasicUi{ + Reader: new(bytes.Buffer), + Writer: new(bytes.Buffer), + }) + return state +} diff --git a/builder/qemu/step_wait_guest_address.go b/builder/qemu/step_wait_guest_address.go index b1541d9ec..7e6f9ad1e 100644 --- a/builder/qemu/step_wait_guest_address.go +++ b/builder/qemu/step_wait_guest_address.go @@ -19,19 +19,31 @@ import ( // This step waits for the guest address to become available in the network // bridge, then it sets the guestAddress state property. type stepWaitGuestAddress struct { + CommunicatorType string + NetBridge string + timeout time.Duration } func (s *stepWaitGuestAddress) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { - config := state.Get("config").(*Config) ui := state.Get("ui").(packer.Ui) + + if s.CommunicatorType == "none" { + ui.Message("No communicator is configured -- skipping StepWaitGuestAddress") + return multistep.ActionContinue + } + if s.NetBridge == "" { + ui.Message("Not using a NetBridge -- skipping StepWaitGuestAddress") + return multistep.ActionContinue + } + qmpMonitor := state.Get("qmp_monitor").(*qmp.SocketMonitor) ctx, cancel := context.WithTimeout(ctx, s.timeout) defer cancel() - ui.Say(fmt.Sprintf("Waiting for the guest address to become available in the %s network bridge...", config.NetBridge)) + ui.Say(fmt.Sprintf("Waiting for the guest address to become available in the %s network bridge...", s.NetBridge)) for { - guestAddress := getGuestAddress(qmpMonitor, config.NetBridge, "user.0") + guestAddress := getGuestAddress(qmpMonitor, s.NetBridge, "user.0") if guestAddress != "" { log.Printf("Found guest address %s", guestAddress) state.Put("guestAddress", guestAddress) diff --git a/builder/scaleway/artifact.go b/builder/scaleway/artifact.go index 0e103cc42..6fe31ee7d 100644 --- a/builder/scaleway/artifact.go +++ b/builder/scaleway/artifact.go @@ -4,7 +4,8 @@ import ( "fmt" "log" - "github.com/scaleway/scaleway-cli/pkg/api" + "github.com/scaleway/scaleway-sdk-go/api/instance/v1" + "github.com/scaleway/scaleway-sdk-go/scw" ) type Artifact struct { @@ -20,11 +21,11 @@ type Artifact struct { // The ID of the snapshot snapshotID string - // The name of the region - regionName string + // The name of the zone + zoneName string // The client for making API calls - client *api.ScalewayAPI + client *scw.Client // StateData should store data such as GeneratedData // to be shared with post-processors @@ -41,12 +42,12 @@ func (*Artifact) Files() []string { } func (a *Artifact) Id() string { - return fmt.Sprintf("%s:%s", a.regionName, a.imageID) + return fmt.Sprintf("%s:%s", a.zoneName, a.imageID) } func (a *Artifact) String() string { - return fmt.Sprintf("An image was created: '%v' (ID: %v) in region '%v' based on snapshot '%v' (ID: %v)", - a.imageName, a.imageID, a.regionName, a.snapshotName, a.snapshotID) + return fmt.Sprintf("An image was created: '%v' (ID: %v) in zone '%v' based on snapshot '%v' (ID: %v)", + a.imageName, a.imageID, a.zoneName, a.snapshotName, a.snapshotID) } func (a *Artifact) State(name string) interface{} { @@ -55,11 +56,19 @@ func (a *Artifact) State(name string) interface{} { func (a *Artifact) Destroy() error { log.Printf("Destroying image: %s (%s)", a.imageID, a.imageName) - if err := a.client.DeleteImage(a.imageID); err != nil { + instanceAPI := instance.NewAPI(a.client) + + err := instanceAPI.DeleteImage(&instance.DeleteImageRequest{ + ImageID: a.imageID, + }) + if err != nil { return err } log.Printf("Destroying snapshot: %s (%s)", a.snapshotID, a.snapshotName) - if err := a.client.DeleteSnapshot(a.snapshotID); err != nil { + err = instanceAPI.DeleteSnapshot(&instance.DeleteSnapshotRequest{ + SnapshotID: a.snapshotID, + }) + if err != nil { return err } return nil diff --git a/builder/scaleway/artifact_test.go b/builder/scaleway/artifact_test.go index 3583fd4e3..619e2ebc2 100644 --- a/builder/scaleway/artifact_test.go +++ b/builder/scaleway/artifact_test.go @@ -27,7 +27,7 @@ func TestArtifactId(t *testing.T) { func TestArtifactString(t *testing.T) { generatedData := make(map[string]interface{}) a := &Artifact{"packer-foobar-image", "cc586e45-5156-4f71-b223-cf406b10dd1d", "packer-foobar-snapshot", "cc586e45-5156-4f71-b223-cf406b10dd1c", "ams1", nil, generatedData} - expected := "An image was created: 'packer-foobar-image' (ID: cc586e45-5156-4f71-b223-cf406b10dd1d) in region 'ams1' based on snapshot 'packer-foobar-snapshot' (ID: cc586e45-5156-4f71-b223-cf406b10dd1c)" + expected := "An image was created: 'packer-foobar-image' (ID: cc586e45-5156-4f71-b223-cf406b10dd1d) in zone 'ams1' based on snapshot 'packer-foobar-snapshot' (ID: cc586e45-5156-4f71-b223-cf406b10dd1c)" if a.String() != expected { t.Fatalf("artifact string should match: %v", expected) diff --git a/builder/scaleway/builder.go b/builder/scaleway/builder.go index 1f25a0509..e25d4cd0e 100644 --- a/builder/scaleway/builder.go +++ b/builder/scaleway/builder.go @@ -13,7 +13,7 @@ import ( "github.com/hashicorp/packer/helper/communicator" "github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/packer" - "github.com/scaleway/scaleway-cli/pkg/api" + "github.com/scaleway/scaleway-sdk-go/scw" ) // The unique id for the builder @@ -32,12 +32,27 @@ func (b *Builder) Prepare(raws ...interface{}) ([]string, []string, error) { return nil, warnings, errs } - return nil, nil, nil + return nil, warnings, nil } func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) { - client, err := api.NewScalewayAPI(b.config.Organization, b.config.Token, b.config.UserAgent, b.config.Region) + scwZone, err := scw.ParseZone(b.config.Zone) + if err != nil { + ui.Error(err.Error()) + return nil, err + } + clientOpts := []scw.ClientOption{ + scw.WithDefaultProjectID(b.config.ProjectID), + scw.WithAuth(b.config.AccessKey, b.config.SecretKey), + scw.WithDefaultZone(scwZone), + } + + if b.config.APIURL != "" { + clientOpts = append(clientOpts, scw.WithAPIURL(b.config.APIURL)) + } + + client, err := scw.NewClient(clientOpts...) if err != nil { ui.Error(err.Error()) return nil, err @@ -50,6 +65,11 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack state.Put("ui", ui) steps := []multistep.Step{ + &stepPreValidate{ + Force: b.config.PackerForce, + ImageName: b.config.ImageName, + SnapshotName: b.config.SnapshotName, + }, &stepCreateSSHKey{ Debug: b.config.PackerDebug, DebugKeyPath: fmt.Sprintf("scw_%s.pem", b.config.PackerBuildName), @@ -96,7 +116,7 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack imageID: state.Get("image_id").(string), snapshotName: state.Get("snapshot_name").(string), snapshotID: state.Get("snapshot_id").(string), - regionName: state.Get("region").(string), + zoneName: b.config.Zone, client: client, StateData: map[string]interface{}{"generated_data": state.Get("generated_data")}, } diff --git a/builder/scaleway/builder_test.go b/builder/scaleway/builder_test.go index be0b2bc7e..e223d6e42 100644 --- a/builder/scaleway/builder_test.go +++ b/builder/scaleway/builder_test.go @@ -9,9 +9,10 @@ import ( func testConfig() map[string]interface{} { return map[string]interface{}{ - "organization_id": "foo", - "api_token": "bar", - "region": "ams1", + "project_id": "00000000-1111-2222-3333-444444444444", + "access_key": "SCWABCXXXXXXXXXXXXXX", + "secret_key": "00000000-1111-2222-3333-444444444444", + "zone": "fr-par-1", "commercial_type": "START1-S", "ssh_username": "root", "image": "image-uuid", @@ -32,10 +33,7 @@ func TestBuilder_Prepare_BadType(t *testing.T) { "api_token": []string{}, } - _, warnings, err := b.Prepare(c) - if len(warnings) > 0 { - t.Fatalf("bad: %#v", warnings) - } + _, _, err := b.Prepare(c) if err == nil { t.Fatalf("prepare should fail") } @@ -68,11 +66,11 @@ func TestBuilderPrepare_InvalidKey(t *testing.T) { } } -func TestBuilderPrepare_Region(t *testing.T) { +func TestBuilderPrepare_Zone(t *testing.T) { var b Builder config := testConfig() - delete(config, "region") + delete(config, "zone") _, warnings, err := b.Prepare(config) if len(warnings) > 0 { t.Fatalf("bad: %#v", warnings) @@ -81,9 +79,9 @@ func TestBuilderPrepare_Region(t *testing.T) { t.Fatalf("should error") } - expected := "ams1" + expected := "fr-par-1" - config["region"] = expected + config["zone"] = expected b = Builder{} _, warnings, err = b.Prepare(config) if len(warnings) > 0 { @@ -93,8 +91,8 @@ func TestBuilderPrepare_Region(t *testing.T) { t.Fatalf("should not have error: %s", err) } - if b.config.Region != expected { - t.Errorf("found %s, expected %s", b.config.Region, expected) + if b.config.Zone != expected { + t.Errorf("found %s, expected %s", b.config.Zone, expected) } } diff --git a/builder/scaleway/config.go b/builder/scaleway/config.go index ae4fc502a..2f744986b 100644 --- a/builder/scaleway/config.go +++ b/builder/scaleway/config.go @@ -17,27 +17,29 @@ import ( "github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/template/interpolate" "github.com/mitchellh/mapstructure" + "github.com/scaleway/scaleway-sdk-go/api/instance/v1" + "github.com/scaleway/scaleway-sdk-go/scw" ) type Config struct { common.PackerConfig `mapstructure:",squash"` Comm communicator.Config `mapstructure:",squash"` - // The token to use to authenticate with your account. - // It can also be specified via environment variable SCALEWAY_API_TOKEN. You - // can see and generate tokens in the "Credentials" - // section of the control panel. - Token string `mapstructure:"api_token" required:"true"` - // The organization id to use to identify your - // organization. It can also be specified via environment variable - // SCALEWAY_ORGANIZATION. Your organization id is available in the - // "Account" section of the - // control panel. - // Previously named: api_access_key with environment variable: SCALEWAY_API_ACCESS_KEY - Organization string `mapstructure:"organization_id" required:"true"` - // The name of the region to launch the server in (par1 - // or ams1). Consequently, this is the region where the snapshot will be - // available. - Region string `mapstructure:"region" required:"true"` + // The AccessKey corresponding to the secret key. + // It can also be specified via the environment variable SCW_ACCESS_KEY. + AccessKey string `mapstructure:"access_key" required:"true"` + // The SecretKey to authenticate against the Scaleway API. + // It can also be specified via the environment variable SCW_SECRET_KEY. + SecretKey string `mapstructure:"secret_key" required:"true"` + // The Project ID in which the instances, volumes and snapshots will be created. + // It can also be specified via the environment variable SCW_DEFAULT_PROJECT_ID. + ProjectID string `mapstructure:"project_id" required:"true"` + // The Zone in which the instances, volumes and snapshots will be created. + // It can also be specified via the environment variable SCW_DEFAULT_ZONE + Zone string `mapstructure:"zone" required:"true"` + // The Scaleway API URL to use + // It can also be specified via the environment variable SCW_API_URL + APIURL string `mapstructure:"api_url"` + // The UUID of the base image to use. This is the image // that will be used to launch a new server and provision it. See // the images list @@ -69,6 +71,28 @@ type Config struct { UserAgent string `mapstructure-to-hcl2:",skip"` ctx interpolate.Context + + // Deprecated configs + + // The token to use to authenticate with your account. + // It can also be specified via environment variable SCALEWAY_API_TOKEN. You + // can see and generate tokens in the "Credentials" + // section of the control panel. + // Deprecated, use SecretKey instead + Token string `mapstructure:"api_token" required:"false"` + // The organization id to use to identify your + // organization. It can also be specified via environment variable + // SCALEWAY_ORGANIZATION. Your organization id is available in the + // "Account" section of the + // control panel. + // Previously named: api_access_key with environment variable: SCALEWAY_API_ACCESS_KEY + // Deprecated, use ProjectID instead + Organization string `mapstructure:"organization_id" required:"false"` + // The name of the region to launch the server in (par1 + // or ams1). Consequently, this is the region where the snapshot will be + // available. + // Deprecated, use Zone instead + Region string `mapstructure:"region" required:"false"` } func (c *Config) Prepare(raws ...interface{}) ([]string, error) { @@ -88,8 +112,11 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { return nil, err } + var warnings []string + c.UserAgent = useragent.String() + // Deprecated variables if c.Organization == "" { if os.Getenv("SCALEWAY_ORGANIZATION") != "" { c.Organization = os.Getenv("SCALEWAY_ORGANIZATION") @@ -98,10 +125,43 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { c.Organization = os.Getenv("SCALEWAY_API_ACCESS_KEY") } } + if c.Organization != "" { + warnings = append(warnings, "organization_id is deprecated in favor of project_id") + c.ProjectID = c.Organization + } if c.Token == "" { c.Token = os.Getenv("SCALEWAY_API_TOKEN") } + if c.Token != "" { + warnings = append(warnings, "token is deprecated in favor of secret_key") + c.SecretKey = c.Token + } + + if c.Region != "" { + warnings = append(warnings, "region is deprecated in favor of zone") + c.Zone = c.Region + } + + if c.AccessKey == "" { + c.AccessKey = os.Getenv(scw.ScwAccessKeyEnv) + } + + if c.SecretKey == "" { + c.SecretKey = os.Getenv(scw.ScwSecretKeyEnv) + } + + if c.ProjectID == "" { + c.ProjectID = os.Getenv(scw.ScwDefaultProjectIDEnv) + } + + if c.Zone == "" { + c.Zone = os.Getenv(scw.ScwDefaultZoneEnv) + } + + if c.APIURL == "" { + c.APIURL = os.Getenv(scw.ScwAPIURLEnv) + } if c.SnapshotName == "" { def, err := interpolate.Render("snapshot-packer-{{timestamp}}", nil) @@ -127,26 +187,31 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { } if c.BootType == "" { - c.BootType = "local" + c.BootType = instance.BootTypeLocal.String() } var errs *packer.MultiError if es := c.Comm.Prepare(&c.ctx); len(es) > 0 { errs = packer.MultiErrorAppend(errs, es...) } - if c.Organization == "" { + if c.ProjectID == "" { errs = packer.MultiErrorAppend( - errs, errors.New("Scaleway Organization ID must be specified")) + errs, errors.New("Scaleway Project ID must be specified")) } - if c.Token == "" { + if c.SecretKey == "" { errs = packer.MultiErrorAppend( - errs, errors.New("Scaleway Token must be specified")) + errs, errors.New("Scaleway Secret Key must be specified")) } - if c.Region == "" { + if c.AccessKey == "" { + warnings = append(warnings, "access_key will be required in future versions") + c.AccessKey = "SCWXXXXXXXXXXXXXXXXX" + } + + if c.Zone == "" { errs = packer.MultiErrorAppend( - errs, errors.New("region is required")) + errs, errors.New("Scaleway Zone is required")) } if c.CommercialType == "" { @@ -160,9 +225,9 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { } if errs != nil && len(errs.Errors) > 0 { - return nil, errs + return warnings, errs } packer.LogSecretFilter.Set(c.Token) - return nil, nil + return warnings, nil } diff --git a/builder/scaleway/config.hcl2spec.go b/builder/scaleway/config.hcl2spec.go index 9c4ed27ed..5de81642f 100644 --- a/builder/scaleway/config.hcl2spec.go +++ b/builder/scaleway/config.hcl2spec.go @@ -63,9 +63,11 @@ type FlatConfig struct { WinRMUseSSL *bool `mapstructure:"winrm_use_ssl" cty:"winrm_use_ssl" hcl:"winrm_use_ssl"` WinRMInsecure *bool `mapstructure:"winrm_insecure" cty:"winrm_insecure" hcl:"winrm_insecure"` WinRMUseNTLM *bool `mapstructure:"winrm_use_ntlm" cty:"winrm_use_ntlm" hcl:"winrm_use_ntlm"` - Token *string `mapstructure:"api_token" required:"true" cty:"api_token" hcl:"api_token"` - Organization *string `mapstructure:"organization_id" required:"true" cty:"organization_id" hcl:"organization_id"` - Region *string `mapstructure:"region" required:"true" cty:"region" hcl:"region"` + AccessKey *string `mapstructure:"access_key" required:"true" cty:"access_key" hcl:"access_key"` + SecretKey *string `mapstructure:"secret_key" required:"true" cty:"secret_key" hcl:"secret_key"` + ProjectID *string `mapstructure:"project_id" required:"true" cty:"project_id" hcl:"project_id"` + Zone *string `mapstructure:"zone" required:"true" cty:"zone" hcl:"zone"` + APIURL *string `mapstructure:"api_url" cty:"api_url" hcl:"api_url"` Image *string `mapstructure:"image" required:"true" cty:"image" hcl:"image"` CommercialType *string `mapstructure:"commercial_type" required:"true" cty:"commercial_type" hcl:"commercial_type"` SnapshotName *string `mapstructure:"snapshot_name" required:"false" cty:"snapshot_name" hcl:"snapshot_name"` @@ -74,6 +76,9 @@ type FlatConfig struct { Bootscript *string `mapstructure:"bootscript" required:"false" cty:"bootscript" hcl:"bootscript"` BootType *string `mapstructure:"boottype" required:"false" cty:"boottype" hcl:"boottype"` RemoveVolume *bool `mapstructure:"remove_volume" cty:"remove_volume" hcl:"remove_volume"` + Token *string `mapstructure:"api_token" required:"false" cty:"api_token" hcl:"api_token"` + Organization *string `mapstructure:"organization_id" required:"false" cty:"organization_id" hcl:"organization_id"` + Region *string `mapstructure:"region" required:"false" cty:"region" hcl:"region"` } // FlatMapstructure returns a new FlatConfig. @@ -142,9 +147,11 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "winrm_use_ssl": &hcldec.AttrSpec{Name: "winrm_use_ssl", Type: cty.Bool, Required: false}, "winrm_insecure": &hcldec.AttrSpec{Name: "winrm_insecure", Type: cty.Bool, Required: false}, "winrm_use_ntlm": &hcldec.AttrSpec{Name: "winrm_use_ntlm", Type: cty.Bool, Required: false}, - "api_token": &hcldec.AttrSpec{Name: "api_token", Type: cty.String, Required: false}, - "organization_id": &hcldec.AttrSpec{Name: "organization_id", Type: cty.String, Required: false}, - "region": &hcldec.AttrSpec{Name: "region", Type: cty.String, Required: false}, + "access_key": &hcldec.AttrSpec{Name: "access_key", Type: cty.String, Required: false}, + "secret_key": &hcldec.AttrSpec{Name: "secret_key", Type: cty.String, Required: false}, + "project_id": &hcldec.AttrSpec{Name: "project_id", Type: cty.String, Required: false}, + "zone": &hcldec.AttrSpec{Name: "zone", Type: cty.String, Required: false}, + "api_url": &hcldec.AttrSpec{Name: "api_url", Type: cty.String, Required: false}, "image": &hcldec.AttrSpec{Name: "image", Type: cty.String, Required: false}, "commercial_type": &hcldec.AttrSpec{Name: "commercial_type", Type: cty.String, Required: false}, "snapshot_name": &hcldec.AttrSpec{Name: "snapshot_name", Type: cty.String, Required: false}, @@ -153,6 +160,9 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "bootscript": &hcldec.AttrSpec{Name: "bootscript", Type: cty.String, Required: false}, "boottype": &hcldec.AttrSpec{Name: "boottype", Type: cty.String, Required: false}, "remove_volume": &hcldec.AttrSpec{Name: "remove_volume", Type: cty.Bool, Required: false}, + "api_token": &hcldec.AttrSpec{Name: "api_token", Type: cty.String, Required: false}, + "organization_id": &hcldec.AttrSpec{Name: "organization_id", Type: cty.String, Required: false}, + "region": &hcldec.AttrSpec{Name: "region", Type: cty.String, Required: false}, } return s } diff --git a/builder/scaleway/step_create_image.go b/builder/scaleway/step_create_image.go index 41f6eee2d..ef8f586a9 100644 --- a/builder/scaleway/step_create_image.go +++ b/builder/scaleway/step_create_image.go @@ -7,13 +7,14 @@ import ( "github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/packer" - "github.com/scaleway/scaleway-cli/pkg/api" + "github.com/scaleway/scaleway-sdk-go/api/instance/v1" + "github.com/scaleway/scaleway-sdk-go/scw" ) type stepImage struct{} func (s *stepImage) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { - client := state.Get("client").(*api.ScalewayAPI) + instanceAPI := instance.NewAPI(state.Get("client").(*scw.Client)) ui := state.Get("ui").(packer.Ui) c := state.Get("config").(*Config) snapshotID := state.Get("snapshot_id").(string) @@ -21,7 +22,9 @@ func (s *stepImage) Run(ctx context.Context, state multistep.StateBag) multistep ui.Say(fmt.Sprintf("Creating image: %v", c.ImageName)) - image, err := client.GetImage(c.Image) + imageResp, err := instanceAPI.GetImage(&instance.GetImageRequest{ + ImageID: c.Image, + }) if err != nil { err := fmt.Errorf("Error getting initial image info: %s", err) state.Put("error", err) @@ -29,11 +32,16 @@ func (s *stepImage) Run(ctx context.Context, state multistep.StateBag) multistep return multistep.ActionHalt } - if image.DefaultBootscript != nil { - bootscriptID = image.DefaultBootscript.Identifier + if imageResp.Image.DefaultBootscript != nil { + bootscriptID = imageResp.Image.DefaultBootscript.ID } - imageID, err := client.PostImage(snapshotID, c.ImageName, bootscriptID, image.Arch) + createImageResp, err := instanceAPI.CreateImage(&instance.CreateImageRequest{ + Arch: imageResp.Image.Arch, + DefaultBootscript: bootscriptID, + Name: c.ImageName, + RootVolume: snapshotID, + }) if err != nil { err := fmt.Errorf("Error creating image: %s", err) state.Put("error", err) @@ -41,10 +49,11 @@ func (s *stepImage) Run(ctx context.Context, state multistep.StateBag) multistep return multistep.ActionHalt } - log.Printf("Image ID: %s", imageID) - state.Put("image_id", imageID) + log.Printf("Image ID: %s", createImageResp.Image.ID) + state.Put("image_id", createImageResp.Image.ID) state.Put("image_name", c.ImageName) - state.Put("region", c.Region) + state.Put("region", c.Zone) // Deprecated + state.Put("zone", c.Zone) return multistep.ActionContinue } diff --git a/builder/scaleway/step_create_server.go b/builder/scaleway/step_create_server.go index 06a72d95a..3342305b1 100644 --- a/builder/scaleway/step_create_server.go +++ b/builder/scaleway/step_create_server.go @@ -7,7 +7,8 @@ import ( "github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/packer" - "github.com/scaleway/scaleway-cli/pkg/api" + "github.com/scaleway/scaleway-sdk-go/api/instance/v1" + "github.com/scaleway/scaleway-sdk-go/scw" ) type stepCreateServer struct { @@ -15,7 +16,7 @@ type stepCreateServer struct { } func (s *stepCreateServer) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { - client := state.Get("client").(*api.ScalewayAPI) + instanceAPI := instance.NewAPI(state.Get("client").(*scw.Client)) ui := state.Get("ui").(packer.Ui) c := state.Get("config").(*Config) tags := []string{} @@ -31,16 +32,16 @@ func (s *stepCreateServer) Run(ctx context.Context, state multistep.StateBag) mu tags = []string{fmt.Sprintf("AUTHORIZED_KEY=%s", strings.Replace(strings.TrimSpace(string(c.Comm.SSHPublicKey)), " ", "_", -1))} } - server, err := client.PostServer(api.ScalewayServerDefinition{ - Name: c.ServerName, - Image: &c.Image, - Organization: c.Organization, - CommercialType: c.CommercialType, - Tags: tags, - Bootscript: bootscript, - BootType: c.BootType, - }) + bootType := instance.BootType(c.BootType) + createServerResp, err := instanceAPI.CreateServer(&instance.CreateServerRequest{ + BootType: &bootType, + Bootscript: bootscript, + CommercialType: c.CommercialType, + Name: c.ServerName, + Image: c.Image, + Tags: tags, + }) if err != nil { err := fmt.Errorf("Error creating server: %s", err) state.Put("error", err) @@ -48,8 +49,10 @@ func (s *stepCreateServer) Run(ctx context.Context, state multistep.StateBag) mu return multistep.ActionHalt } - err = client.PostServerAction(server, "poweron") - + _, err = instanceAPI.ServerAction(&instance.ServerActionRequest{ + Action: instance.ServerActionPoweron, + ServerID: createServerResp.Server.ID, + }) if err != nil { err := fmt.Errorf("Error starting server: %s", err) state.Put("error", err) @@ -57,9 +60,9 @@ func (s *stepCreateServer) Run(ctx context.Context, state multistep.StateBag) mu return multistep.ActionHalt } - s.serverID = server + s.serverID = createServerResp.Server.ID - state.Put("server_id", server) + state.Put("server_id", createServerResp.Server.ID) // instance_id is the generic term used so that users can have access to the // instance id inside of the provisioners, used in step_provision. state.Put("instance_id", s.serverID) @@ -72,16 +75,22 @@ func (s *stepCreateServer) Cleanup(state multistep.StateBag) { return } - client := state.Get("client").(*api.ScalewayAPI) + instanceAPI := instance.NewAPI(state.Get("client").(*scw.Client)) ui := state.Get("ui").(packer.Ui) ui.Say("Destroying server...") - err := client.DeleteServerForce(s.serverID) - + err := instanceAPI.DeleteServer(&instance.DeleteServerRequest{ + ServerID: s.serverID, + }) if err != nil { - ui.Error(fmt.Sprintf( - "Error destroying server. Please destroy it manually: %s", err)) + _, err = instanceAPI.ServerAction(&instance.ServerActionRequest{ + Action: instance.ServerActionTerminate, + ServerID: s.serverID, + }) + if err != nil { + ui.Error(fmt.Sprintf( + "Error destroying server. Please destroy it manually: %s", err)) + } } - } diff --git a/builder/scaleway/step_pre_validate.go b/builder/scaleway/step_pre_validate.go new file mode 100644 index 000000000..0e32b2e5d --- /dev/null +++ b/builder/scaleway/step_pre_validate.go @@ -0,0 +1,80 @@ +package scaleway + +import ( + "context" + "fmt" + + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" + "github.com/scaleway/scaleway-sdk-go/api/instance/v1" + "github.com/scaleway/scaleway-sdk-go/scw" +) + +// StepPreValidate provides an opportunity to pre-validate any configuration for +// the build before actually doing any time consuming work +// +type stepPreValidate struct { + Force bool + ImageName string + SnapshotName string +} + +func (s *stepPreValidate) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { + ui := state.Get("ui").(packer.Ui) + + if s.Force { + ui.Say("Force flag found, skipping prevalidating image name") + return multistep.ActionContinue + } + + ui.Say(fmt.Sprintf("Prevalidating image name: %s", s.ImageName)) + + instanceAPI := instance.NewAPI(state.Get("client").(*scw.Client)) + images, err := instanceAPI.ListImages( + &instance.ListImagesRequest{Name: &s.ImageName}, + scw.WithAllPages()) + if err != nil { + err := fmt.Errorf("Error: getting image list: %s", err) + state.Put("error", err) + ui.Error(err.Error()) + return multistep.ActionHalt + } + + for _, im := range images.Images { + if im.Name == s.ImageName { + err := fmt.Errorf("Error: image name: '%s' is used by existing image with ID %s", + s.ImageName, im.ID) + state.Put("error", err) + ui.Error(err.Error()) + return multistep.ActionHalt + } + } + + ui.Say(fmt.Sprintf("Prevalidating snapshot name: %s", s.SnapshotName)) + + snapshots, err := instanceAPI.ListSnapshots( + &instance.ListSnapshotsRequest{Name: &s.SnapshotName}, + scw.WithAllPages()) + if err != nil { + err := fmt.Errorf("Error: getting snapshot list: %s", err) + state.Put("error", err) + ui.Error(err.Error()) + return multistep.ActionHalt + } + + for _, sn := range snapshots.Snapshots { + if sn.Name == s.SnapshotName { + err := fmt.Errorf("Error: snapshot name: '%s' is used by existing snapshot with ID %s", + s.SnapshotName, sn.ID) + state.Put("error", err) + ui.Error(err.Error()) + return multistep.ActionHalt + } + + } + + return multistep.ActionContinue +} + +func (s *stepPreValidate) Cleanup(multistep.StateBag) { +} diff --git a/builder/scaleway/step_pre_validate_test.go b/builder/scaleway/step_pre_validate_test.go new file mode 100644 index 000000000..51e7d927c --- /dev/null +++ b/builder/scaleway/step_pre_validate_test.go @@ -0,0 +1,154 @@ +package scaleway + +import ( + "bytes" + "context" + "encoding/json" + "math/rand" + "net/http" + "net/http/httptest" + "strconv" + "testing" + + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" + "github.com/scaleway/scaleway-sdk-go/api/instance/v1" + "github.com/scaleway/scaleway-sdk-go/scw" +) + +// 1. Configure a httptest server to return the list of fakeImgNames or fakeSnapNames +// (depending on the endpoint). +// 2. Instantiate a Scaleway API client and wire it to send requests to the httptest +// server. +// 3. Return a state (containing the client) ready to be passed to the step.Run() method. +// 4. Return a teardown function meant to be deferred from the test. +func setup(t *testing.T, fakeImgNames []string, fakeSnapNames []string) (*multistep.BasicStateBag, func()) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + enc := json.NewEncoder(w) + switch r.URL.Path { + case "/instance/v1/zones/fr-par-1/images": + var imgs instance.ListImagesResponse + for _, name := range fakeImgNames { + imgs.Images = append(imgs.Images, &instance.Image{ + ID: strconv.Itoa(rand.Int()), + Name: name, + Zone: "fr-par-1", + }) + } + imgs.TotalCount = uint32(len(fakeImgNames)) + if err := enc.Encode(imgs); err != nil { + t.Fatalf("fake server: encoding reply: %s", err) + } + case "/instance/v1/zones/fr-par-1/snapshots": + var snaps instance.ListSnapshotsResponse + for _, name := range fakeSnapNames { + snaps.Snapshots = append(snaps.Snapshots, &instance.Snapshot{ + ID: strconv.Itoa(rand.Int()), + Name: name, + Zone: "fr-par-1", + }) + } + snaps.TotalCount = uint32(len(fakeSnapNames)) + if err := enc.Encode(snaps); err != nil { + t.Fatalf("fake server: encoding reply: %s", err) + } + default: + t.Fatalf("fake server: unexpected path: %q", r.URL.Path) + } + })) + + clientOpts := []scw.ClientOption{ + scw.WithDefaultZone(scw.ZoneFrPar1), + scw.WithAPIURL(ts.URL), + } + + client, err := scw.NewClient(clientOpts...) + if err != nil { + ts.Close() + t.Fatalf("setup: client: %s", err) + } + + state := multistep.BasicStateBag{} + state.Put("ui", &packer.BasicUi{ + Reader: new(bytes.Buffer), + Writer: new(bytes.Buffer), + }) + state.Put("client", client) + + teardown := func() { + ts.Close() + } + return &state, teardown +} + +func TestStepPreValidate(t *testing.T) { + testCases := []struct { + name string + fakeImgNames []string + fakeSnapNames []string + step stepPreValidate + wantAction multistep.StepAction + }{ + {"happy path: both image name and snapshot name are new", + []string{"image-old"}, + []string{"snapshot-old"}, + stepPreValidate{ + Force: false, + ImageName: "image-new", + SnapshotName: "snapshot-new", + }, + multistep.ActionContinue, + }, + {"want failure: old image name", + []string{"image-old"}, + []string{"snapshot-old"}, + stepPreValidate{ + Force: false, + ImageName: "image-old", + SnapshotName: "snapshot-new", + }, + multistep.ActionHalt, + }, + {"want failure: old snapshot name", + []string{"image-old"}, + []string{"snapshot-old"}, + stepPreValidate{ + Force: false, + ImageName: "image-new", + SnapshotName: "snapshot-old", + }, + multistep.ActionHalt, + }, + {"old image name but force flag", + []string{"image-old"}, + []string{"snapshot-old"}, + stepPreValidate{ + Force: true, + ImageName: "image-old", + SnapshotName: "snapshot-new", + }, + multistep.ActionContinue, + }, + {"old snapshot name but force flag", + []string{"image-old"}, + []string{"snapshot-old"}, + stepPreValidate{ + Force: true, + ImageName: "image-new", + SnapshotName: "snapshot-old", + }, + multistep.ActionContinue, + }, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + state, teardown := setup(t, tc.fakeImgNames, tc.fakeSnapNames) + defer teardown() + + if action := tc.step.Run(context.Background(), state); action != tc.wantAction { + t.Fatalf("step.Run: want: %v; got: %v", tc.wantAction, action) + } + }) + } +} diff --git a/builder/scaleway/step_remove_volume.go b/builder/scaleway/step_remove_volume.go index 9bc6125c1..a9abc2d3b 100644 --- a/builder/scaleway/step_remove_volume.go +++ b/builder/scaleway/step_remove_volume.go @@ -4,10 +4,10 @@ import ( "context" "fmt" - "github.com/scaleway/scaleway-cli/pkg/api" - "github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/packer" + "github.com/scaleway/scaleway-sdk-go/api/instance/v1" + "github.com/scaleway/scaleway-sdk-go/scw" ) type stepRemoveVolume struct{} @@ -24,7 +24,7 @@ func (s *stepRemoveVolume) Cleanup(state multistep.StateBag) { return } - client := state.Get("client").(*api.ScalewayAPI) + instanceAPI := instance.NewAPI(state.Get("client").(*scw.Client)) ui := state.Get("ui").(packer.Ui) c := state.Get("config").(*Config) volumeID := state.Get("root_volume_id").(string) @@ -35,7 +35,9 @@ func (s *stepRemoveVolume) Cleanup(state multistep.StateBag) { ui.Say("Removing Volume ...") - err := client.DeleteVolume(volumeID) + err := instanceAPI.DeleteVolume(&instance.DeleteVolumeRequest{ + VolumeID: volumeID, + }) if err != nil { err := fmt.Errorf("Error removing volume: %s", err) state.Put("error", err) diff --git a/builder/scaleway/step_server_info.go b/builder/scaleway/step_server_info.go index 34b7db1da..7d5f7d1ba 100644 --- a/builder/scaleway/step_server_info.go +++ b/builder/scaleway/step_server_info.go @@ -6,19 +6,22 @@ import ( "github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/packer" - "github.com/scaleway/scaleway-cli/pkg/api" + "github.com/scaleway/scaleway-sdk-go/api/instance/v1" + "github.com/scaleway/scaleway-sdk-go/scw" ) type stepServerInfo struct{} func (s *stepServerInfo) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { - client := state.Get("client").(*api.ScalewayAPI) + instanceAPI := instance.NewAPI(state.Get("client").(*scw.Client)) ui := state.Get("ui").(packer.Ui) serverID := state.Get("server_id").(string) ui.Say("Waiting for server to become active...") - _, err := api.WaitForServerState(client, serverID, "running") + instanceResp, err := instanceAPI.WaitForServer(&instance.WaitForServerRequest{ + ServerID: serverID, + }) if err != nil { err := fmt.Errorf("Error waiting for server to become booted: %s", err) state.Put("error", err) @@ -26,16 +29,22 @@ func (s *stepServerInfo) Run(ctx context.Context, state multistep.StateBag) mult return multistep.ActionHalt } - server, err := client.GetServer(serverID) - if err != nil { - err := fmt.Errorf("Error retrieving server: %s", err) + if instanceResp.State != instance.ServerStateRunning { + err := fmt.Errorf("Server is in state %s", instanceResp.State.String()) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } - state.Put("server_ip", server.PublicAddress.IP) - state.Put("root_volume_id", server.Volumes["0"].Identifier) + if instanceResp.PublicIP == nil { + err := fmt.Errorf("Server does not have a public IP") + state.Put("error", err) + ui.Error(err.Error()) + return multistep.ActionHalt + } + + state.Put("server_ip", instanceResp.PublicIP.Address.String()) + state.Put("root_volume_id", instanceResp.Volumes["0"].ID) return multistep.ActionContinue } diff --git a/builder/scaleway/step_shutdown.go b/builder/scaleway/step_shutdown.go index 69bbf3586..60d76d907 100644 --- a/builder/scaleway/step_shutdown.go +++ b/builder/scaleway/step_shutdown.go @@ -6,20 +6,23 @@ import ( "github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/packer" - "github.com/scaleway/scaleway-cli/pkg/api" + "github.com/scaleway/scaleway-sdk-go/api/instance/v1" + "github.com/scaleway/scaleway-sdk-go/scw" ) type stepShutdown struct{} func (s *stepShutdown) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { - client := state.Get("client").(*api.ScalewayAPI) + instanceAPI := instance.NewAPI(state.Get("client").(*scw.Client)) ui := state.Get("ui").(packer.Ui) serverID := state.Get("server_id").(string) ui.Say("Shutting down server...") - err := client.PostServerAction(serverID, "poweroff") - + _, err := instanceAPI.ServerAction(&instance.ServerActionRequest{ + Action: instance.ServerActionPoweroff, + ServerID: serverID, + }) if err != nil { err := fmt.Errorf("Error stopping server: %s", err) state.Put("error", err) @@ -27,8 +30,9 @@ func (s *stepShutdown) Run(ctx context.Context, state multistep.StateBag) multis return multistep.ActionHalt } - _, err = api.WaitForServerState(client, serverID, "stopped") - + instanceResp, err := instanceAPI.WaitForServer(&instance.WaitForServerRequest{ + ServerID: serverID, + }) if err != nil { err := fmt.Errorf("Error shutting down server: %s", err) state.Put("error", err) @@ -36,6 +40,13 @@ func (s *stepShutdown) Run(ctx context.Context, state multistep.StateBag) multis return multistep.ActionHalt } + if instanceResp.State != instance.ServerStateStopped { + err := fmt.Errorf("Server is in state %s instead of stopped", instanceResp.State.String()) + state.Put("error", err) + ui.Error(err.Error()) + return multistep.ActionHalt + } + return multistep.ActionContinue } diff --git a/builder/scaleway/step_snapshot.go b/builder/scaleway/step_snapshot.go index 705a95806..8b4fab470 100644 --- a/builder/scaleway/step_snapshot.go +++ b/builder/scaleway/step_snapshot.go @@ -7,19 +7,23 @@ import ( "github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/packer" - "github.com/scaleway/scaleway-cli/pkg/api" + "github.com/scaleway/scaleway-sdk-go/api/instance/v1" + "github.com/scaleway/scaleway-sdk-go/scw" ) type stepSnapshot struct{} func (s *stepSnapshot) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { - client := state.Get("client").(*api.ScalewayAPI) + instanceAPI := instance.NewAPI(state.Get("client").(*scw.Client)) ui := state.Get("ui").(packer.Ui) c := state.Get("config").(*Config) volumeID := state.Get("root_volume_id").(string) ui.Say(fmt.Sprintf("Creating snapshot: %v", c.SnapshotName)) - snapshot, err := client.PostSnapshot(volumeID, c.SnapshotName) + createSnapshotResp, err := instanceAPI.CreateSnapshot(&instance.CreateSnapshotRequest{ + Name: c.SnapshotName, + VolumeID: volumeID, + }) if err != nil { err := fmt.Errorf("Error creating snapshot: %s", err) state.Put("error", err) @@ -27,10 +31,11 @@ func (s *stepSnapshot) Run(ctx context.Context, state multistep.StateBag) multis return multistep.ActionHalt } - log.Printf("Snapshot ID: %s", snapshot) - state.Put("snapshot_id", snapshot) + log.Printf("Snapshot ID: %s", createSnapshotResp.Snapshot.ID) + state.Put("snapshot_id", createSnapshotResp.Snapshot.ID) state.Put("snapshot_name", c.SnapshotName) - state.Put("region", c.Region) + state.Put("region", c.Zone) // Deprecated + state.Put("zone", c.Zone) return multistep.ActionContinue } diff --git a/builder/vagrant/builder.hcl2spec.go b/builder/vagrant/builder.hcl2spec.go index 06c1cdd8d..9c3f4e174 100644 --- a/builder/vagrant/builder.hcl2spec.go +++ b/builder/vagrant/builder.hcl2spec.go @@ -20,6 +20,7 @@ type FlatConfig struct { HTTPPortMin *int `mapstructure:"http_port_min" cty:"http_port_min" hcl:"http_port_min"` HTTPPortMax *int `mapstructure:"http_port_max" cty:"http_port_max" hcl:"http_port_max"` HTTPAddress *string `mapstructure:"http_bind_address" cty:"http_bind_address" hcl:"http_bind_address"` + HTTPInterface *string `mapstructure:"http_interface" undocumented:"true" cty:"http_interface" hcl:"http_interface"` ISOChecksum *string `mapstructure:"iso_checksum" required:"true" cty:"iso_checksum" hcl:"iso_checksum"` RawSingleISOUrl *string `mapstructure:"iso_url" required:"true" cty:"iso_url" hcl:"iso_url"` ISOUrls []string `mapstructure:"iso_urls" cty:"iso_urls" hcl:"iso_urls"` @@ -125,6 +126,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "http_port_min": &hcldec.AttrSpec{Name: "http_port_min", Type: cty.Number, Required: false}, "http_port_max": &hcldec.AttrSpec{Name: "http_port_max", Type: cty.Number, Required: false}, "http_bind_address": &hcldec.AttrSpec{Name: "http_bind_address", Type: cty.String, Required: false}, + "http_interface": &hcldec.AttrSpec{Name: "http_interface", Type: cty.String, Required: false}, "iso_checksum": &hcldec.AttrSpec{Name: "iso_checksum", Type: cty.String, Required: false}, "iso_url": &hcldec.AttrSpec{Name: "iso_url", Type: cty.String, Required: false}, "iso_urls": &hcldec.AttrSpec{Name: "iso_urls", Type: cty.List(cty.String), Required: false}, diff --git a/builder/virtualbox/common/guest_additions_config.go b/builder/virtualbox/common/guest_additions_config.go index e0f015dba..5b57c154c 100644 --- a/builder/virtualbox/common/guest_additions_config.go +++ b/builder/virtualbox/common/guest_additions_config.go @@ -4,6 +4,7 @@ package common import ( "fmt" + "strings" "github.com/hashicorp/packer/template/interpolate" ) @@ -19,13 +20,36 @@ const ( type GuestAdditionsConfig struct { Communicator string `mapstructure:"communicator"` // The method by which guest additions are - // made available to the guest for installation. Valid options are upload, - // attach, or disable. If the mode is attach the guest additions ISO will - // be attached as a CD device to the virtual machine. If the mode is upload + // made available to the guest for installation. Valid options are `upload`, + // `attach`, or `disable`. If the mode is `attach` the guest additions ISO will + // be attached as a CD device to the virtual machine. If the mode is `upload` // the guest additions ISO will be uploaded to the path specified by - // guest_additions_path. The default value is upload. If disable is used, + // `guest_additions_path`. The default value is `upload`. If `disable` is used, // guest additions won't be downloaded, either. - GuestAdditionsMode string `mapstructure:"guest_additions_mode" required:"false"` + GuestAdditionsMode string `mapstructure:"guest_additions_mode"` + // The interface type to use to mount guest additions when + // guest_additions_mode is set to attach. Will default to the value set in + // iso_interface, if iso_interface is set. Will default to "ide", if + // iso_interface is not set. Options are "ide" and "sata". + GuestAdditionsInterface string `mapstructure:"guest_additions_interface" required:"false"` + // The path on the guest virtual machine + // where the VirtualBox guest additions ISO will be uploaded. By default this + // is `VBoxGuestAdditions.iso` which should upload into the login directory of + // the user. This is a [configuration + // template](/docs/templates/engine) where the `Version` + // variable is replaced with the VirtualBox version. + GuestAdditionsPath string `mapstructure:"guest_additions_path"` + // The SHA256 checksum of the guest + // additions ISO that will be uploaded to the guest VM. By default the + // checksums will be downloaded from the VirtualBox website, so this only needs + // to be set if you want to be explicit about the checksum. + GuestAdditionsSHA256 string `mapstructure:"guest_additions_sha256"` + // The URL of the guest additions ISO + // to upload. This can also be a file URL if the ISO is at a local path. By + // default, the VirtualBox builder will attempt to find the guest additions ISO + // on the local file system. If it is not available locally, the builder will + // download the proper guest additions ISO from the internet. + GuestAdditionsURL string `mapstructure:"guest_additions_url" required:"false"` } func (c *GuestAdditionsConfig) Prepare(ctx *interpolate.Context) []error { @@ -36,5 +60,36 @@ func (c *GuestAdditionsConfig) Prepare(ctx *interpolate.Context) []error { "'disable' when communicator = 'none'.")) } + if c.GuestAdditionsMode == "" { + c.GuestAdditionsMode = "upload" + } + + if c.GuestAdditionsPath == "" { + c.GuestAdditionsPath = "VBoxGuestAdditions.iso" + } + + if c.GuestAdditionsSHA256 != "" { + c.GuestAdditionsSHA256 = strings.ToLower(c.GuestAdditionsSHA256) + } + + validMode := false + validModes := []string{ + GuestAdditionsModeDisable, + GuestAdditionsModeAttach, + GuestAdditionsModeUpload, + } + + for _, mode := range validModes { + if c.GuestAdditionsMode == mode { + validMode = true + break + } + } + + if !validMode { + errs = append(errs, + fmt.Errorf("guest_additions_mode is invalid. Must be one of: %v", validModes)) + } + return errs } diff --git a/builder/virtualbox/common/step_attach_guest_additions.go b/builder/virtualbox/common/step_attach_guest_additions.go deleted file mode 100644 index 484b074c2..000000000 --- a/builder/virtualbox/common/step_attach_guest_additions.go +++ /dev/null @@ -1,105 +0,0 @@ -package common - -import ( - "context" - "fmt" - "log" - - "github.com/hashicorp/packer/helper/multistep" - "github.com/hashicorp/packer/packer" -) - -// This step attaches the VirtualBox guest additions as a inserted CD onto -// the virtual machine. -// -// Uses: -// config *config -// driver Driver -// guest_additions_path string -// ui packer.Ui -// vmName string -// -// Produces: -type StepAttachGuestAdditions struct { - attachedPath string - GuestAdditionsMode string - GuestAdditionsInterface string -} - -func (s *StepAttachGuestAdditions) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { - driver := state.Get("driver").(Driver) - ui := state.Get("ui").(packer.Ui) - vmName := state.Get("vmName").(string) - - // If we're not attaching the guest additions then just return - if s.GuestAdditionsMode != GuestAdditionsModeAttach { - log.Println("Not attaching guest additions since we're uploading.") - return multistep.ActionContinue - } - - // Get the guest additions path since we're doing it - guestAdditionsPath := state.Get("guest_additions_path").(string) - - // Attach the guest additions to the computer - - controllerName := "IDE Controller" - port := "1" - device := "0" - if s.GuestAdditionsInterface == "sata" { - controllerName = "SATA Controller" - port = "2" - device = "0" - } - - log.Println("Attaching guest additions ISO onto IDE controller...") - command := []string{ - "storageattach", vmName, - "--storagectl", controllerName, - "--port", port, - "--device", device, - "--type", "dvddrive", - "--medium", guestAdditionsPath, - } - if err := driver.VBoxManage(command...); err != nil { - err := fmt.Errorf("Error attaching guest additions: %s", err) - state.Put("error", err) - ui.Error(err.Error()) - return multistep.ActionHalt - } - - // Track the path so that we can unregister it from VirtualBox later - s.attachedPath = guestAdditionsPath - state.Put("guest_additions_attached", true) - - return multistep.ActionContinue -} - -func (s *StepAttachGuestAdditions) Cleanup(state multistep.StateBag) { - if s.attachedPath == "" { - return - } - - driver := state.Get("driver").(Driver) - vmName := state.Get("vmName").(string) - - controllerName := "IDE Controller" - port := "1" - device := "0" - if s.GuestAdditionsInterface == "sata" { - controllerName = "SATA Controller" - port = "2" - device = "0" - } - - command := []string{ - "storageattach", vmName, - "--storagectl", controllerName, - "--port", port, - "--device", device, - "--medium", "none", - } - - // Remove the ISO. Note that this will probably fail since - // stepRemoveDevices does this as well. No big deal. - driver.VBoxManage(command...) -} diff --git a/builder/virtualbox/common/step_attach_isos.go b/builder/virtualbox/common/step_attach_isos.go new file mode 100644 index 000000000..efbe26254 --- /dev/null +++ b/builder/virtualbox/common/step_attach_isos.go @@ -0,0 +1,158 @@ +package common + +import ( + "context" + "fmt" + "log" + "path/filepath" + + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" +) + +// This step attaches the boot ISO, cd_files iso, and guest additions to the +// virtual machine, if present. +type StepAttachISOs struct { + AttachBootISO bool + ISOInterface string + GuestAdditionsMode string + GuestAdditionsInterface string + diskUnmountCommands map[string][]string +} + +func (s *StepAttachISOs) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { + // Check whether there is anything to attach + ui := state.Get("ui").(packer.Ui) + + ui.Say("Mounting ISOs...") + diskMountMap := map[string]string{} + s.diskUnmountCommands = map[string][]string{} + // Track the bootable iso (only used in virtualbox-iso builder. ) + if s.AttachBootISO { + isoPath := state.Get("iso_path").(string) + diskMountMap["boot_iso"] = isoPath + } + + // Determine if we even have a cd_files disk to attach + if cdPathRaw, ok := state.GetOk("cd_path"); ok { + cdFilesPath := cdPathRaw.(string) + diskMountMap["cd_files"] = cdFilesPath + } + + // Determine if we have guest additions to attach + if s.GuestAdditionsMode != GuestAdditionsModeAttach { + log.Println("Not attaching guest additions since we're uploading.") + } else { + // Get the guest additions path since we're doing it + guestAdditionsPath := state.Get("guest_additions_path").(string) + diskMountMap["guest_additions"] = guestAdditionsPath + } + + if len(diskMountMap) == 0 { + ui.Message("No ISOs to mount; continuing...") + return multistep.ActionContinue + } + + driver := state.Get("driver").(Driver) + vmName := state.Get("vmName").(string) + + for diskCategory, isoPath := range diskMountMap { + // If it's a symlink, resolve it to its target. + resolvedIsoPath, err := filepath.EvalSymlinks(isoPath) + if err != nil { + err := fmt.Errorf("Error resolving symlink for ISO: %s", err) + state.Put("error", err) + ui.Error(err.Error()) + return multistep.ActionHalt + } + isoPath = resolvedIsoPath + + // We have three different potential isos we can attach, so let's + // assign each one its own spot so they don't conflict. + var controllerName, device, port string + switch diskCategory { + case "boot_iso": + // figure out controller path + controllerName = "IDE Controller" + port = "0" + device = "1" + if s.ISOInterface == "sata" { + controllerName = "SATA Controller" + port = "1" + device = "0" + } + ui.Message("Mounting boot ISO...") + case "guest_additions": + controllerName = "IDE Controller" + port = "1" + device = "0" + if s.GuestAdditionsInterface == "sata" { + controllerName = "SATA Controller" + port = "2" + device = "0" + } + ui.Message("Mounting guest additions ISO...") + case "cd_files": + controllerName = "IDE Controller" + port = "1" + device = "1" + if s.ISOInterface == "sata" { + controllerName = "SATA Controller" + port = "3" + device = "0" + } + ui.Message("Mounting cd_files ISO...") + } + + // Attach the disk to the controller + command := []string{ + "storageattach", vmName, + "--storagectl", controllerName, + "--port", port, + "--device", device, + "--type", "dvddrive", + "--medium", isoPath, + } + if err := driver.VBoxManage(command...); err != nil { + err := fmt.Errorf("Error attaching ISO: %s", err) + state.Put("error", err) + ui.Error(err.Error()) + return multistep.ActionHalt + } + + // Track the disks we've mounted so we can remove them without having + // to re-derive what was mounted where + unmountCommand := []string{ + "storageattach", vmName, + "--storagectl", controllerName, + "--port", port, + "--device", device, + "--type", "dvddrive", + "--medium", "none", + } + + s.diskUnmountCommands[diskCategory] = unmountCommand + } + + state.Put("disk_unmount_commands", s.diskUnmountCommands) + + return multistep.ActionContinue +} + +func (s *StepAttachISOs) Cleanup(state multistep.StateBag) { + if len(s.diskUnmountCommands) == 0 { + return + } + + driver := state.Get("driver").(Driver) + _, ok := state.GetOk("detached_isos") + + if !ok { + for _, command := range s.diskUnmountCommands { + err := driver.VBoxManage(command...) + if err != nil { + log.Printf("error detaching iso: %s", err) + } + } + } +} diff --git a/builder/virtualbox/common/step_remove_devices.go b/builder/virtualbox/common/step_remove_devices.go index de6b70853..53bc97cca 100644 --- a/builder/virtualbox/common/step_remove_devices.go +++ b/builder/virtualbox/common/step_remove_devices.go @@ -21,8 +21,7 @@ import ( // // Produces: type StepRemoveDevices struct { - Bundling VBoxBundleConfig - GuestAdditionsInterface string + Bundling VBoxBundleConfig } func (s *StepRemoveDevices) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { @@ -73,59 +72,33 @@ func (s *StepRemoveDevices) Run(ctx context.Context, state multistep.StateBag) m } } - if !s.Bundling.BundleISO { - if _, ok := state.GetOk("attachedIso"); ok { - controllerName := "IDE Controller" - port := "0" - device := "1" - if _, ok := state.GetOk("attachedIsoOnSata"); ok { - controllerName = "SATA Controller" - port = "1" - device = "0" - } - - command := []string{ - "storageattach", vmName, - "--storagectl", controllerName, - "--port", port, - "--device", device, - "--medium", "none", - } - - if err := driver.VBoxManage(command...); err != nil { - err := fmt.Errorf("Error detaching ISO: %s", err) - state.Put("error", err) - ui.Error(err.Error()) - return multistep.ActionHalt - } - } + var isoUnmountCommands map[string][]string + isoUnmountCommandsRaw, ok := state.GetOk("disk_unmount_commands") + if !ok { + // No disks to unmount + return multistep.ActionContinue + } else { + isoUnmountCommands = isoUnmountCommandsRaw.(map[string][]string) } - if _, ok := state.GetOk("guest_additions_attached"); ok { - ui.Message("Removing guest additions drive...") - controllerName := "IDE Controller" - port := "1" - device := "0" - if s.GuestAdditionsInterface == "sata" { - controllerName = "SATA Controller" - port = "2" - device = "0" + for diskCategory, unmountCommand := range isoUnmountCommands { + if diskCategory == "boot_iso" && s.Bundling.BundleISO { + // skip the unmount if user wants to bundle the iso + continue } - command := []string{ - "storageattach", vmName, - "--storagectl", controllerName, - "--port", port, - "--device", device, - "--medium", "none", - } - if err := driver.VBoxManage(command...); err != nil { - err := fmt.Errorf("Error removing guest additions: %s", err) + + if err := driver.VBoxManage(unmountCommand...); err != nil { + err := fmt.Errorf("Error detaching ISO: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } } + // log that we removed the isos, so we don't waste time trying to do it + // in the step_attach_isos cleanup. + state.Put("detached_isos", true) + return multistep.ActionContinue } diff --git a/builder/virtualbox/common/step_remove_devices_test.go b/builder/virtualbox/common/step_remove_devices_test.go index 0a548bbd2..d28de98c4 100644 --- a/builder/virtualbox/common/step_remove_devices_test.go +++ b/builder/virtualbox/common/step_remove_devices_test.go @@ -37,7 +37,17 @@ func TestStepRemoveDevices_attachedIso(t *testing.T) { state := testState(t) step := new(StepRemoveDevices) - state.Put("attachedIso", true) + diskUnmountCommands := map[string][]string{ + "boot_iso": []string{ + "storageattach", "myvm", + "--storagectl", "IDE Controller", + "--port", "0", + "--device", "1", + "--type", "dvddrive", + "--medium", "none", + }, + } + state.Put("disk_unmount_commands", diskUnmountCommands) state.Put("vmName", "foo") driver := state.Get("driver").(*DriverMock) @@ -63,8 +73,17 @@ func TestStepRemoveDevices_attachedIsoOnSata(t *testing.T) { state := testState(t) step := new(StepRemoveDevices) - state.Put("attachedIso", true) - state.Put("attachedIsoOnSata", true) + diskUnmountCommands := map[string][]string{ + "boot_iso": []string{ + "storageattach", "myvm", + "--storagectl", "SATA Controller", + "--port", "0", + "--device", "1", + "--type", "dvddrive", + "--medium", "none", + }, + } + state.Put("disk_unmount_commands", diskUnmountCommands) state.Put("vmName", "foo") driver := state.Get("driver").(*DriverMock) diff --git a/builder/virtualbox/iso/builder.go b/builder/virtualbox/iso/builder.go index cc7c74e14..867589036 100644 --- a/builder/virtualbox/iso/builder.go +++ b/builder/virtualbox/iso/builder.go @@ -7,7 +7,6 @@ import ( "context" "errors" "fmt" - "strings" "github.com/hashicorp/hcl/v2/hcldec" vboxcommon "github.com/hashicorp/packer/builder/virtualbox/common" @@ -32,6 +31,7 @@ type Config struct { common.HTTPConfig `mapstructure:",squash"` common.ISOConfig `mapstructure:",squash"` common.FloppyConfig `mapstructure:",squash"` + common.CDConfig `mapstructure:",squash"` bootcommand.BootConfig `mapstructure:",squash"` vboxcommon.ExportConfig `mapstructure:",squash"` vboxcommon.OutputConfig `mapstructure:",squash"` @@ -46,29 +46,6 @@ type Config struct { // The size, in megabytes, of the hard disk to create for the VM. By // default, this is 40000 (about 40 GB). DiskSize uint `mapstructure:"disk_size" required:"false"` - // The path on the guest virtual machine where the VirtualBox guest - // additions ISO will be uploaded. By default this is - // VBoxGuestAdditions.iso which should upload into the login directory of - // the user. This is a configuration template where the `{{ .Version }}` - // variable is replaced with the VirtualBox version. - GuestAdditionsPath string `mapstructure:"guest_additions_path" required:"false"` - // The SHA256 checksum of the guest additions ISO that will be uploaded to - // the guest VM. By default the checksums will be downloaded from the - // VirtualBox website, so this only needs to be set if you want to be - // explicit about the checksum. - GuestAdditionsSHA256 string `mapstructure:"guest_additions_sha256" required:"false"` - // The URL to the guest additions ISO to upload. This can also be a file - // URL if the ISO is at a local path. By default, the VirtualBox builder - // will attempt to find the guest additions ISO on the local file system. - // If it is not available locally, the builder will download the proper - // guest additions ISO from the internet. This is a template engine, and you - // have access to the variable `{{ .Version }}`. - GuestAdditionsURL string `mapstructure:"guest_additions_url" required:"false"` - // The interface type to use to mount guest additions when - // guest_additions_mode is set to attach. Will default to the value set in - // iso_interface, if iso_interface is set. Will default to "ide", if - // iso_interface is not set. Options are "ide" and "sata". - GuestAdditionsInterface string `mapstructure:"guest_additions_interface" required:"false"` // The guest OS type being installed. By default this is other, but you can // get dramatic performance improvements by setting this to the proper // value. To view all available values for this run VBoxManage list @@ -167,6 +144,7 @@ func (b *Builder) Prepare(raws ...interface{}) ([]string, []string, error) { errs = packer.MultiErrorAppend(errs, b.config.ExportConfig.Prepare(&b.config.ctx)...) errs = packer.MultiErrorAppend(errs, b.config.ExportConfig.Prepare(&b.config.ctx)...) errs = packer.MultiErrorAppend(errs, b.config.FloppyConfig.Prepare(&b.config.ctx)...) + errs = packer.MultiErrorAppend(errs, b.config.CDConfig.Prepare(&b.config.ctx)...) errs = packer.MultiErrorAppend( errs, b.config.OutputConfig.Prepare(&b.config.ctx, &b.config.PackerConfig)...) errs = packer.MultiErrorAppend(errs, b.config.HTTPConfig.Prepare(&b.config.ctx)...) @@ -184,14 +162,6 @@ func (b *Builder) Prepare(raws ...interface{}) ([]string, []string, error) { b.config.DiskSize = 40000 } - if b.config.GuestAdditionsMode == "" { - b.config.GuestAdditionsMode = "upload" - } - - if b.config.GuestAdditionsPath == "" { - b.config.GuestAdditionsPath = "VBoxGuestAdditions.iso" - } - if b.config.HardDriveInterface == "" { b.config.HardDriveInterface = "ide" } @@ -244,29 +214,6 @@ func (b *Builder) Prepare(raws ...interface{}) ([]string, []string, error) { errs, errors.New("iso_interface can only be ide or sata")) } - validMode := false - validModes := []string{ - vboxcommon.GuestAdditionsModeDisable, - vboxcommon.GuestAdditionsModeAttach, - vboxcommon.GuestAdditionsModeUpload, - } - - for _, mode := range validModes { - if b.config.GuestAdditionsMode == mode { - validMode = true - break - } - } - - if !validMode { - errs = packer.MultiErrorAppend(errs, - fmt.Errorf("guest_additions_mode is invalid. Must be one of: %v", validModes)) - } - - if b.config.GuestAdditionsSHA256 != "" { - b.config.GuestAdditionsSHA256 = strings.ToLower(b.config.GuestAdditionsSHA256) - } - // Warnings if b.config.ShutdownCommand == "" { warnings = append(warnings, @@ -312,6 +259,10 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack Directories: b.config.FloppyConfig.FloppyDirectories, Label: b.config.FloppyConfig.FloppyLabel, }, + &common.StepCreateCD{ + Files: b.config.CDConfig.CDFiles, + Label: b.config.CDConfig.CDLabel, + }, new(vboxcommon.StepHTTPIPDiscover), &common.StepHTTPServer{ HTTPDir: b.config.HTTPDir, @@ -327,8 +278,9 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack new(vboxcommon.StepSuppressMessages), new(stepCreateVM), new(stepCreateDisk), - new(stepAttachISO), - &vboxcommon.StepAttachGuestAdditions{ + &vboxcommon.StepAttachISOs{ + AttachBootISO: true, + ISOInterface: b.config.ISOInterface, GuestAdditionsMode: b.config.GuestAdditionsMode, GuestAdditionsInterface: b.config.GuestAdditionsInterface, }, @@ -386,8 +338,7 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack ACPIShutdown: b.config.ACPIShutdown, }, &vboxcommon.StepRemoveDevices{ - Bundling: b.config.VBoxBundleConfig, - GuestAdditionsInterface: b.config.GuestAdditionsInterface, + Bundling: b.config.VBoxBundleConfig, }, &vboxcommon.StepVBoxManage{ Commands: b.config.VBoxManagePost, diff --git a/builder/virtualbox/iso/builder.hcl2spec.go b/builder/virtualbox/iso/builder.hcl2spec.go index ecad9a9f1..19cfc0b81 100644 --- a/builder/virtualbox/iso/builder.hcl2spec.go +++ b/builder/virtualbox/iso/builder.hcl2spec.go @@ -20,6 +20,7 @@ type FlatConfig struct { HTTPPortMin *int `mapstructure:"http_port_min" cty:"http_port_min" hcl:"http_port_min"` HTTPPortMax *int `mapstructure:"http_port_max" cty:"http_port_max" hcl:"http_port_max"` HTTPAddress *string `mapstructure:"http_bind_address" cty:"http_bind_address" hcl:"http_bind_address"` + HTTPInterface *string `mapstructure:"http_interface" undocumented:"true" cty:"http_interface" hcl:"http_interface"` ISOChecksum *string `mapstructure:"iso_checksum" required:"true" cty:"iso_checksum" hcl:"iso_checksum"` RawSingleISOUrl *string `mapstructure:"iso_url" required:"true" cty:"iso_url" hcl:"iso_url"` ISOUrls []string `mapstructure:"iso_urls" cty:"iso_urls" hcl:"iso_urls"` @@ -28,6 +29,8 @@ type FlatConfig struct { FloppyFiles []string `mapstructure:"floppy_files" cty:"floppy_files" hcl:"floppy_files"` FloppyDirectories []string `mapstructure:"floppy_dirs" cty:"floppy_dirs" hcl:"floppy_dirs"` FloppyLabel *string `mapstructure:"floppy_label" cty:"floppy_label" hcl:"floppy_label"` + CDFiles []string `mapstructure:"cd_files" cty:"cd_files" hcl:"cd_files"` + CDLabel *string `mapstructure:"cd_label" cty:"cd_label" hcl:"cd_label"` BootGroupInterval *string `mapstructure:"boot_keygroup_interval" cty:"boot_keygroup_interval" hcl:"boot_keygroup_interval"` BootWait *string `mapstructure:"boot_wait" cty:"boot_wait" hcl:"boot_wait"` BootCommand []string `mapstructure:"boot_command" cty:"boot_command" hcl:"boot_command"` @@ -105,12 +108,12 @@ type FlatConfig struct { VBoxManagePost [][]string `mapstructure:"vboxmanage_post" required:"false" cty:"vboxmanage_post" hcl:"vboxmanage_post"` VBoxVersionFile *string `mapstructure:"virtualbox_version_file" required:"false" cty:"virtualbox_version_file" hcl:"virtualbox_version_file"` BundleISO *bool `mapstructure:"bundle_iso" required:"false" cty:"bundle_iso" hcl:"bundle_iso"` - GuestAdditionsMode *string `mapstructure:"guest_additions_mode" required:"false" cty:"guest_additions_mode" hcl:"guest_additions_mode"` - DiskSize *uint `mapstructure:"disk_size" required:"false" cty:"disk_size" hcl:"disk_size"` - GuestAdditionsPath *string `mapstructure:"guest_additions_path" required:"false" cty:"guest_additions_path" hcl:"guest_additions_path"` - GuestAdditionsSHA256 *string `mapstructure:"guest_additions_sha256" required:"false" cty:"guest_additions_sha256" hcl:"guest_additions_sha256"` - GuestAdditionsURL *string `mapstructure:"guest_additions_url" required:"false" cty:"guest_additions_url" hcl:"guest_additions_url"` + GuestAdditionsMode *string `mapstructure:"guest_additions_mode" cty:"guest_additions_mode" hcl:"guest_additions_mode"` GuestAdditionsInterface *string `mapstructure:"guest_additions_interface" required:"false" cty:"guest_additions_interface" hcl:"guest_additions_interface"` + GuestAdditionsPath *string `mapstructure:"guest_additions_path" cty:"guest_additions_path" hcl:"guest_additions_path"` + GuestAdditionsSHA256 *string `mapstructure:"guest_additions_sha256" cty:"guest_additions_sha256" hcl:"guest_additions_sha256"` + GuestAdditionsURL *string `mapstructure:"guest_additions_url" required:"false" cty:"guest_additions_url" hcl:"guest_additions_url"` + DiskSize *uint `mapstructure:"disk_size" required:"false" cty:"disk_size" hcl:"disk_size"` GuestOSType *string `mapstructure:"guest_os_type" required:"false" cty:"guest_os_type" hcl:"guest_os_type"` HardDriveDiscard *bool `mapstructure:"hard_drive_discard" required:"false" cty:"hard_drive_discard" hcl:"hard_drive_discard"` HardDriveInterface *string `mapstructure:"hard_drive_interface" required:"false" cty:"hard_drive_interface" hcl:"hard_drive_interface"` @@ -146,6 +149,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "http_port_min": &hcldec.AttrSpec{Name: "http_port_min", Type: cty.Number, Required: false}, "http_port_max": &hcldec.AttrSpec{Name: "http_port_max", Type: cty.Number, Required: false}, "http_bind_address": &hcldec.AttrSpec{Name: "http_bind_address", Type: cty.String, Required: false}, + "http_interface": &hcldec.AttrSpec{Name: "http_interface", Type: cty.String, Required: false}, "iso_checksum": &hcldec.AttrSpec{Name: "iso_checksum", Type: cty.String, Required: false}, "iso_url": &hcldec.AttrSpec{Name: "iso_url", Type: cty.String, Required: false}, "iso_urls": &hcldec.AttrSpec{Name: "iso_urls", Type: cty.List(cty.String), Required: false}, @@ -154,6 +158,8 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "floppy_files": &hcldec.AttrSpec{Name: "floppy_files", Type: cty.List(cty.String), Required: false}, "floppy_dirs": &hcldec.AttrSpec{Name: "floppy_dirs", Type: cty.List(cty.String), Required: false}, "floppy_label": &hcldec.AttrSpec{Name: "floppy_label", Type: cty.String, Required: false}, + "cd_files": &hcldec.AttrSpec{Name: "cd_files", Type: cty.List(cty.String), Required: false}, + "cd_label": &hcldec.AttrSpec{Name: "cd_label", Type: cty.String, Required: false}, "boot_keygroup_interval": &hcldec.AttrSpec{Name: "boot_keygroup_interval", Type: cty.String, Required: false}, "boot_wait": &hcldec.AttrSpec{Name: "boot_wait", Type: cty.String, Required: false}, "boot_command": &hcldec.AttrSpec{Name: "boot_command", Type: cty.List(cty.String), Required: false}, @@ -232,11 +238,11 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "virtualbox_version_file": &hcldec.AttrSpec{Name: "virtualbox_version_file", Type: cty.String, Required: false}, "bundle_iso": &hcldec.AttrSpec{Name: "bundle_iso", Type: cty.Bool, Required: false}, "guest_additions_mode": &hcldec.AttrSpec{Name: "guest_additions_mode", Type: cty.String, Required: false}, - "disk_size": &hcldec.AttrSpec{Name: "disk_size", Type: cty.Number, Required: false}, + "guest_additions_interface": &hcldec.AttrSpec{Name: "guest_additions_interface", Type: cty.String, Required: false}, "guest_additions_path": &hcldec.AttrSpec{Name: "guest_additions_path", Type: cty.String, Required: false}, "guest_additions_sha256": &hcldec.AttrSpec{Name: "guest_additions_sha256", Type: cty.String, Required: false}, "guest_additions_url": &hcldec.AttrSpec{Name: "guest_additions_url", Type: cty.String, Required: false}, - "guest_additions_interface": &hcldec.AttrSpec{Name: "guest_additions_interface", Type: cty.String, Required: false}, + "disk_size": &hcldec.AttrSpec{Name: "disk_size", Type: cty.Number, Required: false}, "guest_os_type": &hcldec.AttrSpec{Name: "guest_os_type", Type: cty.String, Required: false}, "hard_drive_discard": &hcldec.AttrSpec{Name: "hard_drive_discard", Type: cty.Bool, Required: false}, "hard_drive_interface": &hcldec.AttrSpec{Name: "hard_drive_interface", Type: cty.String, Required: false}, diff --git a/builder/virtualbox/iso/step_attach_iso.go b/builder/virtualbox/iso/step_attach_iso.go deleted file mode 100644 index 0c36f8e92..000000000 --- a/builder/virtualbox/iso/step_attach_iso.go +++ /dev/null @@ -1,105 +0,0 @@ -package iso - -import ( - "context" - "fmt" - "path/filepath" - - vboxcommon "github.com/hashicorp/packer/builder/virtualbox/common" - "github.com/hashicorp/packer/helper/multistep" - "github.com/hashicorp/packer/packer" -) - -// This step attaches the ISO to the virtual machine. -// -// Uses: -// -// Produces: -type stepAttachISO struct { - diskPath string -} - -func (s *stepAttachISO) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { - config := state.Get("config").(*Config) - driver := state.Get("driver").(vboxcommon.Driver) - isoPath := state.Get("iso_path").(string) - ui := state.Get("ui").(packer.Ui) - vmName := state.Get("vmName").(string) - - controllerName := "IDE Controller" - port := "0" - device := "1" - if config.ISOInterface == "sata" { - controllerName = "SATA Controller" - port = "1" - device = "0" - } - - // If it's a symlink, resolve it to it's target. - resolvedIsoPath, err := filepath.EvalSymlinks(isoPath) - if err != nil { - err := fmt.Errorf("Error resolving symlink for ISO: %s", err) - state.Put("error", err) - ui.Error(err.Error()) - return multistep.ActionHalt - } - isoPath = resolvedIsoPath - - // Attach the disk to the controller - command := []string{ - "storageattach", vmName, - "--storagectl", controllerName, - "--port", port, - "--device", device, - "--type", "dvddrive", - "--medium", isoPath, - } - if err := driver.VBoxManage(command...); err != nil { - err := fmt.Errorf("Error attaching ISO: %s", err) - state.Put("error", err) - ui.Error(err.Error()) - return multistep.ActionHalt - } - - // Track the path so that we can unregister it from VirtualBox later - s.diskPath = isoPath - - // Set some state so we know to remove - state.Put("attachedIso", true) - if controllerName == "SATA Controller" { - state.Put("attachedIsoOnSata", true) - } - - return multistep.ActionContinue -} - -func (s *stepAttachISO) Cleanup(state multistep.StateBag) { - if s.diskPath == "" { - return - } - - config := state.Get("config").(*Config) - driver := state.Get("driver").(vboxcommon.Driver) - vmName := state.Get("vmName").(string) - - controllerName := "IDE Controller" - port := "0" - device := "1" - if config.ISOInterface == "sata" { - controllerName = "SATA Controller" - port = "1" - device = "0" - } - - command := []string{ - "storageattach", vmName, - "--storagectl", controllerName, - "--port", port, - "--device", device, - "--medium", "none", - } - - // Remove the ISO. Note that this will probably fail since - // stepRemoveDevices does this as well. No big deal. - driver.VBoxManage(command...) -} diff --git a/builder/virtualbox/ovf/builder.go b/builder/virtualbox/ovf/builder.go index 64485c3bb..14949c1fc 100644 --- a/builder/virtualbox/ovf/builder.go +++ b/builder/virtualbox/ovf/builder.go @@ -60,6 +60,10 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack Directories: b.config.FloppyConfig.FloppyDirectories, Label: b.config.FloppyConfig.FloppyLabel, }, + &common.StepCreateCD{ + Files: b.config.CDConfig.CDFiles, + Label: b.config.CDConfig.CDLabel, + }, new(vboxcommon.StepHTTPIPDiscover), &common.StepHTTPServer{ HTTPDir: b.config.HTTPDir, @@ -91,7 +95,9 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack ImportFlags: b.config.ImportFlags, KeepRegistered: b.config.KeepRegistered, }, - &vboxcommon.StepAttachGuestAdditions{ + &vboxcommon.StepAttachISOs{ + AttachBootISO: false, + ISOInterface: b.config.GuestAdditionsInterface, GuestAdditionsMode: b.config.GuestAdditionsMode, GuestAdditionsInterface: b.config.GuestAdditionsInterface, }, @@ -148,9 +154,7 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack DisableShutdown: b.config.DisableShutdown, ACPIShutdown: b.config.ACPIShutdown, }, - &vboxcommon.StepRemoveDevices{ - GuestAdditionsInterface: b.config.GuestAdditionsInterface, - }, + &vboxcommon.StepRemoveDevices{}, &vboxcommon.StepVBoxManage{ Commands: b.config.VBoxManagePost, Ctx: b.config.ctx, diff --git a/builder/virtualbox/ovf/config.go b/builder/virtualbox/ovf/config.go index df9f69cce..40e47ad56 100644 --- a/builder/virtualbox/ovf/config.go +++ b/builder/virtualbox/ovf/config.go @@ -5,7 +5,6 @@ package ovf import ( "fmt" - "strings" vboxcommon "github.com/hashicorp/packer/builder/virtualbox/common" "github.com/hashicorp/packer/common" @@ -20,6 +19,7 @@ type Config struct { common.PackerConfig `mapstructure:",squash"` common.HTTPConfig `mapstructure:",squash"` common.FloppyConfig `mapstructure:",squash"` + common.CDConfig `mapstructure:",squash"` bootcommand.BootConfig `mapstructure:",squash"` vboxcommon.ExportConfig `mapstructure:",squash"` vboxcommon.OutputConfig `mapstructure:",squash"` @@ -50,38 +50,6 @@ type Config struct { // this is not recommended since these files can be very large and // corruption does happen from time to time. Checksum string `mapstructure:"checksum" required:"true"` - // The method by which guest additions are - // made available to the guest for installation. Valid options are upload, - // attach, or disable. If the mode is attach the guest additions ISO will - // be attached as a CD device to the virtual machine. If the mode is upload - // the guest additions ISO will be uploaded to the path specified by - // guest_additions_path. The default value is upload. If disable is used, - // guest additions won't be downloaded, either. - GuestAdditionsMode string `mapstructure:"guest_additions_mode" required:"false"` - // The path on the guest virtual machine - // where the VirtualBox guest additions ISO will be uploaded. By default this - // is VBoxGuestAdditions.iso which should upload into the login directory of - // the user. This is a configuration - // template where the Version - // variable is replaced with the VirtualBox version. - GuestAdditionsPath string `mapstructure:"guest_additions_path" required:"false"` - // The interface type to use to mount - // guest additions when guest_additions_mode is set to attach. Will - // default to the value set in iso_interface, if iso_interface is set. - // Will default to "ide", if iso_interface is not set. Options are "ide" and - // "sata". - GuestAdditionsInterface string `mapstructure:"guest_additions_interface" required:"false"` - // The SHA256 checksum of the guest - // additions ISO that will be uploaded to the guest VM. By default the - // checksums will be downloaded from the VirtualBox website, so this only needs - // to be set if you want to be explicit about the checksum. - GuestAdditionsSHA256 string `mapstructure:"guest_additions_sha256" required:"false"` - // The URL to the guest additions ISO - // to upload. This can also be a file URL if the ISO is at a local path. By - // default, the VirtualBox builder will attempt to find the guest additions ISO - // on the local file system. If it is not available locally, the builder will - // download the proper guest additions ISO from the internet. - GuestAdditionsURL string `mapstructure:"guest_additions_url" required:"false"` // Additional flags to pass to // VBoxManage import. This can be used to add additional command-line flags // such as --eula-accept to accept a EULA in the OVF. @@ -131,17 +99,6 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { } // Defaults - if c.GuestAdditionsMode == "" { - c.GuestAdditionsMode = "upload" - } - - if c.GuestAdditionsPath == "" { - c.GuestAdditionsPath = "VBoxGuestAdditions.iso" - } - if c.GuestAdditionsInterface == "" { - c.GuestAdditionsInterface = "ide" - } - if c.VMName == "" { c.VMName = fmt.Sprintf( "packer-%s-%d", c.PackerBuildName, interpolate.InitTime.Unix()) @@ -152,6 +109,7 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { errs = packer.MultiErrorAppend(errs, c.ExportConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.ExportConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.FloppyConfig.Prepare(&c.ctx)...) + errs = packer.MultiErrorAppend(errs, c.CDConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.HTTPConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.OutputConfig.Prepare(&c.ctx, &c.PackerConfig)...) errs = packer.MultiErrorAppend(errs, c.RunConfig.Prepare(&c.ctx)...) @@ -166,27 +124,8 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { errs = packer.MultiErrorAppend(errs, fmt.Errorf("source_path is required")) } - validMode := false - validModes := []string{ - vboxcommon.GuestAdditionsModeDisable, - vboxcommon.GuestAdditionsModeAttach, - vboxcommon.GuestAdditionsModeUpload, - } - - for _, mode := range validModes { - if c.GuestAdditionsMode == mode { - validMode = true - break - } - } - - if !validMode { - errs = packer.MultiErrorAppend(errs, - fmt.Errorf("guest_additions_mode is invalid. Must be one of: %v", validModes)) - } - - if c.GuestAdditionsSHA256 != "" { - c.GuestAdditionsSHA256 = strings.ToLower(c.GuestAdditionsSHA256) + if c.GuestAdditionsInterface == "" { + c.GuestAdditionsInterface = "ide" } // Warnings diff --git a/builder/virtualbox/ovf/config.hcl2spec.go b/builder/virtualbox/ovf/config.hcl2spec.go index 6a9f7862d..00e9c45ae 100644 --- a/builder/virtualbox/ovf/config.hcl2spec.go +++ b/builder/virtualbox/ovf/config.hcl2spec.go @@ -20,9 +20,12 @@ type FlatConfig struct { HTTPPortMin *int `mapstructure:"http_port_min" cty:"http_port_min" hcl:"http_port_min"` HTTPPortMax *int `mapstructure:"http_port_max" cty:"http_port_max" hcl:"http_port_max"` HTTPAddress *string `mapstructure:"http_bind_address" cty:"http_bind_address" hcl:"http_bind_address"` + HTTPInterface *string `mapstructure:"http_interface" undocumented:"true" cty:"http_interface" hcl:"http_interface"` FloppyFiles []string `mapstructure:"floppy_files" cty:"floppy_files" hcl:"floppy_files"` FloppyDirectories []string `mapstructure:"floppy_dirs" cty:"floppy_dirs" hcl:"floppy_dirs"` FloppyLabel *string `mapstructure:"floppy_label" cty:"floppy_label" hcl:"floppy_label"` + CDFiles []string `mapstructure:"cd_files" cty:"cd_files" hcl:"cd_files"` + CDLabel *string `mapstructure:"cd_label" cty:"cd_label" hcl:"cd_label"` BootGroupInterval *string `mapstructure:"boot_keygroup_interval" cty:"boot_keygroup_interval" hcl:"boot_keygroup_interval"` BootWait *string `mapstructure:"boot_wait" cty:"boot_wait" hcl:"boot_wait"` BootCommand []string `mapstructure:"boot_command" cty:"boot_command" hcl:"boot_command"` @@ -95,12 +98,12 @@ type FlatConfig struct { VBoxManage [][]string `mapstructure:"vboxmanage" required:"false" cty:"vboxmanage" hcl:"vboxmanage"` VBoxManagePost [][]string `mapstructure:"vboxmanage_post" required:"false" cty:"vboxmanage_post" hcl:"vboxmanage_post"` VBoxVersionFile *string `mapstructure:"virtualbox_version_file" required:"false" cty:"virtualbox_version_file" hcl:"virtualbox_version_file"` - GuestAdditionsMode *string `mapstructure:"guest_additions_mode" required:"false" cty:"guest_additions_mode" hcl:"guest_additions_mode"` - Checksum *string `mapstructure:"checksum" required:"true" cty:"checksum" hcl:"checksum"` - GuestAdditionsPath *string `mapstructure:"guest_additions_path" required:"false" cty:"guest_additions_path" hcl:"guest_additions_path"` + GuestAdditionsMode *string `mapstructure:"guest_additions_mode" cty:"guest_additions_mode" hcl:"guest_additions_mode"` GuestAdditionsInterface *string `mapstructure:"guest_additions_interface" required:"false" cty:"guest_additions_interface" hcl:"guest_additions_interface"` - GuestAdditionsSHA256 *string `mapstructure:"guest_additions_sha256" required:"false" cty:"guest_additions_sha256" hcl:"guest_additions_sha256"` + GuestAdditionsPath *string `mapstructure:"guest_additions_path" cty:"guest_additions_path" hcl:"guest_additions_path"` + GuestAdditionsSHA256 *string `mapstructure:"guest_additions_sha256" cty:"guest_additions_sha256" hcl:"guest_additions_sha256"` GuestAdditionsURL *string `mapstructure:"guest_additions_url" required:"false" cty:"guest_additions_url" hcl:"guest_additions_url"` + Checksum *string `mapstructure:"checksum" required:"true" cty:"checksum" hcl:"checksum"` ImportFlags []string `mapstructure:"import_flags" required:"false" cty:"import_flags" hcl:"import_flags"` ImportOpts *string `mapstructure:"import_opts" required:"false" cty:"import_opts" hcl:"import_opts"` SourcePath *string `mapstructure:"source_path" required:"true" cty:"source_path" hcl:"source_path"` @@ -133,9 +136,12 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "http_port_min": &hcldec.AttrSpec{Name: "http_port_min", Type: cty.Number, Required: false}, "http_port_max": &hcldec.AttrSpec{Name: "http_port_max", Type: cty.Number, Required: false}, "http_bind_address": &hcldec.AttrSpec{Name: "http_bind_address", Type: cty.String, Required: false}, + "http_interface": &hcldec.AttrSpec{Name: "http_interface", Type: cty.String, Required: false}, "floppy_files": &hcldec.AttrSpec{Name: "floppy_files", Type: cty.List(cty.String), Required: false}, "floppy_dirs": &hcldec.AttrSpec{Name: "floppy_dirs", Type: cty.List(cty.String), Required: false}, "floppy_label": &hcldec.AttrSpec{Name: "floppy_label", Type: cty.String, Required: false}, + "cd_files": &hcldec.AttrSpec{Name: "cd_files", Type: cty.List(cty.String), Required: false}, + "cd_label": &hcldec.AttrSpec{Name: "cd_label", Type: cty.String, Required: false}, "boot_keygroup_interval": &hcldec.AttrSpec{Name: "boot_keygroup_interval", Type: cty.String, Required: false}, "boot_wait": &hcldec.AttrSpec{Name: "boot_wait", Type: cty.String, Required: false}, "boot_command": &hcldec.AttrSpec{Name: "boot_command", Type: cty.List(cty.String), Required: false}, @@ -209,11 +215,11 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "vboxmanage_post": &hcldec.AttrSpec{Name: "vboxmanage_post", Type: cty.List(cty.List(cty.String)), Required: false}, "virtualbox_version_file": &hcldec.AttrSpec{Name: "virtualbox_version_file", Type: cty.String, Required: false}, "guest_additions_mode": &hcldec.AttrSpec{Name: "guest_additions_mode", Type: cty.String, Required: false}, - "checksum": &hcldec.AttrSpec{Name: "checksum", Type: cty.String, Required: false}, - "guest_additions_path": &hcldec.AttrSpec{Name: "guest_additions_path", Type: cty.String, Required: false}, "guest_additions_interface": &hcldec.AttrSpec{Name: "guest_additions_interface", Type: cty.String, Required: false}, + "guest_additions_path": &hcldec.AttrSpec{Name: "guest_additions_path", Type: cty.String, Required: false}, "guest_additions_sha256": &hcldec.AttrSpec{Name: "guest_additions_sha256", Type: cty.String, Required: false}, "guest_additions_url": &hcldec.AttrSpec{Name: "guest_additions_url", Type: cty.String, Required: false}, + "checksum": &hcldec.AttrSpec{Name: "checksum", Type: cty.String, Required: false}, "import_flags": &hcldec.AttrSpec{Name: "import_flags", Type: cty.List(cty.String), Required: false}, "import_opts": &hcldec.AttrSpec{Name: "import_opts", Type: cty.String, Required: false}, "source_path": &hcldec.AttrSpec{Name: "source_path", Type: cty.String, Required: false}, diff --git a/builder/virtualbox/vm/builder.go b/builder/virtualbox/vm/builder.go index 4eadfce49..1e7e5f083 100644 --- a/builder/virtualbox/vm/builder.go +++ b/builder/virtualbox/vm/builder.go @@ -54,6 +54,10 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack Files: b.config.FloppyConfig.FloppyFiles, Directories: b.config.FloppyConfig.FloppyDirectories, }, + &common.StepCreateCD{ + Files: b.config.CDConfig.CDFiles, + Label: b.config.CDConfig.CDLabel, + }, &StepSetSnapshot{ Name: b.config.VMName, AttachSnapshot: b.config.AttachSnapshot, @@ -75,8 +79,11 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack &StepImport{ Name: b.config.VMName, }, - &vboxcommon.StepAttachGuestAdditions{ - GuestAdditionsMode: b.config.GuestAdditionsMode, + &vboxcommon.StepAttachISOs{ + AttachBootISO: false, + ISOInterface: b.config.GuestAdditionsInterface, + GuestAdditionsMode: b.config.GuestAdditionsMode, + GuestAdditionsInterface: b.config.GuestAdditionsInterface, }, &vboxcommon.StepConfigureVRDP{ VRDPBindAddress: b.config.VRDPBindAddress, @@ -131,6 +138,7 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack DisableShutdown: b.config.DisableShutdown, ACPIShutdown: b.config.ACPIShutdown, }, + &vboxcommon.StepRemoveDevices{}, &vboxcommon.StepVBoxManage{ Commands: b.config.VBoxManagePost, Ctx: b.config.ctx, diff --git a/builder/virtualbox/vm/config.go b/builder/virtualbox/vm/config.go index 41ef57d20..973be08ed 100644 --- a/builder/virtualbox/vm/config.go +++ b/builder/virtualbox/vm/config.go @@ -6,7 +6,6 @@ package vm import ( "fmt" "log" - "strings" "time" vboxcommon "github.com/hashicorp/packer/builder/virtualbox/common" @@ -19,44 +18,19 @@ import ( // Config is the configuration structure for the builder. type Config struct { - common.PackerConfig `mapstructure:",squash"` - common.HTTPConfig `mapstructure:",squash"` - common.FloppyConfig `mapstructure:",squash"` - bootcommand.BootConfig `mapstructure:",squash"` - vboxcommon.ExportConfig `mapstructure:",squash"` - vboxcommon.OutputConfig `mapstructure:",squash"` - vboxcommon.RunConfig `mapstructure:",squash"` - vboxcommon.CommConfig `mapstructure:",squash"` - vboxcommon.ShutdownConfig `mapstructure:",squash"` - vboxcommon.VBoxManageConfig `mapstructure:",squash"` - vboxcommon.VBoxVersionConfig `mapstructure:",squash"` - - // The method by which guest additions are - // made available to the guest for installation. Valid options are `upload`, - // `attach`, or `disable`. If the mode is `attach` the guest additions ISO will - // be attached as a CD device to the virtual machine. If the mode is `upload` - // the guest additions ISO will be uploaded to the path specified by - // `guest_additions_path`. The default value is `upload`. If `disable` is used, - // guest additions won't be downloaded, either. - GuestAdditionsMode string `mapstructure:"guest_additions_mode"` - // The path on the guest virtual machine - // where the VirtualBox guest additions ISO will be uploaded. By default this - // is `VBoxGuestAdditions.iso` which should upload into the login directory of - // the user. This is a [configuration - // template](/docs/templates/engine) where the `Version` - // variable is replaced with the VirtualBox version. - GuestAdditionsPath string `mapstructure:"guest_additions_path"` - // The SHA256 checksum of the guest - // additions ISO that will be uploaded to the guest VM. By default the - // checksums will be downloaded from the VirtualBox website, so this only needs - // to be set if you want to be explicit about the checksum. - GuestAdditionsSHA256 string `mapstructure:"guest_additions_sha256"` - // The URL to the guest additions ISO - // to upload. This can also be a file URL if the ISO is at a local path. By - // default, the VirtualBox builder will attempt to find the guest additions ISO - // on the local file system. If it is not available locally, the builder will - // download the proper guest additions ISO from the internet. - GuestAdditionsURL string `mapstructure:"guest_additions_url" required:"false"` + common.PackerConfig `mapstructure:",squash"` + common.HTTPConfig `mapstructure:",squash"` + common.FloppyConfig `mapstructure:",squash"` + common.CDConfig `mapstructure:",squash"` + bootcommand.BootConfig `mapstructure:",squash"` + vboxcommon.ExportConfig `mapstructure:",squash"` + vboxcommon.OutputConfig `mapstructure:",squash"` + vboxcommon.RunConfig `mapstructure:",squash"` + vboxcommon.CommConfig `mapstructure:",squash"` + vboxcommon.ShutdownConfig `mapstructure:",squash"` + vboxcommon.VBoxManageConfig `mapstructure:",squash"` + vboxcommon.VBoxVersionConfig `mapstructure:",squash"` + vboxcommon.GuestAdditionsConfig `mapstructure:",squash"` // This is the name of the virtual machine to which the // builder shall attach. VMName string `mapstructure:"vm_name" required:"true"` @@ -109,14 +83,6 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { } // Defaults - if c.GuestAdditionsMode == "" { - c.GuestAdditionsMode = "upload" - } - - if c.GuestAdditionsPath == "" { - c.GuestAdditionsPath = "VBoxGuestAdditions.iso" - } - if c.PostShutdownDelay == 0 { c.PostShutdownDelay = 2 * time.Second } @@ -125,6 +91,7 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { var errs *packer.MultiError errs = packer.MultiErrorAppend(errs, c.ExportConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.FloppyConfig.Prepare(&c.ctx)...) + errs = packer.MultiErrorAppend(errs, c.CDConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.HTTPConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.OutputConfig.Prepare(&c.ctx, &c.PackerConfig)...) errs = packer.MultiErrorAppend(errs, c.RunConfig.Prepare(&c.ctx)...) @@ -133,6 +100,11 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { errs = packer.MultiErrorAppend(errs, c.VBoxManageConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.VBoxVersionConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.BootConfig.Prepare(&c.ctx)...) + errs = packer.MultiErrorAppend(errs, c.GuestAdditionsConfig.Prepare(&c.ctx)...) + + if c.GuestAdditionsInterface == "" { + c.GuestAdditionsInterface = "ide" + } log.Printf("PostShutdownDelay: %s", c.PostShutdownDelay) @@ -141,29 +113,6 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { fmt.Errorf("vm_name is required")) } - validMode := false - validModes := []string{ - vboxcommon.GuestAdditionsModeDisable, - vboxcommon.GuestAdditionsModeAttach, - vboxcommon.GuestAdditionsModeUpload, - } - - for _, mode := range validModes { - if c.GuestAdditionsMode == mode { - validMode = true - break - } - } - - if !validMode { - errs = packer.MultiErrorAppend(errs, - fmt.Errorf("guest_additions_mode is invalid. Must be one of: %v", validModes)) - } - - if c.GuestAdditionsSHA256 != "" { - c.GuestAdditionsSHA256 = strings.ToLower(c.GuestAdditionsSHA256) - } - // Warnings var warnings []string if c.TargetSnapshot == "" && c.SkipExport { diff --git a/builder/virtualbox/vm/config.hcl2spec.go b/builder/virtualbox/vm/config.hcl2spec.go index 9153b92b6..de84615ce 100644 --- a/builder/virtualbox/vm/config.hcl2spec.go +++ b/builder/virtualbox/vm/config.hcl2spec.go @@ -20,9 +20,12 @@ type FlatConfig struct { HTTPPortMin *int `mapstructure:"http_port_min" cty:"http_port_min" hcl:"http_port_min"` HTTPPortMax *int `mapstructure:"http_port_max" cty:"http_port_max" hcl:"http_port_max"` HTTPAddress *string `mapstructure:"http_bind_address" cty:"http_bind_address" hcl:"http_bind_address"` + HTTPInterface *string `mapstructure:"http_interface" undocumented:"true" cty:"http_interface" hcl:"http_interface"` FloppyFiles []string `mapstructure:"floppy_files" cty:"floppy_files" hcl:"floppy_files"` FloppyDirectories []string `mapstructure:"floppy_dirs" cty:"floppy_dirs" hcl:"floppy_dirs"` FloppyLabel *string `mapstructure:"floppy_label" cty:"floppy_label" hcl:"floppy_label"` + CDFiles []string `mapstructure:"cd_files" cty:"cd_files" hcl:"cd_files"` + CDLabel *string `mapstructure:"cd_label" cty:"cd_label" hcl:"cd_label"` BootGroupInterval *string `mapstructure:"boot_keygroup_interval" cty:"boot_keygroup_interval" hcl:"boot_keygroup_interval"` BootWait *string `mapstructure:"boot_wait" cty:"boot_wait" hcl:"boot_wait"` BootCommand []string `mapstructure:"boot_command" cty:"boot_command" hcl:"boot_command"` @@ -96,6 +99,7 @@ type FlatConfig struct { VBoxManagePost [][]string `mapstructure:"vboxmanage_post" required:"false" cty:"vboxmanage_post" hcl:"vboxmanage_post"` VBoxVersionFile *string `mapstructure:"virtualbox_version_file" required:"false" cty:"virtualbox_version_file" hcl:"virtualbox_version_file"` GuestAdditionsMode *string `mapstructure:"guest_additions_mode" cty:"guest_additions_mode" hcl:"guest_additions_mode"` + GuestAdditionsInterface *string `mapstructure:"guest_additions_interface" required:"false" cty:"guest_additions_interface" hcl:"guest_additions_interface"` GuestAdditionsPath *string `mapstructure:"guest_additions_path" cty:"guest_additions_path" hcl:"guest_additions_path"` GuestAdditionsSHA256 *string `mapstructure:"guest_additions_sha256" cty:"guest_additions_sha256" hcl:"guest_additions_sha256"` GuestAdditionsURL *string `mapstructure:"guest_additions_url" required:"false" cty:"guest_additions_url" hcl:"guest_additions_url"` @@ -130,9 +134,12 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "http_port_min": &hcldec.AttrSpec{Name: "http_port_min", Type: cty.Number, Required: false}, "http_port_max": &hcldec.AttrSpec{Name: "http_port_max", Type: cty.Number, Required: false}, "http_bind_address": &hcldec.AttrSpec{Name: "http_bind_address", Type: cty.String, Required: false}, + "http_interface": &hcldec.AttrSpec{Name: "http_interface", Type: cty.String, Required: false}, "floppy_files": &hcldec.AttrSpec{Name: "floppy_files", Type: cty.List(cty.String), Required: false}, "floppy_dirs": &hcldec.AttrSpec{Name: "floppy_dirs", Type: cty.List(cty.String), Required: false}, "floppy_label": &hcldec.AttrSpec{Name: "floppy_label", Type: cty.String, Required: false}, + "cd_files": &hcldec.AttrSpec{Name: "cd_files", Type: cty.List(cty.String), Required: false}, + "cd_label": &hcldec.AttrSpec{Name: "cd_label", Type: cty.String, Required: false}, "boot_keygroup_interval": &hcldec.AttrSpec{Name: "boot_keygroup_interval", Type: cty.String, Required: false}, "boot_wait": &hcldec.AttrSpec{Name: "boot_wait", Type: cty.String, Required: false}, "boot_command": &hcldec.AttrSpec{Name: "boot_command", Type: cty.List(cty.String), Required: false}, @@ -206,6 +213,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "vboxmanage_post": &hcldec.AttrSpec{Name: "vboxmanage_post", Type: cty.List(cty.List(cty.String)), Required: false}, "virtualbox_version_file": &hcldec.AttrSpec{Name: "virtualbox_version_file", Type: cty.String, Required: false}, "guest_additions_mode": &hcldec.AttrSpec{Name: "guest_additions_mode", Type: cty.String, Required: false}, + "guest_additions_interface": &hcldec.AttrSpec{Name: "guest_additions_interface", Type: cty.String, Required: false}, "guest_additions_path": &hcldec.AttrSpec{Name: "guest_additions_path", Type: cty.String, Required: false}, "guest_additions_sha256": &hcldec.AttrSpec{Name: "guest_additions_sha256", Type: cty.String, Required: false}, "guest_additions_url": &hcldec.AttrSpec{Name: "guest_additions_url", Type: cty.String, Required: false}, diff --git a/builder/vmware/common/driver.go b/builder/vmware/common/driver.go index 167d3bce6..9ff431320 100644 --- a/builder/vmware/common/driver.go +++ b/builder/vmware/common/driver.go @@ -91,56 +91,27 @@ func NewDriver(dconfig *DriverConfig, config *SSHConfig, vmName string) (Driver, drivers := []Driver{} if dconfig.RemoteType != "" { - drivers = []Driver{ - &ESX5Driver{ - Host: dconfig.RemoteHost, - Port: dconfig.RemotePort, - Username: dconfig.RemoteUser, - Password: dconfig.RemotePassword, - PrivateKeyFile: dconfig.RemotePrivateKey, - Datastore: dconfig.RemoteDatastore, - CacheDatastore: dconfig.RemoteCacheDatastore, - CacheDirectory: dconfig.RemoteCacheDirectory, - VMName: vmName, - CommConfig: config.Comm, - }, + esx5Driver, err := NewESX5Driver(dconfig, config, vmName) + if err != nil { + return nil, err } + drivers = []Driver{esx5Driver} } else { switch runtime.GOOS { case "darwin": drivers = []Driver{ - &Fusion6Driver{ - Fusion5Driver: Fusion5Driver{ - AppPath: dconfig.FusionAppPath, - SSHConfig: config, - }, - }, - &Fusion5Driver{ - AppPath: dconfig.FusionAppPath, - SSHConfig: config, - }, + NewFusion6Driver(dconfig, config), + NewFusion5Driver(dconfig, config), } case "linux": fallthrough case "windows": drivers = []Driver{ - &Workstation10Driver{ - Workstation9Driver: Workstation9Driver{ - SSHConfig: config, - }, - }, - &Workstation9Driver{ - SSHConfig: config, - }, - &Player6Driver{ - Player5Driver: Player5Driver{ - SSHConfig: config, - }, - }, - &Player5Driver{ - SSHConfig: config, - }, + NewWorkstation10Driver(config), + NewWorkstation9Driver(config), + NewPlayer6Driver(config), + NewPlayer5Driver(config), } default: return nil, fmt.Errorf("can't find driver for OS: %s", runtime.GOOS) diff --git a/builder/vmware/common/driver_config.go b/builder/vmware/common/driver_config.go index c87ab3c6c..8e45ff293 100644 --- a/builder/vmware/common/driver_config.go +++ b/builder/vmware/common/driver_config.go @@ -52,6 +52,8 @@ type DriverConfig struct { } func (c *DriverConfig) Prepare(ctx *interpolate.Context) []error { + var errs []error + if c.FusionAppPath == "" { c.FusionAppPath = os.Getenv("FUSION_APP_PATH") } @@ -74,7 +76,19 @@ func (c *DriverConfig) Prepare(ctx *interpolate.Context) []error { c.RemotePort = 22 } - return nil + if c.RemoteType != "" { + if c.RemoteHost == "" { + errs = append(errs, + fmt.Errorf("remote_host must be specified")) + } + + if c.RemoteType != "esx5" { + errs = append(errs, + fmt.Errorf("Only 'esx5' value is accepted for remote_type")) + } + } + + return errs } func (c *DriverConfig) Validate(SkipExport bool) error { diff --git a/builder/vmware/common/driver_config_test.go b/builder/vmware/common/driver_config_test.go index 1f3774685..ccb7d545e 100644 --- a/builder/vmware/common/driver_config_test.go +++ b/builder/vmware/common/driver_config_test.go @@ -1,32 +1,84 @@ package common import ( + "fmt" + "reflect" "testing" + "github.com/google/go-cmp/cmp" "github.com/hashicorp/packer/template/interpolate" ) func TestDriverConfigPrepare(t *testing.T) { - var c *DriverConfig - - // Test a default boot_wait - c = new(DriverConfig) - errs := c.Prepare(interpolate.NewContext()) - if len(errs) > 0 { - t.Fatalf("bad: %#v", errs) - } - if c.FusionAppPath != "/Applications/VMware Fusion.app" { - t.Fatalf("bad value: %s", c.FusionAppPath) + tc := []struct { + name string + config *DriverConfig + expectedConfig *DriverConfig + errs []error + }{ + { + name: "Set default values", + config: new(DriverConfig), + expectedConfig: &DriverConfig{ + FusionAppPath: "/Applications/VMware Fusion.app", + RemoteDatastore: "datastore1", + RemoteCacheDatastore: "datastore1", + RemoteCacheDirectory: "packer_cache", + RemotePort: 22, + RemoteUser: "root", + }, + errs: nil, + }, + { + name: "Override default values", + config: &DriverConfig{ + FusionAppPath: "foo", + RemoteDatastore: "set-datastore1", + RemoteCacheDatastore: "set-datastore1", + RemoteCacheDirectory: "set_packer_cache", + RemotePort: 443, + RemoteUser: "admin", + }, + expectedConfig: &DriverConfig{ + FusionAppPath: "foo", + RemoteDatastore: "set-datastore1", + RemoteCacheDatastore: "set-datastore1", + RemoteCacheDirectory: "set_packer_cache", + RemotePort: 443, + RemoteUser: "admin", + }, + errs: nil, + }, + { + name: "Invalid remote type", + config: &DriverConfig{ + RemoteType: "invalid", + RemoteHost: "host", + }, + expectedConfig: nil, + errs: []error{fmt.Errorf("Only 'esx5' value is accepted for remote_type")}, + }, + { + name: "Remote host not set", + config: &DriverConfig{ + RemoteType: "esx5", + }, + expectedConfig: nil, + errs: []error{fmt.Errorf("remote_host must be specified")}, + }, } - // Test with a good one - c = new(DriverConfig) - c.FusionAppPath = "foo" - errs = c.Prepare(interpolate.NewContext()) - if len(errs) > 0 { - t.Fatalf("bad: %#v", errs) - } - if c.FusionAppPath != "foo" { - t.Fatalf("bad value: %s", c.FusionAppPath) + for _, c := range tc { + t.Run(c.name, func(t *testing.T) { + errs := c.config.Prepare(interpolate.NewContext()) + if !reflect.DeepEqual(errs, c.errs) { + t.Fatalf("bad: \n expected '%v' \nactual '%v'", c.errs, errs) + } + if len(c.errs) == 0 { + if diff := cmp.Diff(c.config, c.expectedConfig); diff != "" { + t.Fatalf("bad value: %s", diff) + } + } + }) } } diff --git a/builder/vmware/common/driver_esx5.go b/builder/vmware/common/driver_esx5.go index dbece3ff9..bdfa86e70 100644 --- a/builder/vmware/common/driver_esx5.go +++ b/builder/vmware/common/driver_esx5.go @@ -20,6 +20,13 @@ import ( "strings" "time" + "github.com/vmware/govmomi" + "github.com/vmware/govmomi/find" + "github.com/vmware/govmomi/session" + "github.com/vmware/govmomi/vim25" + "github.com/vmware/govmomi/vim25/soap" + "github.com/vmware/govmomi/vim25/types" + "github.com/hashicorp/go-getter/v2" "github.com/hashicorp/packer/communicator/ssh" "github.com/hashicorp/packer/helper/communicator" @@ -45,11 +52,66 @@ type ESX5Driver struct { VMName string CommConfig communicator.Config + ctx context.Context + client *govmomi.Client + finder *find.Finder + comm packer.Communicator outputDir string vmId string } +func NewESX5Driver(dconfig *DriverConfig, config *SSHConfig, vmName string) (Driver, error) { + ctx := context.TODO() + + vsphereUrl, err := url.Parse(fmt.Sprintf("https://%v/sdk", dconfig.RemoteHost)) + if err != nil { + return nil, err + } + credentials := url.UserPassword(dconfig.RemoteUser, dconfig.RemotePassword) + vsphereUrl.User = credentials + + soapClient := soap.NewClient(vsphereUrl, true) + vimClient, err := vim25.NewClient(ctx, soapClient) + if err != nil { + return nil, err + } + + vimClient.RoundTripper = session.KeepAlive(vimClient.RoundTripper, 10*time.Minute) + client := &govmomi.Client{ + Client: vimClient, + SessionManager: session.NewManager(vimClient), + } + + err = client.SessionManager.Login(ctx, credentials) + if err != nil { + return nil, err + } + + finder := find.NewFinder(client.Client, false) + datacenter, err := finder.DefaultDatacenter(ctx) + if err != nil { + return nil, err + } + finder.SetDatacenter(datacenter) + + return &ESX5Driver{ + Host: dconfig.RemoteHost, + Port: dconfig.RemotePort, + Username: dconfig.RemoteUser, + Password: dconfig.RemotePassword, + PrivateKeyFile: dconfig.RemotePrivateKey, + Datastore: dconfig.RemoteDatastore, + CacheDatastore: dconfig.RemoteCacheDatastore, + CacheDirectory: dconfig.RemoteCacheDirectory, + VMName: vmName, + CommConfig: config.Comm, + ctx: ctx, + client: client, + finder: finder, + }, nil +} + func (d *ESX5Driver) Clone(dst, src string, linked bool) error { linesToArray := func(lines string) []string { return strings.Split(strings.Trim(lines, "\r\n"), "\n") } @@ -887,3 +949,11 @@ func (r *esxcliReader) find(key, val string) (map[string]string, error) { } } } + +func (d *ESX5Driver) AcquireVNCOverWebsocketTicket() (*types.VirtualMachineTicket, error) { + vm, err := d.finder.VirtualMachine(d.ctx, d.VMName) + if err != nil { + return nil, err + } + return vm.AcquireTicket(d.ctx, string(types.VirtualMachineTicketTypeWebmks)) +} diff --git a/builder/vmware/common/driver_fusion5.go b/builder/vmware/common/driver_fusion5.go index 2599604b9..02fdf8cf9 100644 --- a/builder/vmware/common/driver_fusion5.go +++ b/builder/vmware/common/driver_fusion5.go @@ -24,6 +24,13 @@ type Fusion5Driver struct { SSHConfig *SSHConfig } +func NewFusion5Driver(dconfig *DriverConfig, config *SSHConfig) Driver { + return &Fusion5Driver{ + AppPath: dconfig.FusionAppPath, + SSHConfig: config, + } +} + func (d *Fusion5Driver) Clone(dst, src string, linked bool) error { return errors.New("Cloning is not supported with Fusion 5. Please use Fusion 6+.") } diff --git a/builder/vmware/common/driver_fusion6.go b/builder/vmware/common/driver_fusion6.go index 1bc26bdb7..27dc578a1 100644 --- a/builder/vmware/common/driver_fusion6.go +++ b/builder/vmware/common/driver_fusion6.go @@ -18,6 +18,15 @@ type Fusion6Driver struct { Fusion5Driver } +func NewFusion6Driver(dconfig *DriverConfig, config *SSHConfig) Driver { + return &Fusion6Driver{ + Fusion5Driver: Fusion5Driver{ + AppPath: dconfig.FusionAppPath, + SSHConfig: config, + }, + } +} + func (d *Fusion6Driver) Clone(dst, src string, linked bool) error { var cloneType string diff --git a/builder/vmware/common/driver_player5.go b/builder/vmware/common/driver_player5.go index ccb1de2c2..a8616c089 100644 --- a/builder/vmware/common/driver_player5.go +++ b/builder/vmware/common/driver_player5.go @@ -25,6 +25,12 @@ type Player5Driver struct { SSHConfig *SSHConfig } +func NewPlayer5Driver(config *SSHConfig) Driver { + return &Player5Driver{ + SSHConfig: config, + } +} + func (d *Player5Driver) Clone(dst, src string, linked bool) error { return errors.New("Cloning is not supported with VMWare Player version 5. Please use VMWare Player version 6, or greater.") } diff --git a/builder/vmware/common/driver_player6.go b/builder/vmware/common/driver_player6.go index d121f02bc..76039a651 100644 --- a/builder/vmware/common/driver_player6.go +++ b/builder/vmware/common/driver_player6.go @@ -13,6 +13,14 @@ type Player6Driver struct { Player5Driver } +func NewPlayer6Driver(config *SSHConfig) Driver { + return &Player6Driver{ + Player5Driver: Player5Driver{ + SSHConfig: config, + }, + } +} + func (d *Player6Driver) Clone(dst, src string, linked bool) error { // TODO(rasa) check if running player+, not just player diff --git a/builder/vmware/common/driver_workstation10.go b/builder/vmware/common/driver_workstation10.go index 070df50c2..b1e4c8a5c 100644 --- a/builder/vmware/common/driver_workstation10.go +++ b/builder/vmware/common/driver_workstation10.go @@ -13,6 +13,14 @@ type Workstation10Driver struct { Workstation9Driver } +func NewWorkstation10Driver(config *SSHConfig) Driver { + return &Workstation10Driver{ + Workstation9Driver: Workstation9Driver{ + SSHConfig: config, + }, + } +} + func (d *Workstation10Driver) Clone(dst, src string, linked bool) error { var cloneType string diff --git a/builder/vmware/common/driver_workstation9.go b/builder/vmware/common/driver_workstation9.go index 50bf77f34..c11733460 100644 --- a/builder/vmware/common/driver_workstation9.go +++ b/builder/vmware/common/driver_workstation9.go @@ -24,6 +24,12 @@ type Workstation9Driver struct { SSHConfig *SSHConfig } +func NewWorkstation9Driver(config *SSHConfig) Driver { + return &Workstation9Driver{ + SSHConfig: config, + } +} + func (d *Workstation9Driver) Clone(dst, src string, linked bool) error { return errors.New("Cloning is not supported with VMware WS version 9. Please use VMware WS version 10, or greater.") } diff --git a/builder/vmware/common/run_config.go b/builder/vmware/common/run_config.go index a649ae4c8..06af92bca 100644 --- a/builder/vmware/common/run_config.go +++ b/builder/vmware/common/run_config.go @@ -8,6 +8,7 @@ import ( "github.com/hashicorp/packer/template/interpolate" ) +// ~> **Note:** If [vnc_over_websocket](#vnc_over_websocket) is set to true, any other VNC configuration will be ignored. type RunConfig struct { // Packer defaults to building VMware virtual machines // by launching a GUI that shows the console of the machine being built. When @@ -37,9 +38,28 @@ type RunConfig struct { // true if building on ESXi 6.5 and 6.7 with VNC enabled. Defaults to // false. VNCDisablePassword bool `mapstructure:"vnc_disable_password" required:"false"` + // When set to true, Packer will connect to the remote VNC server over a websocket connection + // and any other VNC configuration option will be ignored. + // Remote builds using ESXi 6.7+ allows to connect to the VNC server only over websocket, + // for these the `vnc_over_websocket` must be set to true. + VNCOverWebsocket bool `mapstructure:"vnc_over_websocket" required:"false"` + // Do not validate VNC over websocket server's TLS certificate. Defaults to `false`. + InsecureConnection bool `mapstructure:"insecure_connection" required:"false"` } -func (c *RunConfig) Prepare(ctx *interpolate.Context) (errs []error) { +func (c *RunConfig) Prepare(_ *interpolate.Context, driverConfig *DriverConfig) (warnings []string, errs []error) { + if c.VNCOverWebsocket { + if driverConfig.RemoteType == "" { + errs = append(errs, fmt.Errorf("'vnc_over_websocket' can only be used with remote VMWare builds.")) + return + } + if c.VNCPortMin != 0 || c.VNCPortMax != 0 || c.VNCBindAddress != "" || c.VNCDisablePassword { + warnings = append(warnings, "[WARN] When 'vnc_over_websocket' is set "+ + "any other VNC configuration will be ignored.") + } + return + } + if c.VNCPortMin == 0 { c.VNCPortMin = 5900 } diff --git a/builder/vmware/common/run_config_test.go b/builder/vmware/common/run_config_test.go new file mode 100644 index 000000000..6b2cea1cc --- /dev/null +++ b/builder/vmware/common/run_config_test.go @@ -0,0 +1,119 @@ +package common + +import ( + "fmt" + "reflect" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/hashicorp/packer/common/bootcommand" + "github.com/hashicorp/packer/template/interpolate" +) + +func TestRunConfig_Prepare(t *testing.T) { + tc := []struct { + name string + config *RunConfig + expectedConfig *RunConfig + driver *DriverConfig + errs []error + warnings []string + }{ + { + name: "VNC dafaults", + config: &RunConfig{}, + expectedConfig: &RunConfig{ + VNCPortMin: 5900, + VNCPortMax: 6000, + VNCBindAddress: "127.0.0.1", + }, + driver: new(DriverConfig), + errs: nil, + warnings: nil, + }, + { + name: "VNC port min less than vnc port max", + config: &RunConfig{ + VNCPortMin: 5000, + VNCPortMax: 5900, + }, + expectedConfig: &RunConfig{ + VNCPortMin: 5000, + VNCPortMax: 5900, + VNCBindAddress: "127.0.0.1", + }, + driver: new(DriverConfig), + errs: nil, + warnings: nil, + }, + { + name: "VNC port min bigger than vnc port max", + config: &RunConfig{ + VNCPortMin: 5900, + VNCPortMax: 5000, + }, + expectedConfig: nil, + driver: new(DriverConfig), + errs: []error{fmt.Errorf("vnc_port_min must be less than vnc_port_max")}, + warnings: nil, + }, + { + name: "VNC port min must be positive", + config: &RunConfig{ + VNCPortMin: -1, + }, + expectedConfig: nil, + driver: new(DriverConfig), + errs: []error{fmt.Errorf("vnc_port_min must be positive")}, + warnings: nil, + }, + { + name: "fail when vnc_over_websocket set when remote_type is not set", + config: &RunConfig{ + VNCOverWebsocket: true, + }, + expectedConfig: nil, + driver: new(DriverConfig), + errs: []error{fmt.Errorf("'vnc_over_websocket' can only be used with remote VMWare builds.")}, + warnings: nil, + }, + { + name: "warn about ignored vnc configuration", + config: &RunConfig{ + VNCOverWebsocket: true, + VNCPortMin: 5000, + VNCPortMax: 5900, + }, + expectedConfig: &RunConfig{ + VNCOverWebsocket: true, + VNCPortMin: 5000, + VNCPortMax: 5900, + }, + driver: &DriverConfig{RemoteType: "esxi"}, + errs: nil, + warnings: []string{"[WARN] When 'vnc_over_websocket' is set " + + "any other VNC configuration will be ignored."}, + }, + } + + for _, c := range tc { + t.Run(c.name, func(t *testing.T) { + warnings, errs := c.config.Prepare(interpolate.NewContext(), c.driver) + if !reflect.DeepEqual(errs, c.errs) { + t.Fatalf("bad: \n expected '%v' \nactual '%v'", c.errs, errs) + } + if diff := cmp.Diff(warnings, c.warnings); diff != "" { + t.Fatalf("unexpected warnings: %s", diff) + } + if len(c.errs) == 0 { + if diff := cmp.Diff(c.config, c.expectedConfig, + cmpopts.IgnoreFields(bootcommand.VNCConfig{}, + "BootConfig", + )); diff != "" { + t.Fatalf("unexpected config: %s", diff) + } + } + }) + } +} diff --git a/builder/vmware/common/step_configure_vmx.go b/builder/vmware/common/step_configure_vmx.go index 2e48e0574..833008291 100644 --- a/builder/vmware/common/step_configure_vmx.go +++ b/builder/vmware/common/step_configure_vmx.go @@ -20,10 +20,12 @@ import ( // Produces: // display_name string - Value of the displayName key set in the VMX file type StepConfigureVMX struct { - CustomData map[string]string - DisplayName string - SkipFloppy bool - VMName string + CustomData map[string]string + DisplayName string + SkipFloppy bool + VMName string + DiskAdapterType string + CDROMAdapterType string } func (s *StepConfigureVMX) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { @@ -83,6 +85,17 @@ func (s *StepConfigureVMX) Run(ctx context.Context, state multistep.StateBag) mu state.Put("temporaryDevices", tmpBuildDevices) } + // Add our custom CD, if it exists + if cdPath, ok := state.GetOk("cd_path"); ok { + if cdPath != "" { + diskAndCDConfigData := DefaultDiskAndCDROMTypes(s.DiskAdapterType, s.CDROMAdapterType) + cdromPrefix := diskAndCDConfigData.CDROMType + "1:" + diskAndCDConfigData.CDROMType_PrimarySecondary + vmxData[cdromPrefix+".present"] = "TRUE" + vmxData[cdromPrefix+".fileName"] = cdPath.(string) + vmxData[cdromPrefix+".deviceType"] = "cdrom-image" + } + } + // If the build is taking place on a remote ESX server, the displayName // will be needed for discovery of the VM's IP address and for export // of the VM. The displayName key should always be set in the VMX file, @@ -125,5 +138,86 @@ func (s *StepConfigureVMX) Run(ctx context.Context, state multistep.StateBag) mu return multistep.ActionContinue } +type DiskAndCDConfigData struct { + SCSI_Present string + SCSI_diskAdapterType string + SATA_Present string + NVME_Present string + + DiskType string + CDROMType string + CDROMType_PrimarySecondary string + CDROM_PATH string +} + +// DefaultDiskAndCDROMTypes takes the disk adapter type and cdrom adapter type from the config and converts them +// into template interpolation data for creating or configuring a vmx. +func DefaultDiskAndCDROMTypes(diskAdapterType string, cdromAdapterType string) DiskAndCDConfigData { + diskData := DiskAndCDConfigData{ + SCSI_Present: "FALSE", + SCSI_diskAdapterType: "lsilogic", + SATA_Present: "FALSE", + NVME_Present: "FALSE", + + DiskType: "scsi", + CDROMType: "ide", + CDROMType_PrimarySecondary: "0", + } + /// Use the disk adapter type that the user specified to tweak the .vmx + // Also sync the cdrom adapter type according to what's common for that disk type. + // XXX: If the cdrom type is modified, make sure to update common/step_clean_vmx.go + // so that it will regex the correct cdrom device for removal. + diskAdapterType = strings.ToLower(diskAdapterType) + switch diskAdapterType { + case "ide": + diskData.DiskType = "ide" + diskData.CDROMType = "ide" + diskData.CDROMType_PrimarySecondary = "1" + case "sata": + diskData.SATA_Present = "TRUE" + diskData.DiskType = "sata" + diskData.CDROMType = "sata" + diskData.CDROMType_PrimarySecondary = "1" + case "nvme": + diskData.NVME_Present = "TRUE" + diskData.DiskType = "nvme" + diskData.SATA_Present = "TRUE" + diskData.CDROMType = "sata" + diskData.CDROMType_PrimarySecondary = "0" + case "scsi": + diskAdapterType = "lsilogic" + fallthrough + default: + diskData.SCSI_Present = "TRUE" + diskData.SCSI_diskAdapterType = diskAdapterType // defaults to lsilogic + diskData.DiskType = "scsi" + diskData.CDROMType = "ide" + diskData.CDROMType_PrimarySecondary = "0" + } + + /// Handle the cdrom adapter type. If the disk adapter type and the + // cdrom adapter type are the same, then ensure that the cdrom is the + // secondary device on whatever bus the disk adapter is on. + if cdromAdapterType == "" { + cdromAdapterType = diskData.CDROMType + } else if cdromAdapterType == diskAdapterType { + diskData.CDROMType_PrimarySecondary = "1" + } else { + diskData.CDROMType_PrimarySecondary = "0" + } + + switch cdromAdapterType { + case "ide": + diskData.CDROMType = "ide" + case "sata": + diskData.SATA_Present = "TRUE" + diskData.CDROMType = "sata" + case "scsi": + diskData.SCSI_Present = "TRUE" + diskData.CDROMType = "scsi" + } + return diskData +} + func (s *StepConfigureVMX) Cleanup(state multistep.StateBag) { } diff --git a/builder/vmware/common/step_configure_vmx_test.go b/builder/vmware/common/step_configure_vmx_test.go index 87469f6f1..09926acd7 100644 --- a/builder/vmware/common/step_configure_vmx_test.go +++ b/builder/vmware/common/step_configure_vmx_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/hashicorp/packer/helper/multistep" + "github.com/stretchr/testify/assert" ) func testVMXFile(t *testing.T) string { @@ -271,3 +272,108 @@ func TestStepConfigureVMX_vmxPathBad(t *testing.T) { } } + +func TestStepConfigureVMX_DefaultDiskAndCDROMTypes(t *testing.T) { + type testCase struct { + inDiskAdapter string + inCDromAdapter string + expectedOut DiskAndCDConfigData + reason string + } + testcases := []testCase{ + { + inDiskAdapter: "", + inCDromAdapter: "", + expectedOut: DiskAndCDConfigData{ + SCSI_Present: "TRUE", + SCSI_diskAdapterType: "", + SATA_Present: "FALSE", + NVME_Present: "FALSE", + + DiskType: "scsi", + CDROMType: "ide", + CDROMType_PrimarySecondary: "0", + }, + reason: "Test that default creases scsi disk with ide cd", + }, + { + inDiskAdapter: "ide", + inCDromAdapter: "", + expectedOut: DiskAndCDConfigData{ + SCSI_Present: "FALSE", + SCSI_diskAdapterType: "lsilogic", + SATA_Present: "FALSE", + NVME_Present: "FALSE", + + DiskType: "ide", + CDROMType: "ide", + CDROMType_PrimarySecondary: "1", + }, + reason: "ide disk adapter should pass through and not get defaulted to scsi", + }, + { + inDiskAdapter: "sata", + inCDromAdapter: "", + expectedOut: DiskAndCDConfigData{ + SCSI_Present: "FALSE", + SCSI_diskAdapterType: "lsilogic", + SATA_Present: "TRUE", + NVME_Present: "FALSE", + + DiskType: "sata", + CDROMType: "sata", + CDROMType_PrimarySecondary: "1", + }, + reason: "when disk is set to sata, cdromtype should also default to sata", + }, + { + inDiskAdapter: "nvme", + inCDromAdapter: "", + expectedOut: DiskAndCDConfigData{ + SCSI_Present: "FALSE", + SCSI_diskAdapterType: "lsilogic", + SATA_Present: "TRUE", + NVME_Present: "TRUE", + + DiskType: "nvme", + CDROMType: "sata", + CDROMType_PrimarySecondary: "0", + }, + reason: "when disk is set to nvme, cdromtype should default to sata", + }, + { + inDiskAdapter: "scsi", + inCDromAdapter: "", + expectedOut: DiskAndCDConfigData{ + SCSI_Present: "TRUE", + SCSI_diskAdapterType: "lsilogic", + SATA_Present: "FALSE", + NVME_Present: "FALSE", + + DiskType: "scsi", + CDROMType: "ide", + CDROMType_PrimarySecondary: "0", + }, + reason: "when disk is set to scsi, adapter should default back to lsilogic", + }, + { + inDiskAdapter: "scsi", + inCDromAdapter: "scsi", + expectedOut: DiskAndCDConfigData{ + SCSI_Present: "TRUE", + SCSI_diskAdapterType: "lsilogic", + SATA_Present: "FALSE", + NVME_Present: "FALSE", + + DiskType: "scsi", + CDROMType: "scsi", + CDROMType_PrimarySecondary: "0", + }, + reason: "when cdrom adapter is set, it should override the default", + }, + } + for _, tc := range testcases { + diskConfigData := DefaultDiskAndCDROMTypes(tc.inDiskAdapter, tc.inCDromAdapter) + assert.Equal(t, diskConfigData, tc.expectedOut, tc.reason) + } +} diff --git a/builder/vmware/common/step_create_disks.go b/builder/vmware/common/step_create_disks.go index 2bd5bfc91..4bca0f453 100644 --- a/builder/vmware/common/step_create_disks.go +++ b/builder/vmware/common/step_create_disks.go @@ -45,8 +45,13 @@ func (s *StepCreateDisks) Run(ctx context.Context, state multistep.StateBag) mul } // Additional disks if len(s.AdditionalDiskSize) > 0 { + incrementer := 1 for i, diskSize := range s.AdditionalDiskSize { - path := filepath.Join(*s.OutputDir, fmt.Sprintf("%s-%d.vmdk", s.DiskName, i+1)) + // scsi slot 7 is reserved, so we skip it. + if i+incrementer == 7 { + incrementer = 2 + } + path := filepath.Join(*s.OutputDir, fmt.Sprintf("%s-%d.vmdk", s.DiskName, i+incrementer)) diskFullPaths = append(diskFullPaths, path) size := fmt.Sprintf("%dM", uint64(diskSize)) diskSizes = append(diskSizes, size) diff --git a/builder/vmware/common/step_prepare_tools.go b/builder/vmware/common/step_prepare_tools.go index 7c9f992a3..bd64f8885 100644 --- a/builder/vmware/common/step_prepare_tools.go +++ b/builder/vmware/common/step_prepare_tools.go @@ -11,6 +11,7 @@ import ( type StepPrepareTools struct { RemoteType string ToolsUploadFlavor string + ToolsSourcePath string } func (c *StepPrepareTools) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { @@ -20,11 +21,15 @@ func (c *StepPrepareTools) Run(ctx context.Context, state multistep.StateBag) mu return multistep.ActionContinue } - if c.ToolsUploadFlavor == "" { + if c.ToolsUploadFlavor == "" && c.ToolsSourcePath == "" { return multistep.ActionContinue } - path := driver.ToolsIsoPath(c.ToolsUploadFlavor) + path := c.ToolsSourcePath + if path == "" { + path = driver.ToolsIsoPath(c.ToolsUploadFlavor) + } + if _, err := os.Stat(path); err != nil { state.Put("error", fmt.Errorf( "Couldn't find VMware tools for '%s'! VMware often downloads these\n"+ diff --git a/builder/vmware/common/step_prepare_tools_test.go b/builder/vmware/common/step_prepare_tools_test.go index cddf0ffba..e70f7d43b 100644 --- a/builder/vmware/common/step_prepare_tools_test.go +++ b/builder/vmware/common/step_prepare_tools_test.go @@ -114,3 +114,65 @@ func TestStepPrepareTools_nonExist(t *testing.T) { t.Fatal("should NOT have tools_upload_source") } } + +func TestStepPrepareTools_SourcePath(t *testing.T) { + state := testState(t) + step := &StepPrepareTools{ + RemoteType: "", + ToolsSourcePath: "/path/to/tool.iso", + } + + driver := state.Get("driver").(*DriverMock) + + // Mock results + driver.ToolsIsoPathResult = "foo" + + // Test the run + if action := step.Run(context.Background(), state); action != multistep.ActionHalt { + t.Fatalf("Should have failed when stat failed %#v", action) + } + if _, ok := state.GetOk("error"); !ok { + t.Fatal("should have error") + } + + // Test the driver + if driver.ToolsIsoPathCalled { + t.Fatal("tools iso path should not be called when ToolsSourcePath is set") + } + + // Test the resulting state + if _, ok := state.GetOk("tools_upload_source"); ok { + t.Fatal("should NOT have tools_upload_source") + } +} + +func TestStepPrepareTools_SourcePath_exists(t *testing.T) { + state := testState(t) + step := &StepPrepareTools{ + RemoteType: "", + ToolsSourcePath: "./step_prepare_tools.go", + } + + driver := state.Get("driver").(*DriverMock) + + // Mock results + driver.ToolsIsoPathResult = "foo" + + // Test the run + if action := step.Run(context.Background(), state); action != multistep.ActionContinue { + t.Fatalf("Step should succeed when stat succeeds: %#v", action) + } + if _, ok := state.GetOk("error"); ok { + t.Fatal("should NOT have error") + } + + // Test the driver + if driver.ToolsIsoPathCalled { + t.Fatal("tools iso path should not be called when ToolsSourcePath is set") + } + + // Test the resulting state + if _, ok := state.GetOk("tools_upload_source"); !ok { + t.Fatal("should have tools_upload_source") + } +} diff --git a/builder/vmware/common/step_type_boot_command.go b/builder/vmware/common/step_vnc_boot_command.go similarity index 50% rename from builder/vmware/common/step_type_boot_command.go rename to builder/vmware/common/step_vnc_boot_command.go index 13baae9e2..0471fbc07 100644 --- a/builder/vmware/common/step_type_boot_command.go +++ b/builder/vmware/common/step_vnc_boot_command.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "log" - "net" "time" "github.com/hashicorp/packer/common/bootcommand" @@ -23,22 +22,20 @@ import ( // // Produces: // -type StepTypeBootCommand struct { - BootCommand string - VNCEnabled bool - BootWait time.Duration - VMName string - Ctx interpolate.Context - KeyInterval time.Duration +type StepVNCBootCommand struct { + Config bootcommand.VNCConfig + VMName string + Ctx interpolate.Context } -type bootCommandTemplateData struct { + +type VNCBootCommandTemplateData struct { HTTPIP string HTTPPort int Name string } -func (s *StepTypeBootCommand) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { - if !s.VNCEnabled { +func (s *StepVNCBootCommand) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { + if s.Config.DisableVNC { log.Println("Skipping boot command step...") return multistep.ActionContinue } @@ -46,68 +43,36 @@ func (s *StepTypeBootCommand) Run(ctx context.Context, state multistep.StateBag) debug := state.Get("debug").(bool) httpPort := state.Get("http_port").(int) ui := state.Get("ui").(packer.Ui) - vncIp := state.Get("vnc_ip").(string) - vncPort := state.Get("vnc_port").(int) - vncPassword := state.Get("vnc_password") + conn := state.Get("vnc_conn").(*vnc.ClientConn) + defer conn.Close() // Wait the for the vm to boot. - if int64(s.BootWait) > 0 { - ui.Say(fmt.Sprintf("Waiting %s for boot...", s.BootWait.String())) + if int64(s.Config.BootWait) > 0 { + ui.Say(fmt.Sprintf("Waiting %s for boot...", s.Config.BootWait.String())) select { - case <-time.After(s.BootWait): + case <-time.After(s.Config.BootWait): break case <-ctx.Done(): return multistep.ActionHalt } } - var pauseFn multistep.DebugPauseFn if debug { pauseFn = state.Get("pauseFn").(multistep.DebugPauseFn) } - // Connect to VNC - ui.Say(fmt.Sprintf("Connecting to VM via VNC (%s:%d)", vncIp, vncPort)) - - nc, err := net.Dial("tcp", fmt.Sprintf("%s:%d", vncIp, vncPort)) - if err != nil { - err := fmt.Errorf("Error connecting to VNC: %s", err) - state.Put("error", err) - ui.Error(err.Error()) - return multistep.ActionHalt - } - defer nc.Close() - - var auth []vnc.ClientAuth - - if vncPassword != nil && len(vncPassword.(string)) > 0 { - auth = []vnc.ClientAuth{&vnc.PasswordAuth{Password: vncPassword.(string)}} - } else { - auth = []vnc.ClientAuth{new(vnc.ClientAuthNone)} - } - - c, err := vnc.Client(nc, &vnc.ClientConfig{Auth: auth, Exclusive: true}) - if err != nil { - err := fmt.Errorf("Error handshaking with VNC: %s", err) - state.Put("error", err) - ui.Error(err.Error()) - return multistep.ActionHalt - } - defer c.Close() - - log.Printf("Connected to VNC desktop: %s", c.DesktopName) - hostIP := state.Get("http_ip").(string) - s.Ctx.Data = &bootCommandTemplateData{ - hostIP, - httpPort, - s.VMName, + s.Ctx.Data = &VNCBootCommandTemplateData{ + HTTPIP: hostIP, + HTTPPort: httpPort, + Name: s.VMName, } - d := bootcommand.NewVNCDriver(c, s.KeyInterval) + d := bootcommand.NewVNCDriver(conn, s.Config.BootKeyInterval) ui.Say("Typing the boot command over VNC...") - command, err := interpolate.Render(s.BootCommand, &s.Ctx) + flatBootCommand := s.Config.FlatBootCommand() + command, err := interpolate.Render(flatBootCommand, &s.Ctx) if err != nil { err := fmt.Errorf("Error preparing boot command: %s", err) state.Put("error", err) @@ -138,4 +103,4 @@ func (s *StepTypeBootCommand) Run(ctx context.Context, state multistep.StateBag) return multistep.ActionContinue } -func (*StepTypeBootCommand) Cleanup(multistep.StateBag) {} +func (*StepVNCBootCommand) Cleanup(multistep.StateBag) {} diff --git a/builder/vmware/common/step_vnc_connect.go b/builder/vmware/common/step_vnc_connect.go new file mode 100644 index 000000000..7499c8279 --- /dev/null +++ b/builder/vmware/common/step_vnc_connect.go @@ -0,0 +1,141 @@ +package common + +import ( + "context" + "crypto/tls" + "fmt" + "log" + "net" + "net/url" + + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" + "github.com/mitchellh/go-vnc" + "golang.org/x/net/websocket" +) + +type StepVNCConnect struct { + VNCEnabled bool + VNCOverWebsocket bool + InsecureConnection bool + DriverConfig *DriverConfig +} + +func (s *StepVNCConnect) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { + if !s.VNCOverWebsocket && !s.VNCEnabled { + return multistep.ActionContinue + } + ui := state.Get("ui").(packer.Ui) + + var c *vnc.ClientConn + var err error + + if s.VNCOverWebsocket { + ui.Say("Connecting to VNC over websocket...") + c, err = s.ConnectVNCOverWebsocketClient(state) + } else { + ui.Say("Connecting to VNC...") + c, err = s.ConnectVNC(state) + } + + if err != nil { + state.Put("error", err) + ui.Error(err.Error()) + return multistep.ActionHalt + } + + state.Put("vnc_conn", c) + return multistep.ActionContinue +} + +func (s *StepVNCConnect) ConnectVNCOverWebsocketClient(state multistep.StateBag) (*vnc.ClientConn, error) { + driver := state.Get("driver").(*ESX5Driver) + + // Acquire websocket ticket + ticket, err := driver.AcquireVNCOverWebsocketTicket() + if err != nil { + err := fmt.Errorf("Error acquiring vnc over websocket ticket: %s", err) + state.Put("error", err) + return nil, err + } + host := ticket.Host + if len(host) == 0 { + host = s.DriverConfig.RemoteHost + } + port := ticket.Port + if port == 0 { + port = 443 + } + + websocketUrl := fmt.Sprintf("wss://%s:%d/ticket/%s", host, port, ticket.Ticket) + log.Printf("[DEBUG] websocket url: %s", websocketUrl) + u, err := url.Parse(websocketUrl) + if err != nil { + err := fmt.Errorf("Error parsing websocket url: %s\n", err) + state.Put("error", err) + return nil, err + } + origin, err := url.Parse("http://localhost") + if err != nil { + err := fmt.Errorf("Error parsing websocket origin url: %s\n", err) + state.Put("error", err) + return nil, err + } + + // Create the websocket connection and set it to a BinaryFrame + websocketConfig := &websocket.Config{ + Location: u, + Origin: origin, + TlsConfig: &tls.Config{InsecureSkipVerify: s.InsecureConnection}, + Version: websocket.ProtocolVersionHybi13, + Protocol: []string{"binary"}, + } + nc, err := websocket.DialConfig(websocketConfig) + if err != nil { + err := fmt.Errorf("Error Dialing: %s\n", err) + state.Put("error", err) + return nil, err + } + nc.PayloadType = websocket.BinaryFrame + + // Setup the VNC connection over the websocket + ccconfig := &vnc.ClientConfig{ + Auth: []vnc.ClientAuth{new(vnc.ClientAuthNone)}, + Exclusive: false, + } + c, err := vnc.Client(nc, ccconfig) + if err != nil { + err := fmt.Errorf("Error setting the VNC over websocket client: %s\n", err) + state.Put("error", err) + return nil, err + } + return c, nil +} + +func (s *StepVNCConnect) ConnectVNC(state multistep.StateBag) (*vnc.ClientConn, error) { + vncIp := state.Get("vnc_ip").(string) + vncPort := state.Get("vnc_port").(int) + vncPassword := state.Get("vnc_password") + + nc, err := net.Dial("tcp", fmt.Sprintf("%s:%d", vncIp, vncPort)) + if err != nil { + err := fmt.Errorf("Error connecting to VNC: %s", err) + state.Put("error", err) + return nil, err + } + + auth := []vnc.ClientAuth{new(vnc.ClientAuthNone)} + if vncPassword != nil && len(vncPassword.(string)) > 0 { + auth = []vnc.ClientAuth{&vnc.PasswordAuth{Password: vncPassword.(string)}} + } + + c, err := vnc.Client(nc, &vnc.ClientConfig{Auth: auth, Exclusive: true}) + if err != nil { + err := fmt.Errorf("Error handshaking with VNC: %s", err) + state.Put("error", err) + return nil, err + } + return c, nil +} + +func (s *StepVNCConnect) Cleanup(multistep.StateBag) {} diff --git a/builder/vmware/common/tools_config.go b/builder/vmware/common/tools_config.go index 02a54f375..dd37831bf 100644 --- a/builder/vmware/common/tools_config.go +++ b/builder/vmware/common/tools_config.go @@ -3,6 +3,8 @@ package common import ( + "fmt" + "github.com/hashicorp/packer/template/interpolate" ) @@ -18,12 +20,22 @@ type ToolsConfig struct { // the upload path is set to `{{.Flavor}}.iso`. This setting is not used // when `remote_type` is `esx5`. ToolsUploadPath string `mapstructure:"tools_upload_path" required:"false"` + // The path on your local machine to fetch the vmware tools from. If this + // is not set but the tools_upload_flavor is set, then Packer will try to + // load the VMWare tools from the VMWare installation directory. + ToolsSourcePath string `mapstructure:"tools_source_path" required:"false"` } func (c *ToolsConfig) Prepare(ctx *interpolate.Context) []error { + errs := []error{} if c.ToolsUploadPath == "" { + if c.ToolsSourcePath != "" && c.ToolsUploadFlavor == "" { + errs = append(errs, fmt.Errorf("If you provide a "+ + "tools_source_path, you must also provide either a "+ + "tools_upload_flavor or a tools_upload_path.")) + } c.ToolsUploadPath = "{{ .Flavor }}.iso" } - return nil + return errs } diff --git a/builder/vmware/common/tools_config_test.go b/builder/vmware/common/tools_config_test.go new file mode 100644 index 000000000..8294661ca --- /dev/null +++ b/builder/vmware/common/tools_config_test.go @@ -0,0 +1,65 @@ +package common + +import ( + "testing" + + "github.com/hashicorp/packer/template/interpolate" +) + +func TestToolsConfigPrepare_Empty(t *testing.T) { + c := &ToolsConfig{} + + errs := c.Prepare(interpolate.NewContext()) + if len(errs) > 0 { + t.Fatalf("err: %#v", errs) + } + + if c.ToolsUploadPath != "{{ .Flavor }}.iso" { + t.Fatal("should have defaulted tools upload path") + } +} + +func TestToolsConfigPrepare_SetUploadPath(t *testing.T) { + c := &ToolsConfig{ + ToolsUploadPath: "path/to/tools.iso", + } + + errs := c.Prepare(interpolate.NewContext()) + if len(errs) > 0 { + t.Fatalf("err: %#v", errs) + } + + if c.ToolsUploadPath != "path/to/tools.iso" { + t.Fatal("should have used given tools upload path") + } +} + +func TestToolsConfigPrepare_ErrorIfOnlySource(t *testing.T) { + c := &ToolsConfig{ + ToolsSourcePath: "path/to/tools.iso", + } + + errs := c.Prepare(interpolate.NewContext()) + if len(errs) != 1 { + t.Fatalf("Should have received an error because the flavor and " + + "upload path aren't set") + } +} + +func TestToolsConfigPrepare_SourceSuccess(t *testing.T) { + for _, c := range []*ToolsConfig{ + &ToolsConfig{ + ToolsSourcePath: "path/to/tools.iso", + ToolsUploadPath: "partypath.iso", + }, + &ToolsConfig{ + ToolsSourcePath: "path/to/tools.iso", + ToolsUploadFlavor: "linux", + }, + } { + errs := c.Prepare(interpolate.NewContext()) + if len(errs) != 0 { + t.Fatalf("Should not have received an error") + } + } +} diff --git a/builder/vmware/iso/builder.go b/builder/vmware/iso/builder.go index 624bd8c86..db4afcd6b 100644 --- a/builder/vmware/iso/builder.go +++ b/builder/vmware/iso/builder.go @@ -76,12 +76,22 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack Directories: b.config.FloppyConfig.FloppyDirectories, Label: b.config.FloppyConfig.FloppyLabel, }, + &common.StepCreateCD{ + Files: b.config.CDConfig.CDFiles, + Label: b.config.CDConfig.CDLabel, + }, &vmwcommon.StepRemoteUpload{ Key: "floppy_path", Message: "Uploading Floppy to remote machine...", DoCleanup: true, Checksum: "none", }, + &vmwcommon.StepRemoteUpload{ + Key: "cd_path", + Message: "Uploading CD to remote machine...", + DoCleanup: true, + Checksum: "none", + }, &vmwcommon.StepRemoteUpload{ Key: "iso_path", Message: "Uploading ISO to remote machine...", @@ -99,9 +109,11 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack }, &stepCreateVMX{}, &vmwcommon.StepConfigureVMX{ - CustomData: b.config.VMXData, - VMName: b.config.VMName, - DisplayName: b.config.VMXDisplayName, + CustomData: b.config.VMXData, + VMName: b.config.VMName, + DisplayName: b.config.VMXDisplayName, + DiskAdapterType: b.config.DiskAdapterType, + CDROMAdapterType: b.config.CdromAdapterType, }, &vmwcommon.StepSuppressMessages{}, &vmwcommon.StepHTTPIPDiscover{}, @@ -112,7 +124,7 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack HTTPAddress: b.config.HTTPAddress, }, &vmwcommon.StepConfigureVNC{ - Enabled: !b.config.DisableVNC, + Enabled: !b.config.DisableVNC && !b.config.VNCOverWebsocket, VNCBindAddress: b.config.VNCBindAddress, VNCPortMin: b.config.VNCPortMin, VNCPortMax: b.config.VNCPortMax, @@ -127,13 +139,16 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack DurationBeforeStop: 5 * time.Second, Headless: b.config.Headless, }, - &vmwcommon.StepTypeBootCommand{ - BootWait: b.config.BootWait, - VNCEnabled: !b.config.DisableVNC, - BootCommand: b.config.FlatBootCommand(), - VMName: b.config.VMName, - Ctx: b.config.ctx, - KeyInterval: b.config.VNCConfig.BootKeyInterval, + &vmwcommon.StepVNCConnect{ + VNCEnabled: !b.config.DisableVNC, + VNCOverWebsocket: b.config.VNCOverWebsocket, + InsecureConnection: b.config.InsecureConnection, + DriverConfig: &b.config.DriverConfig, + }, + &vmwcommon.StepVNCBootCommand{ + Config: b.config.VNCConfig, + VMName: b.config.VMName, + Ctx: b.config.ctx, }, &communicator.StepConnect{ Config: &b.config.SSHConfig.Comm, diff --git a/builder/vmware/iso/config.go b/builder/vmware/iso/config.go index dcb5d0faf..becb555c3 100644 --- a/builder/vmware/iso/config.go +++ b/builder/vmware/iso/config.go @@ -23,6 +23,7 @@ type Config struct { common.HTTPConfig `mapstructure:",squash"` common.ISOConfig `mapstructure:",squash"` common.FloppyConfig `mapstructure:",squash"` + common.CDConfig `mapstructure:",squash"` bootcommand.VNCConfig `mapstructure:",squash"` vmwcommon.DriverConfig `mapstructure:",squash"` vmwcommon.HWConfig `mapstructure:",squash"` @@ -93,24 +94,26 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { } // Accumulate any errors and warnings + var warnings []string var errs *packer.MultiError - warnings := make([]string, 0) + runConfigWarnings, runConfigErrs := c.RunConfig.Prepare(&c.ctx, &c.DriverConfig) + warnings = append(warnings, runConfigWarnings...) + errs = packer.MultiErrorAppend(errs, runConfigErrs...) isoWarnings, isoErrs := c.ISOConfig.Prepare(&c.ctx) warnings = append(warnings, isoWarnings...) errs = packer.MultiErrorAppend(errs, isoErrs...) errs = packer.MultiErrorAppend(errs, c.HTTPConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.HWConfig.Prepare(&c.ctx)...) + errs = packer.MultiErrorAppend(errs, c.OutputConfig.Prepare(&c.ctx, &c.PackerConfig)...) errs = packer.MultiErrorAppend(errs, c.DriverConfig.Prepare(&c.ctx)...) - errs = packer.MultiErrorAppend(errs, - c.OutputConfig.Prepare(&c.ctx, &c.PackerConfig)...) - errs = packer.MultiErrorAppend(errs, c.RunConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.ShutdownConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.SSHConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.ToolsConfig.Prepare(&c.ctx)...) + errs = packer.MultiErrorAppend(errs, c.CDConfig.Prepare(&c.ctx)...) + errs = packer.MultiErrorAppend(errs, c.VNCConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.VMXConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.FloppyConfig.Prepare(&c.ctx)...) - errs = packer.MultiErrorAppend(errs, c.VNCConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.ExportConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.DiskConfig.Prepare(&c.ctx)...) @@ -163,19 +166,6 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { c.HWConfig.Network = "nat" } - // Remote configuration validation - if c.RemoteType != "" { - if c.RemoteHost == "" { - errs = packer.MultiErrorAppend(errs, - fmt.Errorf("remote_host must be specified")) - } - - if c.RemoteType != "esx5" { - errs = packer.MultiErrorAppend(errs, - fmt.Errorf("Only 'esx5' value is accepted for remote_type")) - } - } - if c.Format == "" { if c.RemoteType == "" { c.Format = "vmx" @@ -184,11 +174,18 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { } } - if c.RemoteType == "" && c.Format == "vmx" { - // if we're building locally and want a vmx, there's nothing to export. - // Set skip export flag here to keep the export step from attempting - // an unneded export - c.SkipExport = true + if c.RemoteType == "" { + if c.Format == "vmx" { + // if we're building locally and want a vmx, there's nothing to export. + // Set skip export flag here to keep the export step from attempting + // an unneded export + c.SkipExport = true + } + if c.Headless && c.DisableVNC { + warnings = append(warnings, + "Headless mode uses VNC to retrieve output. Since VNC has been disabled,\n"+ + "you won't be able to see any output.") + } } err = c.DriverConfig.Validate(c.SkipExport) @@ -196,6 +193,14 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { errs = packer.MultiErrorAppend(errs, err) } + if c.CdromAdapterType != "" { + c.CdromAdapterType = strings.ToLower(c.CdromAdapterType) + if c.CdromAdapterType != "ide" && c.CdromAdapterType != "sata" && c.CdromAdapterType != "scsi" { + errs = packer.MultiErrorAppend(errs, + fmt.Errorf("cdrom_adapter_type must be one of ide, sata, or scsi")) + } + } + // Warnings if c.ShutdownCommand == "" { warnings = append(warnings, @@ -203,12 +208,6 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { "will forcibly halt the virtual machine, which may result in data loss.") } - if c.Headless && c.DisableVNC { - warnings = append(warnings, - "Headless mode uses VNC to retrieve output. Since VNC has been disabled,\n"+ - "you won't be able to see any output.") - } - if errs != nil && len(errs.Errors) > 0 { return warnings, errs } diff --git a/builder/vmware/iso/config.hcl2spec.go b/builder/vmware/iso/config.hcl2spec.go index 5ee9f0283..8a726b193 100644 --- a/builder/vmware/iso/config.hcl2spec.go +++ b/builder/vmware/iso/config.hcl2spec.go @@ -20,6 +20,7 @@ type FlatConfig struct { HTTPPortMin *int `mapstructure:"http_port_min" cty:"http_port_min" hcl:"http_port_min"` HTTPPortMax *int `mapstructure:"http_port_max" cty:"http_port_max" hcl:"http_port_max"` HTTPAddress *string `mapstructure:"http_bind_address" cty:"http_bind_address" hcl:"http_bind_address"` + HTTPInterface *string `mapstructure:"http_interface" undocumented:"true" cty:"http_interface" hcl:"http_interface"` ISOChecksum *string `mapstructure:"iso_checksum" required:"true" cty:"iso_checksum" hcl:"iso_checksum"` RawSingleISOUrl *string `mapstructure:"iso_url" required:"true" cty:"iso_url" hcl:"iso_url"` ISOUrls []string `mapstructure:"iso_urls" cty:"iso_urls" hcl:"iso_urls"` @@ -28,6 +29,8 @@ type FlatConfig struct { FloppyFiles []string `mapstructure:"floppy_files" cty:"floppy_files" hcl:"floppy_files"` FloppyDirectories []string `mapstructure:"floppy_dirs" cty:"floppy_dirs" hcl:"floppy_dirs"` FloppyLabel *string `mapstructure:"floppy_label" cty:"floppy_label" hcl:"floppy_label"` + CDFiles []string `mapstructure:"cd_files" cty:"cd_files" hcl:"cd_files"` + CDLabel *string `mapstructure:"cd_label" cty:"cd_label" hcl:"cd_label"` BootGroupInterval *string `mapstructure:"boot_keygroup_interval" cty:"boot_keygroup_interval" hcl:"boot_keygroup_interval"` BootWait *string `mapstructure:"boot_wait" cty:"boot_wait" hcl:"boot_wait"` BootCommand []string `mapstructure:"boot_command" cty:"boot_command" hcl:"boot_command"` @@ -62,6 +65,8 @@ type FlatConfig struct { VNCPortMin *int `mapstructure:"vnc_port_min" required:"false" cty:"vnc_port_min" hcl:"vnc_port_min"` VNCPortMax *int `mapstructure:"vnc_port_max" cty:"vnc_port_max" hcl:"vnc_port_max"` VNCDisablePassword *bool `mapstructure:"vnc_disable_password" required:"false" cty:"vnc_disable_password" hcl:"vnc_disable_password"` + VNCOverWebsocket *bool `mapstructure:"vnc_over_websocket" required:"false" cty:"vnc_over_websocket" hcl:"vnc_over_websocket"` + InsecureConnection *bool `mapstructure:"insecure_connection" required:"false" cty:"insecure_connection" hcl:"insecure_connection"` ShutdownCommand *string `mapstructure:"shutdown_command" required:"false" cty:"shutdown_command" hcl:"shutdown_command"` ShutdownTimeout *string `mapstructure:"shutdown_timeout" required:"false" cty:"shutdown_timeout" hcl:"shutdown_timeout"` Type *string `mapstructure:"communicator" cty:"communicator" hcl:"communicator"` @@ -114,6 +119,7 @@ type FlatConfig struct { SSHSkipRequestPty *bool `mapstructure:"ssh_skip_request_pty" cty:"ssh_skip_request_pty" hcl:"ssh_skip_request_pty"` ToolsUploadFlavor *string `mapstructure:"tools_upload_flavor" required:"false" cty:"tools_upload_flavor" hcl:"tools_upload_flavor"` ToolsUploadPath *string `mapstructure:"tools_upload_path" required:"false" cty:"tools_upload_path" hcl:"tools_upload_path"` + ToolsSourcePath *string `mapstructure:"tools_source_path" required:"false" cty:"tools_source_path" hcl:"tools_source_path"` VMXData map[string]string `mapstructure:"vmx_data" required:"false" cty:"vmx_data" hcl:"vmx_data"` VMXDataPost map[string]string `mapstructure:"vmx_data_post" required:"false" cty:"vmx_data_post" hcl:"vmx_data_post"` VMXRemoveEthernet *bool `mapstructure:"vmx_remove_ethernet_interfaces" required:"false" cty:"vmx_remove_ethernet_interfaces" hcl:"vmx_remove_ethernet_interfaces"` @@ -159,6 +165,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "http_port_min": &hcldec.AttrSpec{Name: "http_port_min", Type: cty.Number, Required: false}, "http_port_max": &hcldec.AttrSpec{Name: "http_port_max", Type: cty.Number, Required: false}, "http_bind_address": &hcldec.AttrSpec{Name: "http_bind_address", Type: cty.String, Required: false}, + "http_interface": &hcldec.AttrSpec{Name: "http_interface", Type: cty.String, Required: false}, "iso_checksum": &hcldec.AttrSpec{Name: "iso_checksum", Type: cty.String, Required: false}, "iso_url": &hcldec.AttrSpec{Name: "iso_url", Type: cty.String, Required: false}, "iso_urls": &hcldec.AttrSpec{Name: "iso_urls", Type: cty.List(cty.String), Required: false}, @@ -167,6 +174,8 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "floppy_files": &hcldec.AttrSpec{Name: "floppy_files", Type: cty.List(cty.String), Required: false}, "floppy_dirs": &hcldec.AttrSpec{Name: "floppy_dirs", Type: cty.List(cty.String), Required: false}, "floppy_label": &hcldec.AttrSpec{Name: "floppy_label", Type: cty.String, Required: false}, + "cd_files": &hcldec.AttrSpec{Name: "cd_files", Type: cty.List(cty.String), Required: false}, + "cd_label": &hcldec.AttrSpec{Name: "cd_label", Type: cty.String, Required: false}, "boot_keygroup_interval": &hcldec.AttrSpec{Name: "boot_keygroup_interval", Type: cty.String, Required: false}, "boot_wait": &hcldec.AttrSpec{Name: "boot_wait", Type: cty.String, Required: false}, "boot_command": &hcldec.AttrSpec{Name: "boot_command", Type: cty.List(cty.String), Required: false}, @@ -201,6 +210,8 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "vnc_port_min": &hcldec.AttrSpec{Name: "vnc_port_min", Type: cty.Number, Required: false}, "vnc_port_max": &hcldec.AttrSpec{Name: "vnc_port_max", Type: cty.Number, Required: false}, "vnc_disable_password": &hcldec.AttrSpec{Name: "vnc_disable_password", Type: cty.Bool, Required: false}, + "vnc_over_websocket": &hcldec.AttrSpec{Name: "vnc_over_websocket", Type: cty.Bool, Required: false}, + "insecure_connection": &hcldec.AttrSpec{Name: "insecure_connection", Type: cty.Bool, Required: false}, "shutdown_command": &hcldec.AttrSpec{Name: "shutdown_command", Type: cty.String, Required: false}, "shutdown_timeout": &hcldec.AttrSpec{Name: "shutdown_timeout", Type: cty.String, Required: false}, "communicator": &hcldec.AttrSpec{Name: "communicator", Type: cty.String, Required: false}, @@ -253,6 +264,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "ssh_skip_request_pty": &hcldec.AttrSpec{Name: "ssh_skip_request_pty", Type: cty.Bool, Required: false}, "tools_upload_flavor": &hcldec.AttrSpec{Name: "tools_upload_flavor", Type: cty.String, Required: false}, "tools_upload_path": &hcldec.AttrSpec{Name: "tools_upload_path", Type: cty.String, Required: false}, + "tools_source_path": &hcldec.AttrSpec{Name: "tools_source_path", Type: cty.String, Required: false}, "vmx_data": &hcldec.AttrSpec{Name: "vmx_data", Type: cty.Map(cty.String), Required: false}, "vmx_data_post": &hcldec.AttrSpec{Name: "vmx_data_post", Type: cty.Map(cty.String), Required: false}, "vmx_remove_ethernet_interfaces": &hcldec.AttrSpec{Name: "vmx_remove_ethernet_interfaces", Type: cty.Bool, Required: false}, diff --git a/builder/vmware/iso/step_create_vmx.go b/builder/vmware/iso/step_create_vmx.go index 7a837cabd..d764d5aeb 100644 --- a/builder/vmware/iso/step_create_vmx.go +++ b/builder/vmware/iso/step_create_vmx.go @@ -25,15 +25,8 @@ type vmxTemplateData struct { CpuCount string MemorySize string - SCSI_Present string - SCSI_diskAdapterType string - SATA_Present string - NVME_Present string - - DiskName string - DiskType string - CDROMType string - CDROMType_PrimarySecondary string + DiskName string + vmwcommon.DiskAndCDConfigData Network_Type string Network_Device string @@ -112,10 +105,16 @@ func (s *stepCreateVMX) Run(ctx context.Context, state multistep.StateBag) multi ictx := config.ctx + // Mount extra vmdks we created earlier. if len(config.AdditionalDiskSize) > 0 { + incrementer := 1 for i := range config.AdditionalDiskSize { + // slot 7 is special and reserved, so we need to skip that index. + if i+1 == 7 { + incrementer = 2 + } ictx.Data = &additionalDiskTemplateData{ - DiskNumber: i + 1, + DiskNumber: i + incrementer, DiskName: config.DiskName, } @@ -160,15 +159,6 @@ func (s *stepCreateVMX) Run(ctx context.Context, state multistep.StateBag) multi Version: config.Version, ISOPath: isoPath, - SCSI_Present: "FALSE", - SCSI_diskAdapterType: "lsilogic", - SATA_Present: "FALSE", - NVME_Present: "FALSE", - - DiskType: "scsi", - CDROMType: "ide", - CDROMType_PrimarySecondary: "0", - Network_Adapter: "e1000", Sound_Present: map[bool]string{true: "TRUE", false: "FALSE"}[bool(config.HWConfig.Sound)], @@ -178,65 +168,7 @@ func (s *stepCreateVMX) Run(ctx context.Context, state multistep.StateBag) multi Parallel_Present: "FALSE", } - /// Use the disk adapter type that the user specified to tweak the .vmx - // Also sync the cdrom adapter type according to what's common for that disk type. - // XXX: If the cdrom type is modified, make sure to update common/step_clean_vmx.go - // so that it will regex the correct cdrom device for removal. - diskAdapterType := strings.ToLower(config.DiskAdapterType) - switch diskAdapterType { - case "ide": - templateData.DiskType = "ide" - templateData.CDROMType = "ide" - templateData.CDROMType_PrimarySecondary = "1" - case "sata": - templateData.SATA_Present = "TRUE" - templateData.DiskType = "sata" - templateData.CDROMType = "sata" - templateData.CDROMType_PrimarySecondary = "1" - case "nvme": - templateData.NVME_Present = "TRUE" - templateData.DiskType = "nvme" - templateData.SATA_Present = "TRUE" - templateData.CDROMType = "sata" - templateData.CDROMType_PrimarySecondary = "0" - case "scsi": - diskAdapterType = "lsilogic" - fallthrough - default: - templateData.SCSI_Present = "TRUE" - templateData.SCSI_diskAdapterType = diskAdapterType - templateData.DiskType = "scsi" - templateData.CDROMType = "ide" - templateData.CDROMType_PrimarySecondary = "0" - } - - /// Handle the cdrom adapter type. If the disk adapter type and the - // cdrom adapter type are the same, then ensure that the cdrom is the - // secondary device on whatever bus the disk adapter is on. - cdromAdapterType := strings.ToLower(config.CdromAdapterType) - if cdromAdapterType == "" { - cdromAdapterType = templateData.CDROMType - } else if cdromAdapterType == diskAdapterType { - templateData.CDROMType_PrimarySecondary = "1" - } else { - templateData.CDROMType_PrimarySecondary = "0" - } - - switch cdromAdapterType { - case "ide": - templateData.CDROMType = "ide" - case "sata": - templateData.SATA_Present = "TRUE" - templateData.CDROMType = "sata" - case "scsi": - templateData.SCSI_Present = "TRUE" - templateData.CDROMType = "scsi" - default: - err := fmt.Errorf("Error processing VMX template: %s", cdromAdapterType) - state.Put("error", err) - ui.Error(err.Error()) - return multistep.ActionHalt - } + templateData.DiskAndCDConfigData = vmwcommon.DefaultDiskAndCDROMTypes(config.DiskAdapterType, config.CdromAdapterType) /// Now that we figured out the CDROM device to add, store it /// to the list of temporary build devices in our statebag diff --git a/builder/vmware/vmx/builder.go b/builder/vmware/vmx/builder.go index 4c303d8bb..9b283b9d0 100644 --- a/builder/vmware/vmx/builder.go +++ b/builder/vmware/vmx/builder.go @@ -73,6 +73,10 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack Directories: b.config.FloppyConfig.FloppyDirectories, Label: b.config.FloppyConfig.FloppyLabel, }, + &common.StepCreateCD{ + Files: b.config.CDConfig.CDFiles, + Label: b.config.CDConfig.CDLabel, + }, &vmwcommon.StepRemoteUpload{ Key: "floppy_path", Message: "Uploading Floppy to remote machine...", @@ -95,9 +99,11 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack Linked: b.config.Linked, }, &vmwcommon.StepConfigureVMX{ - CustomData: b.config.VMXData, - VMName: b.config.VMName, - DisplayName: b.config.VMXDisplayName, + CustomData: b.config.VMXData, + VMName: b.config.VMName, + DisplayName: b.config.VMXDisplayName, + DiskAdapterType: b.config.DiskAdapterType, + CDROMAdapterType: "", }, &vmwcommon.StepSuppressMessages{}, &vmwcommon.StepHTTPIPDiscover{}, @@ -111,7 +117,7 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack RemoteType: b.config.RemoteType, }, &vmwcommon.StepConfigureVNC{ - Enabled: !b.config.DisableVNC, + Enabled: !b.config.DisableVNC && !b.config.VNCOverWebsocket, VNCBindAddress: b.config.VNCBindAddress, VNCPortMin: b.config.VNCPortMin, VNCPortMax: b.config.VNCPortMax, @@ -126,13 +132,16 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack DurationBeforeStop: 5 * time.Second, Headless: b.config.Headless, }, - &vmwcommon.StepTypeBootCommand{ - BootWait: b.config.BootWait, - VNCEnabled: !b.config.DisableVNC, - BootCommand: b.config.FlatBootCommand(), - VMName: b.config.VMName, - Ctx: b.config.ctx, - KeyInterval: b.config.VNCConfig.BootKeyInterval, + &vmwcommon.StepVNCConnect{ + VNCEnabled: !b.config.DisableVNC, + VNCOverWebsocket: b.config.VNCOverWebsocket, + InsecureConnection: b.config.InsecureConnection, + DriverConfig: &b.config.DriverConfig, + }, + &vmwcommon.StepVNCBootCommand{ + Config: b.config.VNCConfig, + VMName: b.config.VMName, + Ctx: b.config.ctx, }, &communicator.StepConnect{ Config: &b.config.SSHConfig.Comm, @@ -203,5 +212,3 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack return vmwcommon.NewArtifact(b.config.RemoteType, b.config.Format, exportOutputPath, b.config.VMName, b.config.SkipExport, b.config.KeepRegistered, state) } - -// Cancel. diff --git a/builder/vmware/vmx/config.go b/builder/vmware/vmx/config.go index fc32099e1..e7c34616e 100644 --- a/builder/vmware/vmx/config.go +++ b/builder/vmware/vmx/config.go @@ -22,6 +22,7 @@ type Config struct { common.HTTPConfig `mapstructure:",squash"` common.FloppyConfig `mapstructure:",squash"` bootcommand.VNCConfig `mapstructure:",squash"` + common.CDConfig `mapstructure:",squash"` vmwcommon.DriverConfig `mapstructure:",squash"` vmwcommon.OutputConfig `mapstructure:",squash"` vmwcommon.RunConfig `mapstructure:",squash"` @@ -77,17 +78,22 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { "packer-%s-%d", c.PackerBuildName, interpolate.InitTime.Unix()) } - // Prepare the errors + // Accumulate any errors and warnings + var warnings []string var errs *packer.MultiError + + runConfigWarnings, runConfigErrs := c.RunConfig.Prepare(&c.ctx, &c.DriverConfig) + warnings = append(warnings, runConfigWarnings...) + errs = packer.MultiErrorAppend(errs, runConfigErrs...) errs = packer.MultiErrorAppend(errs, c.DriverConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.HTTPConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.OutputConfig.Prepare(&c.ctx, &c.PackerConfig)...) - errs = packer.MultiErrorAppend(errs, c.RunConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.ShutdownConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.SSHConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.ToolsConfig.Prepare(&c.ctx)...) - errs = packer.MultiErrorAppend(errs, c.VMXConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.FloppyConfig.Prepare(&c.ctx)...) + errs = packer.MultiErrorAppend(errs, c.CDConfig.Prepare(&c.ctx)...) + errs = packer.MultiErrorAppend(errs, c.VNCConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.VNCConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.ExportConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.DiskConfig.Prepare(&c.ctx)...) @@ -101,16 +107,10 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { fmt.Errorf("source_path is invalid: %s", err)) } } - } else { - // Remote configuration validation - if c.RemoteHost == "" { - errs = packer.MultiErrorAppend(errs, - fmt.Errorf("remote_host must be specified")) - } - - if c.RemoteType != "esx5" { - errs = packer.MultiErrorAppend(errs, - fmt.Errorf("Only 'esx5' value is accepted for remote_type")) + if c.Headless && c.DisableVNC { + warnings = append(warnings, + "Headless mode uses VNC to retrieve output. Since VNC has been disabled,\n"+ + "you won't be able to see any output.") } } @@ -143,20 +143,12 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { errs = packer.MultiErrorAppend(errs, err) } - // Warnings - var warnings []string if c.ShutdownCommand == "" { warnings = append(warnings, "A shutdown_command was not specified. Without a shutdown command, Packer\n"+ "will forcibly halt the virtual machine, which may result in data loss.") } - if c.Headless && c.DisableVNC { - warnings = append(warnings, - "Headless mode uses VNC to retrieve output. Since VNC has been disabled,\n"+ - "you won't be able to see any output.") - } - // Check for any errors. if errs != nil && len(errs.Errors) > 0 { return warnings, errs diff --git a/builder/vmware/vmx/config.hcl2spec.go b/builder/vmware/vmx/config.hcl2spec.go index c507035a6..bc4ce8802 100644 --- a/builder/vmware/vmx/config.hcl2spec.go +++ b/builder/vmware/vmx/config.hcl2spec.go @@ -20,6 +20,7 @@ type FlatConfig struct { HTTPPortMin *int `mapstructure:"http_port_min" cty:"http_port_min" hcl:"http_port_min"` HTTPPortMax *int `mapstructure:"http_port_max" cty:"http_port_max" hcl:"http_port_max"` HTTPAddress *string `mapstructure:"http_bind_address" cty:"http_bind_address" hcl:"http_bind_address"` + HTTPInterface *string `mapstructure:"http_interface" undocumented:"true" cty:"http_interface" hcl:"http_interface"` FloppyFiles []string `mapstructure:"floppy_files" cty:"floppy_files" hcl:"floppy_files"` FloppyDirectories []string `mapstructure:"floppy_dirs" cty:"floppy_dirs" hcl:"floppy_dirs"` FloppyLabel *string `mapstructure:"floppy_label" cty:"floppy_label" hcl:"floppy_label"` @@ -28,6 +29,8 @@ type FlatConfig struct { BootCommand []string `mapstructure:"boot_command" cty:"boot_command" hcl:"boot_command"` DisableVNC *bool `mapstructure:"disable_vnc" cty:"disable_vnc" hcl:"disable_vnc"` BootKeyInterval *string `mapstructure:"boot_key_interval" cty:"boot_key_interval" hcl:"boot_key_interval"` + CDFiles []string `mapstructure:"cd_files" cty:"cd_files" hcl:"cd_files"` + CDLabel *string `mapstructure:"cd_label" cty:"cd_label" hcl:"cd_label"` CleanUpRemoteCache *bool `mapstructure:"cleanup_remote_cache" required:"false" cty:"cleanup_remote_cache" hcl:"cleanup_remote_cache"` FusionAppPath *string `mapstructure:"fusion_app_path" required:"false" cty:"fusion_app_path" hcl:"fusion_app_path"` RemoteType *string `mapstructure:"remote_type" required:"false" cty:"remote_type" hcl:"remote_type"` @@ -47,6 +50,8 @@ type FlatConfig struct { VNCPortMin *int `mapstructure:"vnc_port_min" required:"false" cty:"vnc_port_min" hcl:"vnc_port_min"` VNCPortMax *int `mapstructure:"vnc_port_max" cty:"vnc_port_max" hcl:"vnc_port_max"` VNCDisablePassword *bool `mapstructure:"vnc_disable_password" required:"false" cty:"vnc_disable_password" hcl:"vnc_disable_password"` + VNCOverWebsocket *bool `mapstructure:"vnc_over_websocket" required:"false" cty:"vnc_over_websocket" hcl:"vnc_over_websocket"` + InsecureConnection *bool `mapstructure:"insecure_connection" required:"false" cty:"insecure_connection" hcl:"insecure_connection"` ShutdownCommand *string `mapstructure:"shutdown_command" required:"false" cty:"shutdown_command" hcl:"shutdown_command"` ShutdownTimeout *string `mapstructure:"shutdown_timeout" required:"false" cty:"shutdown_timeout" hcl:"shutdown_timeout"` Type *string `mapstructure:"communicator" cty:"communicator" hcl:"communicator"` @@ -99,6 +104,7 @@ type FlatConfig struct { SSHSkipRequestPty *bool `mapstructure:"ssh_skip_request_pty" cty:"ssh_skip_request_pty" hcl:"ssh_skip_request_pty"` ToolsUploadFlavor *string `mapstructure:"tools_upload_flavor" required:"false" cty:"tools_upload_flavor" hcl:"tools_upload_flavor"` ToolsUploadPath *string `mapstructure:"tools_upload_path" required:"false" cty:"tools_upload_path" hcl:"tools_upload_path"` + ToolsSourcePath *string `mapstructure:"tools_source_path" required:"false" cty:"tools_source_path" hcl:"tools_source_path"` VMXData map[string]string `mapstructure:"vmx_data" required:"false" cty:"vmx_data" hcl:"vmx_data"` VMXDataPost map[string]string `mapstructure:"vmx_data_post" required:"false" cty:"vmx_data_post" hcl:"vmx_data_post"` VMXRemoveEthernet *bool `mapstructure:"vmx_remove_ethernet_interfaces" required:"false" cty:"vmx_remove_ethernet_interfaces" hcl:"vmx_remove_ethernet_interfaces"` @@ -140,6 +146,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "http_port_min": &hcldec.AttrSpec{Name: "http_port_min", Type: cty.Number, Required: false}, "http_port_max": &hcldec.AttrSpec{Name: "http_port_max", Type: cty.Number, Required: false}, "http_bind_address": &hcldec.AttrSpec{Name: "http_bind_address", Type: cty.String, Required: false}, + "http_interface": &hcldec.AttrSpec{Name: "http_interface", Type: cty.String, Required: false}, "floppy_files": &hcldec.AttrSpec{Name: "floppy_files", Type: cty.List(cty.String), Required: false}, "floppy_dirs": &hcldec.AttrSpec{Name: "floppy_dirs", Type: cty.List(cty.String), Required: false}, "floppy_label": &hcldec.AttrSpec{Name: "floppy_label", Type: cty.String, Required: false}, @@ -148,6 +155,8 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "boot_command": &hcldec.AttrSpec{Name: "boot_command", Type: cty.List(cty.String), Required: false}, "disable_vnc": &hcldec.AttrSpec{Name: "disable_vnc", Type: cty.Bool, Required: false}, "boot_key_interval": &hcldec.AttrSpec{Name: "boot_key_interval", Type: cty.String, Required: false}, + "cd_files": &hcldec.AttrSpec{Name: "cd_files", Type: cty.List(cty.String), Required: false}, + "cd_label": &hcldec.AttrSpec{Name: "cd_label", Type: cty.String, Required: false}, "cleanup_remote_cache": &hcldec.AttrSpec{Name: "cleanup_remote_cache", Type: cty.Bool, Required: false}, "fusion_app_path": &hcldec.AttrSpec{Name: "fusion_app_path", Type: cty.String, Required: false}, "remote_type": &hcldec.AttrSpec{Name: "remote_type", Type: cty.String, Required: false}, @@ -167,6 +176,8 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "vnc_port_min": &hcldec.AttrSpec{Name: "vnc_port_min", Type: cty.Number, Required: false}, "vnc_port_max": &hcldec.AttrSpec{Name: "vnc_port_max", Type: cty.Number, Required: false}, "vnc_disable_password": &hcldec.AttrSpec{Name: "vnc_disable_password", Type: cty.Bool, Required: false}, + "vnc_over_websocket": &hcldec.AttrSpec{Name: "vnc_over_websocket", Type: cty.Bool, Required: false}, + "insecure_connection": &hcldec.AttrSpec{Name: "insecure_connection", Type: cty.Bool, Required: false}, "shutdown_command": &hcldec.AttrSpec{Name: "shutdown_command", Type: cty.String, Required: false}, "shutdown_timeout": &hcldec.AttrSpec{Name: "shutdown_timeout", Type: cty.String, Required: false}, "communicator": &hcldec.AttrSpec{Name: "communicator", Type: cty.String, Required: false}, @@ -219,6 +230,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "ssh_skip_request_pty": &hcldec.AttrSpec{Name: "ssh_skip_request_pty", Type: cty.Bool, Required: false}, "tools_upload_flavor": &hcldec.AttrSpec{Name: "tools_upload_flavor", Type: cty.String, Required: false}, "tools_upload_path": &hcldec.AttrSpec{Name: "tools_upload_path", Type: cty.String, Required: false}, + "tools_source_path": &hcldec.AttrSpec{Name: "tools_source_path", Type: cty.String, Required: false}, "vmx_data": &hcldec.AttrSpec{Name: "vmx_data", Type: cty.Map(cty.String), Required: false}, "vmx_data_post": &hcldec.AttrSpec{Name: "vmx_data_post", Type: cty.Map(cty.String), Required: false}, "vmx_remove_ethernet_interfaces": &hcldec.AttrSpec{Name: "vmx_remove_ethernet_interfaces", Type: cty.Bool, Required: false}, diff --git a/builder/vsphere/clone/builder.go b/builder/vsphere/clone/builder.go index 100670754..92d574187 100644 --- a/builder/vsphere/clone/builder.go +++ b/builder/vsphere/clone/builder.go @@ -41,6 +41,15 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack &common.StepConnect{ Config: &b.config.ConnectConfig, }, + &packerCommon.StepCreateCD{ + Files: b.config.CDConfig.CDFiles, + Label: b.config.CDConfig.CDLabel, + }, + &common.StepRemoteUpload{ + Datastore: b.config.Datastore, + Host: b.config.Host, + SetHostForDatastoreUploads: b.config.SetHostForDatastoreUploads, + }, &StepCloneVM{ Config: &b.config.CloneConfig, Location: &b.config.LocationConfig, @@ -49,6 +58,9 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack &common.StepConfigureHardware{ Config: &b.config.HardwareConfig, }, + &common.StepAddCDRom{ + Config: &b.config.CDRomConfig, + }, &common.StepConfigParams{ Config: &b.config.ConfigParamsConfig, }, @@ -62,6 +74,17 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack if b.config.Comm.Type != "none" { steps = append(steps, + &packerCommon.StepCreateFloppy{ + Files: b.config.FloppyFiles, + Directories: b.config.FloppyDirectories, + Label: b.config.FloppyLabel, + }, + &common.StepAddFloppy{ + Config: &b.config.FloppyConfig, + Datastore: b.config.Datastore, + Host: b.config.Host, + SetHostForDatastoreUploads: b.config.SetHostForDatastoreUploads, + }, &common.StepHTTPIPDiscover{ HTTPIP: b.config.BootConfig.HTTPIP, Network: b.config.WaitIpConfig.GetIPNet(), @@ -98,10 +121,17 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack &common.StepShutdown{ Config: &b.config.ShutdownConfig, }, + &common.StepRemoveFloppy{ + Datastore: b.config.Datastore, + Host: b.config.Host, + }, ) } steps = append(steps, + &common.StepRemoveCDRom{ + Config: &b.config.RemoveCDRomConfig, + }, &common.StepCreateSnapshot{ CreateSnapshot: b.config.CreateSnapshot, }, diff --git a/builder/vsphere/clone/config.go b/builder/vsphere/clone/config.go index 8d182bf25..c2d9c2e8a 100644 --- a/builder/vsphere/clone/config.go +++ b/builder/vsphere/clone/config.go @@ -15,6 +15,7 @@ import ( type Config struct { packerCommon.PackerConfig `mapstructure:",squash"` packerCommon.HTTPConfig `mapstructure:",squash"` + packerCommon.CDConfig `mapstructure:",squash"` common.ConnectConfig `mapstructure:",squash"` CloneConfig `mapstructure:",squash"` @@ -22,11 +23,14 @@ type Config struct { common.HardwareConfig `mapstructure:",squash"` common.ConfigParamsConfig `mapstructure:",squash"` - common.RunConfig `mapstructure:",squash"` - common.BootConfig `mapstructure:",squash"` - common.WaitIpConfig `mapstructure:",squash"` - Comm communicator.Config `mapstructure:",squash"` - common.ShutdownConfig `mapstructure:",squash"` + common.CDRomConfig `mapstructure:",squash"` + common.RemoveCDRomConfig `mapstructure:",squash"` + common.FloppyConfig `mapstructure:",squash"` + common.RunConfig `mapstructure:",squash"` + common.BootConfig `mapstructure:",squash"` + common.WaitIpConfig `mapstructure:",squash"` + Comm communicator.Config `mapstructure:",squash"` + common.ShutdownConfig `mapstructure:",squash"` // Create a snapshot when set to `true`, so the VM can be used as a base // for linked clones. Defaults to `false`. @@ -67,6 +71,8 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { errs = packer.MultiErrorAppend(errs, c.HardwareConfig.Prepare()...) errs = packer.MultiErrorAppend(errs, c.HTTPConfig.Prepare(&c.ctx)...) + errs = packer.MultiErrorAppend(errs, c.CDRomConfig.Prepare()...) + errs = packer.MultiErrorAppend(errs, c.CDConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.BootConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.WaitIpConfig.Prepare()...) errs = packer.MultiErrorAppend(errs, c.Comm.Prepare(&c.ctx)...) diff --git a/builder/vsphere/clone/config.hcl2spec.go b/builder/vsphere/clone/config.hcl2spec.go index 06f7c5c60..7db101c50 100644 --- a/builder/vsphere/clone/config.hcl2spec.go +++ b/builder/vsphere/clone/config.hcl2spec.go @@ -21,6 +21,9 @@ type FlatConfig struct { HTTPPortMin *int `mapstructure:"http_port_min" cty:"http_port_min" hcl:"http_port_min"` HTTPPortMax *int `mapstructure:"http_port_max" cty:"http_port_max" hcl:"http_port_max"` HTTPAddress *string `mapstructure:"http_bind_address" cty:"http_bind_address" hcl:"http_bind_address"` + HTTPInterface *string `mapstructure:"http_interface" undocumented:"true" cty:"http_interface" hcl:"http_interface"` + CDFiles []string `mapstructure:"cd_files" cty:"cd_files" hcl:"cd_files"` + CDLabel *string `mapstructure:"cd_label" cty:"cd_label" hcl:"cd_label"` VCenterServer *string `mapstructure:"vcenter_server" cty:"vcenter_server" hcl:"vcenter_server"` Username *string `mapstructure:"username" cty:"username" hcl:"username"` Password *string `mapstructure:"password" cty:"password" hcl:"password"` @@ -30,6 +33,7 @@ type FlatConfig struct { DiskSize *int64 `mapstructure:"disk_size" cty:"disk_size" hcl:"disk_size"` LinkedClone *bool `mapstructure:"linked_clone" cty:"linked_clone" hcl:"linked_clone"` Network *string `mapstructure:"network" cty:"network" hcl:"network"` + MacAddress *string `mapstructure:"mac_address" cty:"mac_address" hcl:"mac_address"` Notes *string `mapstructure:"notes" cty:"notes" hcl:"notes"` VAppConfig *FlatvAppConfig `mapstructure:"vapp" cty:"vapp" hcl:"vapp"` VMName *string `mapstructure:"vm_name" cty:"vm_name" hcl:"vm_name"` @@ -56,6 +60,13 @@ type FlatConfig struct { ConfigParams map[string]string `mapstructure:"configuration_parameters" cty:"configuration_parameters" hcl:"configuration_parameters"` ToolsSyncTime *bool `mapstructure:"tools_sync_time" cty:"tools_sync_time" hcl:"tools_sync_time"` ToolsUpgradePolicy *bool `mapstructure:"tools_upgrade_policy" cty:"tools_upgrade_policy" hcl:"tools_upgrade_policy"` + CdromType *string `mapstructure:"cdrom_type" cty:"cdrom_type" hcl:"cdrom_type"` + ISOPaths []string `mapstructure:"iso_paths" cty:"iso_paths" hcl:"iso_paths"` + RemoveCdrom *bool `mapstructure:"remove_cdrom" cty:"remove_cdrom" hcl:"remove_cdrom"` + FloppyIMGPath *string `mapstructure:"floppy_img_path" cty:"floppy_img_path" hcl:"floppy_img_path"` + FloppyFiles []string `mapstructure:"floppy_files" cty:"floppy_files" hcl:"floppy_files"` + FloppyDirectories []string `mapstructure:"floppy_dirs" cty:"floppy_dirs" hcl:"floppy_dirs"` + FloppyLabel *string `mapstructure:"floppy_label" cty:"floppy_label" hcl:"floppy_label"` BootOrder *string `mapstructure:"boot_order" cty:"boot_order" hcl:"boot_order"` BootGroupInterval *string `mapstructure:"boot_keygroup_interval" cty:"boot_keygroup_interval" hcl:"boot_keygroup_interval"` BootWait *string `mapstructure:"boot_wait" cty:"boot_wait" hcl:"boot_wait"` @@ -144,6 +155,9 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "http_port_min": &hcldec.AttrSpec{Name: "http_port_min", Type: cty.Number, Required: false}, "http_port_max": &hcldec.AttrSpec{Name: "http_port_max", Type: cty.Number, Required: false}, "http_bind_address": &hcldec.AttrSpec{Name: "http_bind_address", Type: cty.String, Required: false}, + "http_interface": &hcldec.AttrSpec{Name: "http_interface", Type: cty.String, Required: false}, + "cd_files": &hcldec.AttrSpec{Name: "cd_files", Type: cty.List(cty.String), Required: false}, + "cd_label": &hcldec.AttrSpec{Name: "cd_label", Type: cty.String, Required: false}, "vcenter_server": &hcldec.AttrSpec{Name: "vcenter_server", Type: cty.String, Required: false}, "username": &hcldec.AttrSpec{Name: "username", Type: cty.String, Required: false}, "password": &hcldec.AttrSpec{Name: "password", Type: cty.String, Required: false}, @@ -153,6 +167,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "disk_size": &hcldec.AttrSpec{Name: "disk_size", Type: cty.Number, Required: false}, "linked_clone": &hcldec.AttrSpec{Name: "linked_clone", Type: cty.Bool, Required: false}, "network": &hcldec.AttrSpec{Name: "network", Type: cty.String, Required: false}, + "mac_address": &hcldec.AttrSpec{Name: "mac_address", Type: cty.String, Required: false}, "notes": &hcldec.AttrSpec{Name: "notes", Type: cty.String, Required: false}, "vapp": &hcldec.BlockSpec{TypeName: "vapp", Nested: hcldec.ObjectSpec((*FlatvAppConfig)(nil).HCL2Spec())}, "vm_name": &hcldec.AttrSpec{Name: "vm_name", Type: cty.String, Required: false}, @@ -179,6 +194,13 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "configuration_parameters": &hcldec.AttrSpec{Name: "configuration_parameters", Type: cty.Map(cty.String), Required: false}, "tools_sync_time": &hcldec.AttrSpec{Name: "tools_sync_time", Type: cty.Bool, Required: false}, "tools_upgrade_policy": &hcldec.AttrSpec{Name: "tools_upgrade_policy", Type: cty.Bool, Required: false}, + "cdrom_type": &hcldec.AttrSpec{Name: "cdrom_type", Type: cty.String, Required: false}, + "iso_paths": &hcldec.AttrSpec{Name: "iso_paths", Type: cty.List(cty.String), Required: false}, + "remove_cdrom": &hcldec.AttrSpec{Name: "remove_cdrom", Type: cty.Bool, Required: false}, + "floppy_img_path": &hcldec.AttrSpec{Name: "floppy_img_path", Type: cty.String, Required: false}, + "floppy_files": &hcldec.AttrSpec{Name: "floppy_files", Type: cty.List(cty.String), Required: false}, + "floppy_dirs": &hcldec.AttrSpec{Name: "floppy_dirs", Type: cty.List(cty.String), Required: false}, + "floppy_label": &hcldec.AttrSpec{Name: "floppy_label", Type: cty.String, Required: false}, "boot_order": &hcldec.AttrSpec{Name: "boot_order", Type: cty.String, Required: false}, "boot_keygroup_interval": &hcldec.AttrSpec{Name: "boot_keygroup_interval", Type: cty.String, Required: false}, "boot_wait": &hcldec.AttrSpec{Name: "boot_wait", Type: cty.String, Required: false}, diff --git a/builder/vsphere/clone/step_clone.go b/builder/vsphere/clone/step_clone.go index ec55a3ecd..18ba50a30 100644 --- a/builder/vsphere/clone/step_clone.go +++ b/builder/vsphere/clone/step_clone.go @@ -37,6 +37,8 @@ type CloneConfig struct { // available network. If the network is inside a network folder in vCenter, // you need to provide the full path to the network. Network string `mapstructure:"network"` + // Sets a custom Mac Address to the network adapter. If set, the [network](#network) must be also specified. + MacAddress string `mapstructure:"mac_address"` // VM notes. Notes string `mapstructure:"notes"` // Set the vApp Options to a virtual machine. @@ -56,6 +58,10 @@ func (c *CloneConfig) Prepare() []error { errs = append(errs, fmt.Errorf("'linked_clone' and 'disk_size' cannot be used together")) } + if c.MacAddress != "" && c.Network == "" { + errs = append(errs, fmt.Errorf("'network' is required when 'mac_address' is specified")) + } + return errs } @@ -92,6 +98,7 @@ func (s *StepCloneVM) Run(ctx context.Context, state multistep.StateBag) multist Datastore: s.Location.Datastore, LinkedClone: s.Config.LinkedClone, Network: s.Config.Network, + MacAddress: s.Config.MacAddress, Annotation: s.Config.Notes, VAppProperties: s.Config.VAppConfig.Properties, }) diff --git a/builder/vsphere/clone/step_clone.hcl2spec.go b/builder/vsphere/clone/step_clone.hcl2spec.go index a9f670f94..ad55ebfa8 100644 --- a/builder/vsphere/clone/step_clone.hcl2spec.go +++ b/builder/vsphere/clone/step_clone.hcl2spec.go @@ -13,6 +13,7 @@ type FlatCloneConfig struct { DiskSize *int64 `mapstructure:"disk_size" cty:"disk_size" hcl:"disk_size"` LinkedClone *bool `mapstructure:"linked_clone" cty:"linked_clone" hcl:"linked_clone"` Network *string `mapstructure:"network" cty:"network" hcl:"network"` + MacAddress *string `mapstructure:"mac_address" cty:"mac_address" hcl:"mac_address"` Notes *string `mapstructure:"notes" cty:"notes" hcl:"notes"` VAppConfig *FlatvAppConfig `mapstructure:"vapp" cty:"vapp" hcl:"vapp"` } @@ -33,6 +34,7 @@ func (*FlatCloneConfig) HCL2Spec() map[string]hcldec.Spec { "disk_size": &hcldec.AttrSpec{Name: "disk_size", Type: cty.Number, Required: false}, "linked_clone": &hcldec.AttrSpec{Name: "linked_clone", Type: cty.Bool, Required: false}, "network": &hcldec.AttrSpec{Name: "network", Type: cty.String, Required: false}, + "mac_address": &hcldec.AttrSpec{Name: "mac_address", Type: cty.String, Required: false}, "notes": &hcldec.AttrSpec{Name: "notes", Type: cty.String, Required: false}, "vapp": &hcldec.BlockSpec{TypeName: "vapp", Nested: hcldec.ObjectSpec((*FlatvAppConfig)(nil).HCL2Spec())}, } diff --git a/builder/vsphere/iso/step_add_cdrom.go b/builder/vsphere/common/step_add_cdrom.go similarity index 90% rename from builder/vsphere/iso/step_add_cdrom.go rename to builder/vsphere/common/step_add_cdrom.go index 6a6c22c1f..d6a6f62b8 100644 --- a/builder/vsphere/iso/step_add_cdrom.go +++ b/builder/vsphere/common/step_add_cdrom.go @@ -1,7 +1,7 @@ //go:generate struct-markdown //go:generate mapstructure-to-hcl2 -type CDRomConfig -package iso +package common import ( "context" @@ -42,7 +42,7 @@ func (c *CDRomConfig) Prepare() []error { func (s *StepAddCDRom) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { ui := state.Get("ui").(packer.Ui) - vm := state.Get("vm").(*driver.VirtualMachineDriver) + vm := state.Get("vm").(driver.VirtualMachine) if s.Config.CdromType == "sata" { if _, err := vm.FindSATAController(); err == driver.ErrNoSataController { @@ -62,6 +62,11 @@ func (s *StepAddCDRom) Run(_ context.Context, state multistep.StateBag) multiste } } + // Add our custom CD, if it exists + if cd_path, _ := state.Get("cd_path").(string); cd_path != "" { + s.Config.ISOPaths = append(s.Config.ISOPaths, cd_path) + } + if len(s.Config.ISOPaths) > 0 { for _, path := range s.Config.ISOPaths { if err := vm.AddCdrom(s.Config.CdromType, path); err != nil { diff --git a/builder/vsphere/iso/step_add_cdrom.hcl2spec.go b/builder/vsphere/common/step_add_cdrom.hcl2spec.go similarity index 98% rename from builder/vsphere/iso/step_add_cdrom.hcl2spec.go rename to builder/vsphere/common/step_add_cdrom.hcl2spec.go index 572236571..6890fe091 100644 --- a/builder/vsphere/iso/step_add_cdrom.hcl2spec.go +++ b/builder/vsphere/common/step_add_cdrom.hcl2spec.go @@ -1,5 +1,5 @@ // Code generated by "mapstructure-to-hcl2 -type CDRomConfig"; DO NOT EDIT. -package iso +package common import ( "github.com/hashicorp/hcl/v2/hcldec" diff --git a/builder/vsphere/common/step_add_cdrom_test.go b/builder/vsphere/common/step_add_cdrom_test.go new file mode 100644 index 000000000..e1116660c --- /dev/null +++ b/builder/vsphere/common/step_add_cdrom_test.go @@ -0,0 +1,235 @@ +package common + +import ( + "context" + "fmt" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/hashicorp/packer/builder/vsphere/driver" + "github.com/hashicorp/packer/helper/multistep" +) + +func TestCDRomConfig_Prepare(t *testing.T) { + // Data validation + tc := []struct { + name string + config *CDRomConfig + fail bool + expectedErrMsg string + }{ + { + name: "Should not fail for empty config", + config: new(CDRomConfig), + fail: false, + expectedErrMsg: "", + }, + { + name: "Valid cdroom type ide", + config: &CDRomConfig{CdromType: "ide"}, + fail: false, + expectedErrMsg: "", + }, + { + name: "Valid cdroom type sata", + config: &CDRomConfig{CdromType: "ide"}, + fail: false, + expectedErrMsg: "", + }, + { + name: "Invalid cdroom type", + config: &CDRomConfig{CdromType: "invalid"}, + fail: true, + expectedErrMsg: "'cdrom_type' must be 'ide' or 'sata'", + }, + } + + for _, c := range tc { + errs := c.config.Prepare() + if c.fail { + if len(errs) == 0 { + t.Fatalf("Config preprare should fail") + } + if errs[0].Error() != c.expectedErrMsg { + t.Fatalf("Expected error message: %s but was '%s'", c.expectedErrMsg, errs[0].Error()) + } + } else { + if len(errs) != 0 { + t.Fatalf("Config preprare should not fail") + } + } + } +} + +func TestStepAddCDRom_Run(t *testing.T) { + tc := []struct { + name string + state *multistep.BasicStateBag + step *StepAddCDRom + vmMock *driver.VirtualMachineMock + expectedAction multistep.StepAction + expectedVmMock *driver.VirtualMachineMock + fail bool + errMessage string + }{ + { + name: "CDRom SATA type with all iso paths set", + state: cdAndIsoRemotePathStateBag(), + step: &StepAddCDRom{ + Config: &CDRomConfig{ + CdromType: "sata", + ISOPaths: []string{"iso/path"}, + }, + }, + vmMock: new(driver.VirtualMachineMock), + expectedAction: multistep.ActionContinue, + expectedVmMock: &driver.VirtualMachineMock{ + FindSATAControllerCalled: true, + AddCdromCalled: true, + AddCdromCalledTimes: 3, + AddCdromTypes: []string{"sata", "sata", "sata"}, + AddCdromPaths: []string{"remote/path", "iso/path", "cd/path"}, + }, + fail: false, + errMessage: "", + }, + { + name: "Add SATA Controller", + state: basicStateBag(nil), + step: &StepAddCDRom{ + Config: &CDRomConfig{ + CdromType: "sata", + }, + }, + vmMock: &driver.VirtualMachineMock{ + FindSATAControllerErr: driver.ErrNoSataController, + }, + expectedAction: multistep.ActionContinue, + expectedVmMock: &driver.VirtualMachineMock{ + FindSATAControllerCalled: true, + FindSATAControllerErr: driver.ErrNoSataController, + AddSATAControllerCalled: true, + }, + fail: false, + errMessage: "", + }, + { + name: "Fail to add SATA Controller", + state: basicStateBag(nil), + step: &StepAddCDRom{ + Config: &CDRomConfig{ + CdromType: "sata", + }, + }, + vmMock: &driver.VirtualMachineMock{ + FindSATAControllerErr: driver.ErrNoSataController, + AddSATAControllerErr: fmt.Errorf("AddSATAController error"), + }, + expectedAction: multistep.ActionHalt, + expectedVmMock: &driver.VirtualMachineMock{ + FindSATAControllerCalled: true, + AddSATAControllerCalled: true, + }, + fail: true, + errMessage: fmt.Sprintf("error adding SATA controller: %v", fmt.Errorf("AddSATAController error")), + }, + { + name: "IDE CDRom Type and Iso Path set", + state: basicStateBag(nil), + step: &StepAddCDRom{ + Config: &CDRomConfig{ + CdromType: "ide", + ISOPaths: []string{"iso/path"}, + }, + }, + vmMock: new(driver.VirtualMachineMock), + expectedAction: multistep.ActionContinue, + expectedVmMock: &driver.VirtualMachineMock{ + AddCdromCalled: true, + AddCdromCalledTimes: 1, + AddCdromTypes: []string{"ide"}, + AddCdromPaths: []string{"iso/path"}, + }, + fail: false, + errMessage: "", + }, + { + name: "Fail to add cdrom from ISOPaths", + state: basicStateBag(nil), + step: &StepAddCDRom{ + Config: &CDRomConfig{ + ISOPaths: []string{"iso/path"}, + }, + }, + vmMock: &driver.VirtualMachineMock{ + AddCdromErr: fmt.Errorf("AddCdrom error"), + }, + expectedAction: multistep.ActionHalt, + expectedVmMock: &driver.VirtualMachineMock{ + AddCdromCalled: true, + AddCdromCalledTimes: 1, + AddCdromTypes: []string{""}, + AddCdromPaths: []string{"iso/path"}, + }, + fail: true, + errMessage: fmt.Sprintf("error mounting an image 'iso/path': %v", fmt.Errorf("AddCdrom error")), + }, + { + name: "Fail to add cdrom from state iso_remote_path", + state: isoRemotePathStateBag(), + step: &StepAddCDRom{ + Config: new(CDRomConfig), + }, + vmMock: &driver.VirtualMachineMock{ + AddCdromErr: fmt.Errorf("AddCdrom error"), + }, + expectedAction: multistep.ActionHalt, + expectedVmMock: &driver.VirtualMachineMock{ + AddCdromCalled: true, + AddCdromCalledTimes: 1, + AddCdromTypes: []string{""}, + AddCdromPaths: []string{"remote/path"}, + }, + fail: true, + errMessage: fmt.Sprintf("error mounting an image 'remote/path': %v", fmt.Errorf("AddCdrom error")), + }, + } + + for _, c := range tc { + t.Run(c.name, func(t *testing.T) { + c.state.Put("vm", c.vmMock) + if action := c.step.Run(context.TODO(), c.state); action != c.expectedAction { + t.Fatalf("unexpected action %v", action) + } + err, ok := c.state.Get("error").(error) + if ok { + if err.Error() != c.errMessage { + t.Fatalf("unexpected error %s", err.Error()) + } + } else { + if c.fail { + t.Fatalf("expected to fail but it didn't") + } + } + + if diff := cmp.Diff(c.vmMock, c.expectedVmMock, + cmpopts.IgnoreInterfaces(struct{ error }{})); diff != "" { + t.Fatalf("unexpected VirtualMachine calls: %s", diff) + } + }) + } +} + +func cdAndIsoRemotePathStateBag() *multistep.BasicStateBag { + state := basicStateBag(nil) + state.Put("iso_remote_path", "remote/path") + state.Put("cd_path", "cd/path") + return state +} + +func isoRemotePathStateBag() *multistep.BasicStateBag { + state := basicStateBag(nil) + state.Put("iso_remote_path", "remote/path") + return state +} diff --git a/builder/vsphere/iso/step_add_floppy.go b/builder/vsphere/common/step_add_floppy.go similarity index 94% rename from builder/vsphere/iso/step_add_floppy.go rename to builder/vsphere/common/step_add_floppy.go index ee69a9c5c..213f08429 100644 --- a/builder/vsphere/iso/step_add_floppy.go +++ b/builder/vsphere/common/step_add_floppy.go @@ -1,7 +1,7 @@ //go:generate struct-markdown //go:generate mapstructure-to-hcl2 -type FloppyConfig -package iso +package common import ( "context" @@ -37,8 +37,8 @@ type StepAddFloppy struct { func (s *StepAddFloppy) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { ui := state.Get("ui").(packer.Ui) - vm := state.Get("vm").(*driver.VirtualMachineDriver) - d := state.Get("driver").(*driver.VCenterDriver) + vm := state.Get("vm").(driver.VirtualMachine) + d := state.Get("driver").(driver.Driver) if floppyPath, ok := state.GetOk("floppy_path"); ok { ui.Say("Uploading created floppy image") @@ -90,7 +90,7 @@ func (s *StepAddFloppy) Cleanup(state multistep.StateBag) { } ui := state.Get("ui").(packer.Ui) - d := state.Get("driver").(*driver.VCenterDriver) + d := state.Get("driver").(driver.Driver) if UploadedFloppyPath, ok := state.GetOk("uploaded_floppy_path"); ok { ui.Say("Deleting Floppy image ...") diff --git a/builder/vsphere/iso/step_add_floppy.hcl2spec.go b/builder/vsphere/common/step_add_floppy.hcl2spec.go similarity index 99% rename from builder/vsphere/iso/step_add_floppy.hcl2spec.go rename to builder/vsphere/common/step_add_floppy.hcl2spec.go index 23925eeac..6f4956d99 100644 --- a/builder/vsphere/iso/step_add_floppy.hcl2spec.go +++ b/builder/vsphere/common/step_add_floppy.hcl2spec.go @@ -1,5 +1,5 @@ // Code generated by "mapstructure-to-hcl2 -type FloppyConfig"; DO NOT EDIT. -package iso +package common import ( "github.com/hashicorp/hcl/v2/hcldec" diff --git a/builder/vsphere/common/step_add_floppy_test.go b/builder/vsphere/common/step_add_floppy_test.go new file mode 100644 index 000000000..52963526a --- /dev/null +++ b/builder/vsphere/common/step_add_floppy_test.go @@ -0,0 +1,453 @@ +package common + +import ( + "context" + "fmt" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/hashicorp/packer/builder/vsphere/driver" + "github.com/hashicorp/packer/helper/multistep" +) + +func TestStepAddFloppy_Run(t *testing.T) { + tc := []struct { + name string + floppyPath string + uploadedPath string + step *StepAddFloppy + expectedAction multistep.StepAction + vmMock *driver.VirtualMachineMock + expectedVmMock *driver.VirtualMachineMock + driverMock *driver.DriverMock + expectedDriverMock *driver.DriverMock + dsMock *driver.DatastoreMock + expectedDsMock *driver.DatastoreMock + fail bool + errMessage string + }{ + { + name: "Add floppy from state floppy path", + floppyPath: "floppy/path", + uploadedPath: "vm/dir/packer-tmp-created-floppy.flp", + step: &StepAddFloppy{ + Config: new(FloppyConfig), + Datastore: "datastore", + Host: "host", + SetHostForDatastoreUploads: true, + }, + expectedAction: multistep.ActionContinue, + vmMock: &driver.VirtualMachineMock{ + GetDirResponse: "vm/dir", + }, + expectedVmMock: &driver.VirtualMachineMock{ + GetDirResponse: "vm/dir", + GetDirCalled: true, + AddFloppyCalled: true, + AddFloppyImagePath: "resolved/path", + }, + driverMock: new(driver.DriverMock), + expectedDriverMock: &driver.DriverMock{ + FindDatastoreCalled: true, + FindDatastoreName: "datastore", + FindDatastoreHost: "host", + }, + dsMock: &driver.DatastoreMock{ + ResolvePathReturn: "resolved/path", + }, + expectedDsMock: &driver.DatastoreMock{ + UploadFileCalled: true, + UploadFileSrc: "floppy/path", + UploadFileDst: "vm/dir/packer-tmp-created-floppy.flp", + UploadFileHost: "host", + UploadFileSetHost: true, + ResolvePathCalled: true, + ResolvePathReturn: "resolved/path", + }, + fail: false, + }, + { + name: "State floppy path - find datastore fail", + floppyPath: "floppy/path", + step: &StepAddFloppy{ + Config: new(FloppyConfig), + Datastore: "datastore", + Host: "host", + SetHostForDatastoreUploads: true, + }, + expectedAction: multistep.ActionHalt, + vmMock: new(driver.VirtualMachineMock), + expectedVmMock: new(driver.VirtualMachineMock), + driverMock: &driver.DriverMock{ + FindDatastoreErr: fmt.Errorf("error finding datastore"), + }, + expectedDriverMock: &driver.DriverMock{ + FindDatastoreCalled: true, + FindDatastoreName: "datastore", + FindDatastoreHost: "host", + }, + dsMock: new(driver.DatastoreMock), + expectedDsMock: new(driver.DatastoreMock), + fail: true, + errMessage: "error finding datastore", + }, + { + name: "State floppy path - vm get dir fail", + floppyPath: "floppy/path", + step: &StepAddFloppy{ + Config: new(FloppyConfig), + Datastore: "datastore", + Host: "host", + SetHostForDatastoreUploads: true, + }, + expectedAction: multistep.ActionHalt, + vmMock: &driver.VirtualMachineMock{ + GetDirErr: fmt.Errorf("fail to get vm dir"), + }, + expectedVmMock: &driver.VirtualMachineMock{ + GetDirCalled: true, + }, + driverMock: new(driver.DriverMock), + expectedDriverMock: &driver.DriverMock{ + FindDatastoreCalled: true, + FindDatastoreName: "datastore", + FindDatastoreHost: "host", + }, + dsMock: new(driver.DatastoreMock), + expectedDsMock: new(driver.DatastoreMock), + fail: true, + errMessage: "fail to get vm dir", + }, + { + name: "State floppy path - datastore upload file fail", + floppyPath: "floppy/path", + step: &StepAddFloppy{ + Config: new(FloppyConfig), + Datastore: "datastore", + Host: "host", + SetHostForDatastoreUploads: true, + }, + expectedAction: multistep.ActionHalt, + vmMock: &driver.VirtualMachineMock{ + GetDirResponse: "vm/dir", + }, + expectedVmMock: &driver.VirtualMachineMock{ + GetDirResponse: "vm/dir", + GetDirCalled: true, + }, + driverMock: new(driver.DriverMock), + expectedDriverMock: &driver.DriverMock{ + FindDatastoreCalled: true, + FindDatastoreName: "datastore", + FindDatastoreHost: "host", + }, + dsMock: &driver.DatastoreMock{ + UploadFileErr: fmt.Errorf("failed to upload file"), + }, + expectedDsMock: &driver.DatastoreMock{ + UploadFileCalled: true, + UploadFileSrc: "floppy/path", + UploadFileDst: "vm/dir/packer-tmp-created-floppy.flp", + UploadFileHost: "host", + UploadFileSetHost: true, + }, + fail: true, + errMessage: "failed to upload file", + }, + { + name: "State floppy path - vm fail to add floppy", + floppyPath: "floppy/path", + uploadedPath: "vm/dir/packer-tmp-created-floppy.flp", + step: &StepAddFloppy{ + Config: new(FloppyConfig), + Datastore: "datastore", + Host: "host", + SetHostForDatastoreUploads: true, + }, + expectedAction: multistep.ActionHalt, + vmMock: &driver.VirtualMachineMock{ + GetDirResponse: "vm/dir", + AddFloppyErr: fmt.Errorf("failed to add floppy"), + }, + expectedVmMock: &driver.VirtualMachineMock{ + GetDirResponse: "vm/dir", + GetDirCalled: true, + AddFloppyCalled: true, + AddFloppyImagePath: "resolved/path", + }, + driverMock: new(driver.DriverMock), + expectedDriverMock: &driver.DriverMock{ + FindDatastoreCalled: true, + FindDatastoreName: "datastore", + FindDatastoreHost: "host", + }, + dsMock: &driver.DatastoreMock{ + ResolvePathReturn: "resolved/path", + }, + expectedDsMock: &driver.DatastoreMock{ + UploadFileCalled: true, + UploadFileSrc: "floppy/path", + UploadFileDst: "vm/dir/packer-tmp-created-floppy.flp", + UploadFileHost: "host", + UploadFileSetHost: true, + ResolvePathCalled: true, + ResolvePathReturn: "resolved/path", + }, + fail: true, + errMessage: "failed to add floppy", + }, + { + name: "Add floppy from FloppyIMGPath config", + step: &StepAddFloppy{ + Config: &FloppyConfig{ + FloppyIMGPath: "floppy/image/path", + }, + }, + expectedAction: multistep.ActionContinue, + vmMock: new(driver.VirtualMachineMock), + expectedVmMock: &driver.VirtualMachineMock{ + AddFloppyCalled: true, + AddFloppyImagePath: "floppy/image/path", + }, + driverMock: new(driver.DriverMock), + expectedDriverMock: new(driver.DriverMock), + dsMock: new(driver.DatastoreMock), + expectedDsMock: new(driver.DatastoreMock), + fail: false, + }, + { + name: "Fail to add floppy from FloppyIMGPath config", + step: &StepAddFloppy{ + Config: &FloppyConfig{ + FloppyIMGPath: "floppy/image/path", + }, + }, + expectedAction: multistep.ActionHalt, + vmMock: &driver.VirtualMachineMock{ + AddFloppyErr: fmt.Errorf("fail to add floppy"), + }, + expectedVmMock: &driver.VirtualMachineMock{ + AddFloppyCalled: true, + AddFloppyImagePath: "floppy/image/path", + }, + driverMock: new(driver.DriverMock), + expectedDriverMock: new(driver.DriverMock), + dsMock: new(driver.DatastoreMock), + expectedDsMock: new(driver.DatastoreMock), + fail: true, + errMessage: "fail to add floppy", + }, + } + + for _, c := range tc { + t.Run(c.name, func(t *testing.T) { + state := basicStateBag(nil) + state.Put("vm", c.vmMock) + c.driverMock.DatastoreMock = c.dsMock + state.Put("driver", c.driverMock) + + if c.floppyPath != "" { + state.Put("floppy_path", c.floppyPath) + } + + if action := c.step.Run(context.TODO(), state); action != c.expectedAction { + t.Fatalf("unexpected action %v", action) + } + err, ok := state.Get("error").(error) + if ok { + if err.Error() != c.errMessage { + t.Fatalf("unexpected error %s", err.Error()) + } + } else { + if c.fail { + t.Fatalf("expected to fail but it didn't") + } + } + + uploadedPath, _ := state.Get("uploaded_floppy_path").(string) + if uploadedPath != c.uploadedPath { + t.Fatalf("Unexpected uploaded path state %s", uploadedPath) + } + + if diff := cmp.Diff(c.vmMock, c.expectedVmMock, + cmpopts.IgnoreInterfaces(struct{ error }{})); diff != "" { + t.Fatalf("unexpected VirtualMachine calls: %s", diff) + } + c.expectedDriverMock.DatastoreMock = c.expectedDsMock + if diff := cmp.Diff(c.driverMock, c.expectedDriverMock, + cmpopts.IgnoreInterfaces(struct{ error }{})); diff != "" { + t.Fatalf("unexpected Driver calls: %s", diff) + } + if diff := cmp.Diff(c.dsMock, c.expectedDsMock, + cmpopts.IgnoreInterfaces(struct{ error }{})); diff != "" { + t.Fatalf("unexpected Datastore calls: %s", diff) + } + }) + } +} + +func TestStepAddFloppy_Cleanup(t *testing.T) { + tc := []struct { + name string + uploadedPath string + multistepState string + step *StepAddFloppy + driverMock *driver.DriverMock + expectedDriverMock *driver.DriverMock + dsMock *driver.DatastoreMock + expectedDsMock *driver.DatastoreMock + fail bool + errMessage string + }{ + { + name: "State cancelled clean up", + uploadedPath: "uploaded/path", + multistepState: multistep.StateCancelled, + step: &StepAddFloppy{ + Datastore: "datastore", + Host: "host", + }, + driverMock: new(driver.DriverMock), + expectedDriverMock: &driver.DriverMock{ + FindDatastoreCalled: true, + FindDatastoreName: "datastore", + FindDatastoreHost: "host", + }, + dsMock: &driver.DatastoreMock{ + DeleteCalled: true, + }, + expectedDsMock: &driver.DatastoreMock{ + DeleteCalled: true, + DeletePath: "uploaded/path", + }, + fail: false, + }, + { + name: "State halted clean up", + uploadedPath: "uploaded/path", + multistepState: multistep.StateHalted, + step: &StepAddFloppy{ + Datastore: "datastore", + Host: "host", + }, + driverMock: new(driver.DriverMock), + expectedDriverMock: &driver.DriverMock{ + FindDatastoreCalled: true, + FindDatastoreName: "datastore", + FindDatastoreHost: "host", + }, + dsMock: &driver.DatastoreMock{ + DeleteCalled: true, + }, + expectedDsMock: &driver.DatastoreMock{ + DeleteCalled: true, + DeletePath: "uploaded/path", + }, + fail: false, + }, + { + name: "Don't clean up without uploaded path", + multistepState: multistep.StateHalted, + step: new(StepAddFloppy), + driverMock: new(driver.DriverMock), + expectedDriverMock: new(driver.DriverMock), + dsMock: new(driver.DatastoreMock), + expectedDsMock: new(driver.DatastoreMock), + fail: false, + }, + { + name: "Don't clean up if state is not halted or canceled", + multistepState: "", + step: new(StepAddFloppy), + driverMock: new(driver.DriverMock), + expectedDriverMock: new(driver.DriverMock), + dsMock: new(driver.DatastoreMock), + expectedDsMock: new(driver.DatastoreMock), + fail: false, + }, + { + name: "Fail because datastore is not found", + uploadedPath: "uploaded/path", + multistepState: multistep.StateHalted, + step: &StepAddFloppy{ + Datastore: "datastore", + Host: "host", + }, + driverMock: &driver.DriverMock{ + FindDatastoreErr: fmt.Errorf("fail to find datastore"), + }, + expectedDriverMock: &driver.DriverMock{ + FindDatastoreCalled: true, + FindDatastoreName: "datastore", + FindDatastoreHost: "host", + }, + dsMock: new(driver.DatastoreMock), + expectedDsMock: new(driver.DatastoreMock), + fail: true, + errMessage: "fail to find datastore", + }, + { + name: "Fail to delete floppy", + uploadedPath: "uploaded/path", + multistepState: multistep.StateHalted, + step: &StepAddFloppy{ + Datastore: "datastore", + Host: "host", + }, + driverMock: new(driver.DriverMock), + expectedDriverMock: &driver.DriverMock{ + FindDatastoreCalled: true, + FindDatastoreName: "datastore", + FindDatastoreHost: "host", + }, + dsMock: &driver.DatastoreMock{ + DeleteCalled: true, + DeleteErr: fmt.Errorf("failed to delete floppy"), + }, + expectedDsMock: &driver.DatastoreMock{ + DeleteCalled: true, + DeletePath: "uploaded/path", + }, + fail: true, + errMessage: "failed to delete floppy", + }, + } + + for _, c := range tc { + t.Run(c.name, func(t *testing.T) { + state := basicStateBag(nil) + c.driverMock.DatastoreMock = c.dsMock + state.Put("driver", c.driverMock) + if c.uploadedPath != "" { + state.Put("uploaded_floppy_path", c.uploadedPath) + } + + if c.multistepState != "" { + state.Put(c.multistepState, true) + } + + c.step.Cleanup(state) + err, ok := state.Get("error").(error) + if ok { + if err.Error() != c.errMessage { + t.Fatalf("unexpected error %s", err.Error()) + } + } else { + if c.fail { + t.Fatalf("expected to fail but it didn't") + } + } + + c.expectedDriverMock.DatastoreMock = c.expectedDsMock + if diff := cmp.Diff(c.driverMock, c.expectedDriverMock, + cmpopts.IgnoreInterfaces(struct{ error }{})); diff != "" { + t.Fatalf("unexpected Driver calls: %s", diff) + } + if diff := cmp.Diff(c.dsMock, c.expectedDsMock, + cmpopts.IgnoreInterfaces(struct{ error }{})); diff != "" { + t.Fatalf("unexpected Datastore calls: %s", diff) + } + }) + } +} diff --git a/builder/vsphere/common/step_hardware.go b/builder/vsphere/common/step_hardware.go index 98e36d0d6..43f0f60d3 100644 --- a/builder/vsphere/common/step_hardware.go +++ b/builder/vsphere/common/step_hardware.go @@ -13,7 +13,7 @@ import ( ) type HardwareConfig struct { - // Number of CPU sockets. + // Number of CPU cores. CPUs int32 `mapstructure:"CPUs"` // Number of CPU cores per socket. CpuCores int32 `mapstructure:"cpu_cores"` diff --git a/builder/vsphere/common/step_remote_upload.go b/builder/vsphere/common/step_remote_upload.go new file mode 100644 index 000000000..bfabaeb67 --- /dev/null +++ b/builder/vsphere/common/step_remote_upload.go @@ -0,0 +1,99 @@ +package common + +import ( + "context" + "fmt" + "path/filepath" + + "github.com/hashicorp/packer/builder/vsphere/driver" + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" +) + +type StepRemoteUpload struct { + Datastore string + Host string + SetHostForDatastoreUploads bool +} + +func (s *StepRemoteUpload) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { + ui := state.Get("ui").(packer.Ui) + d := state.Get("driver").(driver.Driver) + + if path, ok := state.GetOk("iso_path"); ok { + // user-supplied boot iso + fullRemotePath, err := s.uploadFile(path.(string), d, ui) + if err != nil { + state.Put("error", err) + return multistep.ActionHalt + } + state.Put("iso_remote_path", fullRemotePath) + } + if cdPath, ok := state.GetOk("cd_path"); ok { + // Packer-created cd_files disk + fullRemotePath, err := s.uploadFile(cdPath.(string), d, ui) + if err != nil { + state.Put("error", err) + return multistep.ActionHalt + } + state.Put("cd_path", fullRemotePath) + } + + return multistep.ActionContinue +} + +func (s *StepRemoteUpload) uploadFile(path string, d driver.Driver, ui packer.Ui) (string, error) { + ds, err := d.FindDatastore(s.Datastore, s.Host) + if err != nil { + return "", fmt.Errorf("datastore doesn't exist: %v", err) + } + + filename := filepath.Base(path) + remotePath := fmt.Sprintf("packer_cache/%s", filename) + remoteDirectory := fmt.Sprintf("[%s] packer_cache/", ds.Name()) + fullRemotePath := fmt.Sprintf("%s/%s", remoteDirectory, filename) + + ui.Say(fmt.Sprintf("Uploading %s to %s", filename, remotePath)) + + if exists := ds.FileExists(remotePath); exists == true { + ui.Say(fmt.Sprintf("File %s already uploaded; continuing", filename)) + return fullRemotePath, nil + } + + if err := ds.MakeDirectory(remoteDirectory); err != nil { + return "", err + } + + if err := ds.UploadFile(path, remotePath, s.Host, s.SetHostForDatastoreUploads); err != nil { + return "", err + } + return fullRemotePath, nil +} + +func (s *StepRemoteUpload) Cleanup(state multistep.StateBag) { + _, cancelled := state.GetOk(multistep.StateCancelled) + _, halted := state.GetOk(multistep.StateHalted) + if !cancelled && !halted { + return + } + + ui := state.Get("ui").(packer.Ui) + d := state.Get("driver").(*driver.VCenterDriver) + + if UploadedCDPath, ok := state.GetOk("cd_path"); ok { + ui.Say("Deleting cd_files image from remote datastore ...") + + ds, err := d.FindDatastore(s.Datastore, s.Host) + if err != nil { + state.Put("error", err) + return + } + + err = ds.Delete(UploadedCDPath.(string)) + if err != nil { + state.Put("error", err) + return + } + + } +} diff --git a/builder/vsphere/iso/step_remote_upload_test.go b/builder/vsphere/common/step_remote_upload_test.go similarity index 96% rename from builder/vsphere/iso/step_remote_upload_test.go rename to builder/vsphere/common/step_remote_upload_test.go index 1e19f747c..85526017d 100644 --- a/builder/vsphere/iso/step_remote_upload_test.go +++ b/builder/vsphere/common/step_remote_upload_test.go @@ -1,4 +1,4 @@ -package iso +package common import ( "context" @@ -10,7 +10,7 @@ import ( ) func TestStepRemoteUpload_Run(t *testing.T) { - state := basicStateBag() + state := basicStateBag(nil) driverMock := driver.NewDriverMock() state.Put("driver", driverMock) state.Put("iso_path", "[datastore] iso/path") @@ -48,7 +48,7 @@ func TestStepRemoteUpload_Run(t *testing.T) { } func TestStepRemoteUpload_SkipRun(t *testing.T) { - state := basicStateBag() + state := basicStateBag(nil) driverMock := driver.NewDriverMock() state.Put("driver", driverMock) diff --git a/builder/vsphere/iso/step_remove_cdrom.go b/builder/vsphere/common/step_remove_cdrom.go similarity index 93% rename from builder/vsphere/iso/step_remove_cdrom.go rename to builder/vsphere/common/step_remove_cdrom.go index 9aba1b46a..00bd6dc94 100644 --- a/builder/vsphere/iso/step_remove_cdrom.go +++ b/builder/vsphere/common/step_remove_cdrom.go @@ -1,7 +1,7 @@ //go:generate struct-markdown //go:generate mapstructure-to-hcl2 -type RemoveCDRomConfig -package iso +package common import ( "context" @@ -22,7 +22,7 @@ type StepRemoveCDRom struct { func (s *StepRemoveCDRom) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { ui := state.Get("ui").(packer.Ui) - vm := state.Get("vm").(*driver.VirtualMachineDriver) + vm := state.Get("vm").(driver.VirtualMachine) ui.Say("Eject CD-ROM drives...") err := vm.EjectCdroms() diff --git a/builder/vsphere/iso/step_remove_cdrom.hcl2spec.go b/builder/vsphere/common/step_remove_cdrom.hcl2spec.go similarity index 98% rename from builder/vsphere/iso/step_remove_cdrom.hcl2spec.go rename to builder/vsphere/common/step_remove_cdrom.hcl2spec.go index 06875db8b..b4f333504 100644 --- a/builder/vsphere/iso/step_remove_cdrom.hcl2spec.go +++ b/builder/vsphere/common/step_remove_cdrom.hcl2spec.go @@ -1,5 +1,5 @@ // Code generated by "mapstructure-to-hcl2 -type RemoveCDRomConfig"; DO NOT EDIT. -package iso +package common import ( "github.com/hashicorp/hcl/v2/hcldec" diff --git a/builder/vsphere/common/step_remove_cdrom_test.go b/builder/vsphere/common/step_remove_cdrom_test.go new file mode 100644 index 000000000..1017e48b0 --- /dev/null +++ b/builder/vsphere/common/step_remove_cdrom_test.go @@ -0,0 +1,111 @@ +package common + +import ( + "context" + "fmt" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/hashicorp/packer/builder/vsphere/driver" + "github.com/hashicorp/packer/helper/multistep" +) + +func TestStepRemoveCDRom_Run(t *testing.T) { + tc := []struct { + name string + step *StepRemoveCDRom + expectedAction multistep.StepAction + vmMock *driver.VirtualMachineMock + expectedVmMock *driver.VirtualMachineMock + fail bool + errMessage string + }{ + { + name: "Eject CD-ROM drives", + step: &StepRemoveCDRom{ + Config: &RemoveCDRomConfig{}, + }, + expectedAction: multistep.ActionContinue, + vmMock: new(driver.VirtualMachineMock), + expectedVmMock: &driver.VirtualMachineMock{ + EjectCdromsCalled: true, + }, + fail: false, + }, + { + name: "Failed to eject CD-ROM drives", + step: &StepRemoveCDRom{ + Config: &RemoveCDRomConfig{}, + }, + expectedAction: multistep.ActionHalt, + vmMock: &driver.VirtualMachineMock{ + EjectCdromsErr: fmt.Errorf("failed to eject cd-rom drives"), + }, + expectedVmMock: &driver.VirtualMachineMock{ + EjectCdromsCalled: true, + }, + fail: true, + errMessage: "failed to eject cd-rom drives", + }, + { + name: "Eject and delete CD-ROM drives", + step: &StepRemoveCDRom{ + Config: &RemoveCDRomConfig{ + RemoveCdrom: true, + }, + }, + expectedAction: multistep.ActionContinue, + vmMock: new(driver.VirtualMachineMock), + expectedVmMock: &driver.VirtualMachineMock{ + EjectCdromsCalled: true, + RemoveCdromsCalled: true, + }, + fail: false, + }, + { + name: "Fail to delete CD-ROM drives", + step: &StepRemoveCDRom{ + Config: &RemoveCDRomConfig{ + RemoveCdrom: true, + }, + }, + expectedAction: multistep.ActionHalt, + vmMock: &driver.VirtualMachineMock{ + RemoveCdromsErr: fmt.Errorf("failed to delete cd-rom devices"), + }, + expectedVmMock: &driver.VirtualMachineMock{ + EjectCdromsCalled: true, + RemoveCdromsCalled: true, + }, + fail: true, + errMessage: "failed to delete cd-rom devices", + }, + } + + for _, c := range tc { + t.Run(c.name, func(t *testing.T) { + state := basicStateBag(nil) + state.Put("vm", c.vmMock) + + if action := c.step.Run(context.TODO(), state); action != c.expectedAction { + t.Fatalf("unexpected action %v", action) + } + err, ok := state.Get("error").(error) + if ok { + if err.Error() != c.errMessage { + t.Fatalf("unexpected error %s", err.Error()) + } + } else { + if c.fail { + t.Fatalf("expected to fail but it didn't") + } + } + + if diff := cmp.Diff(c.vmMock, c.expectedVmMock, + cmpopts.IgnoreInterfaces(struct{ error }{})); diff != "" { + t.Fatalf("unexpected VirtualMachine calls: %s", diff) + } + }) + } +} diff --git a/builder/vsphere/iso/step_remove_floppy.go b/builder/vsphere/common/step_remove_floppy.go similarity index 81% rename from builder/vsphere/iso/step_remove_floppy.go rename to builder/vsphere/common/step_remove_floppy.go index 012b7be23..7141e04b9 100644 --- a/builder/vsphere/iso/step_remove_floppy.go +++ b/builder/vsphere/common/step_remove_floppy.go @@ -1,4 +1,4 @@ -package iso +package common import ( "context" @@ -6,7 +6,6 @@ import ( "github.com/hashicorp/packer/builder/vsphere/driver" "github.com/hashicorp/packer/helper/multistep" "github.com/hashicorp/packer/packer" - "github.com/vmware/govmomi/vim25/types" ) type StepRemoveFloppy struct { @@ -16,16 +15,15 @@ type StepRemoveFloppy struct { func (s *StepRemoveFloppy) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { ui := state.Get("ui").(packer.Ui) - vm := state.Get("vm").(*driver.VirtualMachineDriver) - d := state.Get("driver").(*driver.VCenterDriver) + vm := state.Get("vm").(driver.VirtualMachine) + d := state.Get("driver").(driver.Driver) ui.Say("Deleting Floppy drives...") - devices, err := vm.Devices() + floppies, err := vm.FloppyDevices() if err != nil { state.Put("error", err) return multistep.ActionHalt } - floppies := devices.SelectByType((*types.VirtualFloppy)(nil)) if err = vm.RemoveDevice(true, floppies...); err != nil { state.Put("error", err) return multistep.ActionHalt diff --git a/builder/vsphere/common/step_remove_floppy_test.go b/builder/vsphere/common/step_remove_floppy_test.go new file mode 100644 index 000000000..1b76bb0fa --- /dev/null +++ b/builder/vsphere/common/step_remove_floppy_test.go @@ -0,0 +1,213 @@ +package common + +import ( + "context" + "fmt" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/hashicorp/packer/builder/vsphere/driver" + "github.com/hashicorp/packer/helper/multistep" +) + +func TestStepRemoveFloppy_Run(t *testing.T) { + tc := []struct { + name string + uploadedPath string + step *StepRemoveFloppy + expectedAction multistep.StepAction + vmMock *driver.VirtualMachineMock + expectedVmMock *driver.VirtualMachineMock + driverMock *driver.DriverMock + expectedDriverMock *driver.DriverMock + dsMock *driver.DatastoreMock + expectedDsMock *driver.DatastoreMock + fail bool + errMessage string + }{ + { + name: "Remove floppy drives and images", + uploadedPath: "vm/dir/packer-tmp-created-floppy.flp", + step: &StepRemoveFloppy{ + Datastore: "datastore", + Host: "host", + }, + expectedAction: multistep.ActionContinue, + vmMock: new(driver.VirtualMachineMock), + expectedVmMock: &driver.VirtualMachineMock{ + FloppyDevicesCalled: true, + RemoveDeviceCalled: true, + RemoveDeviceKeepFiles: true, + }, + driverMock: new(driver.DriverMock), + expectedDriverMock: &driver.DriverMock{ + FindDatastoreCalled: true, + FindDatastoreName: "datastore", + FindDatastoreHost: "host", + }, + dsMock: new(driver.DatastoreMock), + expectedDsMock: &driver.DatastoreMock{ + DeleteCalled: true, + DeletePath: "vm/dir/packer-tmp-created-floppy.flp", + }, + fail: false, + }, + { + name: "No floppy image to remove", + step: &StepRemoveFloppy{}, + expectedAction: multistep.ActionContinue, + vmMock: new(driver.VirtualMachineMock), + expectedVmMock: &driver.VirtualMachineMock{ + FloppyDevicesCalled: true, + RemoveDeviceCalled: true, + RemoveDeviceKeepFiles: true, + }, + driverMock: new(driver.DriverMock), + expectedDriverMock: new(driver.DriverMock), + dsMock: new(driver.DatastoreMock), + expectedDsMock: new(driver.DatastoreMock), + fail: false, + }, + { + name: "Fail to find floppy devices", + step: &StepRemoveFloppy{}, + expectedAction: multistep.ActionHalt, + vmMock: &driver.VirtualMachineMock{ + FloppyDevicesErr: fmt.Errorf("failed to find floppy devices"), + }, + expectedVmMock: &driver.VirtualMachineMock{ + FloppyDevicesCalled: true, + }, + driverMock: new(driver.DriverMock), + expectedDriverMock: new(driver.DriverMock), + dsMock: new(driver.DatastoreMock), + expectedDsMock: new(driver.DatastoreMock), + fail: true, + errMessage: "failed to find floppy devices", + }, + { + name: "Fail to remove floppy devices", + step: &StepRemoveFloppy{}, + expectedAction: multistep.ActionHalt, + vmMock: &driver.VirtualMachineMock{ + RemoveDeviceErr: fmt.Errorf("failed to remove device"), + }, + expectedVmMock: &driver.VirtualMachineMock{ + FloppyDevicesCalled: true, + RemoveDeviceCalled: true, + RemoveDeviceKeepFiles: true, + }, + driverMock: new(driver.DriverMock), + expectedDriverMock: new(driver.DriverMock), + dsMock: new(driver.DatastoreMock), + expectedDsMock: new(driver.DatastoreMock), + fail: true, + errMessage: "failed to remove device", + }, + { + name: "Fail to find datastore", + uploadedPath: "vm/dir/packer-tmp-created-floppy.flp", + step: &StepRemoveFloppy{ + Datastore: "datastore", + Host: "host", + }, + expectedAction: multistep.ActionHalt, + vmMock: new(driver.VirtualMachineMock), + expectedVmMock: &driver.VirtualMachineMock{ + FloppyDevicesCalled: true, + RemoveDeviceCalled: true, + RemoveDeviceKeepFiles: true, + }, + driverMock: &driver.DriverMock{ + FindDatastoreErr: fmt.Errorf("failed to find datastore"), + }, + expectedDriverMock: &driver.DriverMock{ + FindDatastoreCalled: true, + FindDatastoreName: "datastore", + FindDatastoreHost: "host", + }, + dsMock: new(driver.DatastoreMock), + expectedDsMock: new(driver.DatastoreMock), + fail: true, + errMessage: "failed to find datastore", + }, + { + name: "Fail to delete floppy image", + uploadedPath: "vm/dir/packer-tmp-created-floppy.flp", + step: &StepRemoveFloppy{ + Datastore: "datastore", + Host: "host", + }, + expectedAction: multistep.ActionHalt, + vmMock: new(driver.VirtualMachineMock), + expectedVmMock: &driver.VirtualMachineMock{ + FloppyDevicesCalled: true, + RemoveDeviceCalled: true, + RemoveDeviceKeepFiles: true, + }, + driverMock: new(driver.DriverMock), + expectedDriverMock: &driver.DriverMock{ + FindDatastoreCalled: true, + FindDatastoreName: "datastore", + FindDatastoreHost: "host", + }, + dsMock: &driver.DatastoreMock{ + DeleteErr: fmt.Errorf("failed to delete floppy"), + }, + expectedDsMock: &driver.DatastoreMock{ + DeleteCalled: true, + DeletePath: "vm/dir/packer-tmp-created-floppy.flp", + }, + fail: true, + errMessage: "failed to delete floppy", + }, + } + + for _, c := range tc { + t.Run(c.name, func(t *testing.T) { + state := basicStateBag(nil) + state.Put("vm", c.vmMock) + c.driverMock.DatastoreMock = c.dsMock + state.Put("driver", c.driverMock) + + if c.uploadedPath != "" { + state.Put("uploaded_floppy_path", c.uploadedPath) + } + + if action := c.step.Run(context.TODO(), state); action != c.expectedAction { + t.Fatalf("unexpected action %v", action) + } + err, ok := state.Get("error").(error) + if ok { + if err.Error() != c.errMessage { + t.Fatalf("unexpected error %s", err.Error()) + } + } else { + if c.fail { + t.Fatalf("expected to fail but it didn't") + } + } + + if !c.fail { + if _, ok := state.GetOk("uploaded_floppy_path"); ok { + t.Fatalf("uploaded_floppy_path should not be in state") + } + } + + if diff := cmp.Diff(c.vmMock, c.expectedVmMock, + cmpopts.IgnoreInterfaces(struct{ error }{})); diff != "" { + t.Fatalf("unexpected VirtualMachine calls: %s", diff) + } + c.expectedDriverMock.DatastoreMock = c.expectedDsMock + if diff := cmp.Diff(c.driverMock, c.expectedDriverMock, + cmpopts.IgnoreInterfaces(struct{ error }{})); diff != "" { + t.Fatalf("unexpected Driver calls: %s", diff) + } + if diff := cmp.Diff(c.dsMock, c.expectedDsMock, + cmpopts.IgnoreInterfaces(struct{ error }{})); diff != "" { + t.Fatalf("unexpected Datastore calls: %s", diff) + } + }) + } +} diff --git a/builder/vsphere/driver/datastore_mock.go b/builder/vsphere/driver/datastore_mock.go index 52fbc7c6b..b85c95f5b 100644 --- a/builder/vsphere/driver/datastore_mock.go +++ b/builder/vsphere/driver/datastore_mock.go @@ -8,7 +8,20 @@ import ( type DatastoreMock struct { FileExistsCalled bool MakeDirectoryCalled bool - UploadFileCalled bool + + ResolvePathCalled bool + ResolvePathReturn string + + DeleteCalled bool + DeletePath string + DeleteErr error + + UploadFileCalled bool + UploadFileSrc string + UploadFileDst string + UploadFileHost string + UploadFileSetHost bool + UploadFileErr error } func (ds *DatastoreMock) Info(params ...string) (*mo.Datastore, error) { @@ -29,16 +42,23 @@ func (ds *DatastoreMock) Reference() types.ManagedObjectReference { } func (ds *DatastoreMock) ResolvePath(path string) string { - return "" + ds.ResolvePathCalled = true + return ds.ResolvePathReturn } func (ds *DatastoreMock) UploadFile(src, dst, host string, setHost bool) error { ds.UploadFileCalled = true - return nil + ds.UploadFileSrc = src + ds.UploadFileDst = dst + ds.UploadFileHost = host + ds.UploadFileSetHost = setHost + return ds.UploadFileErr } func (ds *DatastoreMock) Delete(path string) error { - return nil + ds.DeleteCalled = true + ds.DeletePath = path + return ds.DeleteErr } func (ds *DatastoreMock) MakeDirectory(path string) error { diff --git a/builder/vsphere/driver/datastore_test.go b/builder/vsphere/driver/datastore_test.go index 33f5f25e3..d2b296d92 100644 --- a/builder/vsphere/driver/datastore_test.go +++ b/builder/vsphere/driver/datastore_test.go @@ -1,6 +1,10 @@ package driver -import "testing" +import ( + "testing" + + "github.com/vmware/govmomi/simulator" +) func TestDatastoreIsoPath(t *testing.T) { tc := []struct { @@ -87,3 +91,84 @@ func TestDatastoreIsoPath(t *testing.T) { } } } + +func TestVCenterDriver_FindDatastore(t *testing.T) { + sim, err := NewVCenterSimulator() + if err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + defer sim.Close() + + _, datastore := sim.ChooseSimulatorPreCreatedDatastore() + _, host := sim.ChooseSimulatorPreCreatedHost() + + tc := []struct { + name string + datastore string + host string + fail bool + errMessage string + }{ + { + name: "should find datastore when name is provided", + datastore: datastore.Name, + fail: false, + }, + { + name: "should find datastore when only host is provided", + host: host.Name, + fail: false, + }, + { + name: "should not find invalid datastore", + datastore: "invalid", + fail: true, + }, + { + name: "should not find invalid host", + host: "invalid", + fail: true, + }, + } + + for _, c := range tc { + t.Run(c.name, func(t *testing.T) { + ds, err := sim.driver.FindDatastore(c.datastore, c.host) + if c.fail { + if err == nil { + t.Fatalf("expected to fail") + } + if c.errMessage != "" && err.Error() != c.errMessage { + t.Fatalf("unexpected error message %s", err.Error()) + } + } else { + if err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + if ds == nil { + t.Fatalf("expected to find datastore") + } + } + }) + } +} + +func TestVCenterDriver_MultipleDatastoreError(t *testing.T) { + model := simulator.ESX() + model.Datastore = 2 + sim, err := NewCustomVCenterSimulator(model) + if err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + defer sim.Close() + + _, host := sim.ChooseSimulatorPreCreatedHost() + + _, err = sim.driver.FindDatastore("", host.Name) + if err == nil { + t.Fatalf("expected to fail") + } + if err.Error() != "Host has multiple datastores. Specify it explicitly" { + t.Fatalf("unexpected error message %s", err.Error()) + } +} diff --git a/builder/vsphere/driver/driver_mock.go b/builder/vsphere/driver/driver_mock.go index e1bbe1348..7f8748606 100644 --- a/builder/vsphere/driver/driver_mock.go +++ b/builder/vsphere/driver/driver_mock.go @@ -11,6 +11,9 @@ import ( type DriverMock struct { FindDatastoreCalled bool DatastoreMock *DatastoreMock + FindDatastoreName string + FindDatastoreHost string + FindDatastoreErr error PreCleanShouldFail bool PreCleanVMCalled bool @@ -32,7 +35,9 @@ func (d *DriverMock) FindDatastore(name string, host string) (Datastore, error) if d.DatastoreMock == nil { d.DatastoreMock = new(DatastoreMock) } - return d.DatastoreMock, nil + d.FindDatastoreName = name + d.FindDatastoreHost = host + return d.DatastoreMock, d.FindDatastoreErr } func (d *DriverMock) NewVM(ref *types.ManagedObjectReference) VirtualMachine { diff --git a/builder/vsphere/driver/driver_test.go b/builder/vsphere/driver/driver_test.go index a3818a34a..534755858 100644 --- a/builder/vsphere/driver/driver_test.go +++ b/builder/vsphere/driver/driver_test.go @@ -50,24 +50,89 @@ func newVMName() string { return fmt.Sprintf("test-%v", rand.Intn(1000)) } -func NewSimulatorServer(model *simulator.Model) (*simulator.Server, error) { - err := model.Create() +type VCenterSimulator struct { + model *simulator.Model + server *simulator.Server + driver *VCenterDriver +} + +func NewCustomVCenterSimulator(model *simulator.Model) (*VCenterSimulator, error) { + sim := new(VCenterSimulator) + sim.model = model + + server, err := sim.NewSimulatorServer() + if err != nil { + sim.Close() + return nil, err + } + sim.server = server + + driver, err := sim.NewSimulatorDriver() + if err != nil { + sim.Close() + return nil, err + } + sim.driver = driver + return sim, nil +} + +func NewVCenterSimulator() (*VCenterSimulator, error) { + model := simulator.VPX() + model.Machine = 1 + return NewCustomVCenterSimulator(model) +} + +func (s *VCenterSimulator) Close() { + if s.model != nil { + s.model.Remove() + } + if s.server != nil { + s.server.Close() + } +} + +//Simulator shortcut to choose any pre created VM. +func (s *VCenterSimulator) ChooseSimulatorPreCreatedVM() (VirtualMachine, *simulator.VirtualMachine) { + machine := simulator.Map.Any("VirtualMachine").(*simulator.VirtualMachine) + ref := machine.Reference() + vm := s.driver.NewVM(&ref) + return vm, machine +} + +//Simulator shortcut to choose any pre created Datastore. +func (s *VCenterSimulator) ChooseSimulatorPreCreatedDatastore() (Datastore, *simulator.Datastore) { + ds := simulator.Map.Any("Datastore").(*simulator.Datastore) + ref := ds.Reference() + datastore := s.driver.NewDatastore(&ref) + return datastore, ds +} + +//Simulator shortcut to choose any pre created Host. +func (s *VCenterSimulator) ChooseSimulatorPreCreatedHost() (*Host, *simulator.HostSystem) { + h := simulator.Map.Any("HostSystem").(*simulator.HostSystem) + ref := h.Reference() + host := s.driver.NewHost(&ref) + return host, h +} + +func (s *VCenterSimulator) NewSimulatorServer() (*simulator.Server, error) { + err := s.model.Create() if err != nil { return nil, err } - model.Service.RegisterEndpoints = true - model.Service.TLS = new(tls.Config) - model.Service.ServeMux = http.NewServeMux() - return model.Service.NewServer(), nil + s.model.Service.RegisterEndpoints = true + s.model.Service.TLS = new(tls.Config) + s.model.Service.ServeMux = http.NewServeMux() + return s.model.Service.NewServer(), nil } -func NewSimulatorDriver(s *simulator.Server) (*VCenterDriver, error) { +func (s *VCenterSimulator) NewSimulatorDriver() (*VCenterDriver, error) { ctx := context.TODO() user := &url.Userinfo{} - s.URL.User = user + s.server.URL.User = user - soapClient := soap.NewClient(s.URL, true) + soapClient := soap.NewClient(s.server.URL, true) vimClient, err := vim25.NewClient(ctx, soapClient) if err != nil { return nil, err diff --git a/builder/vsphere/driver/resource_pool_test.go b/builder/vsphere/driver/resource_pool_test.go index d70656db5..32badbae9 100644 --- a/builder/vsphere/driver/resource_pool_test.go +++ b/builder/vsphere/driver/resource_pool_test.go @@ -7,21 +7,13 @@ import ( ) func TestVCenterDriver_FindResourcePool(t *testing.T) { - model := simulator.VPX() - defer model.Remove() - - s, err := NewSimulatorServer(model) + sim, err := NewVCenterSimulator() if err != nil { t.Fatalf("should not fail: %s", err.Error()) } - defer s.Close() + defer sim.Close() - driverSim, err := NewSimulatorDriver(s) - if err != nil { - t.Fatalf("should not fail: %s", err.Error()) - } - - res, err := driverSim.FindResourcePool("", "DC0_H0", "") + res, err := sim.driver.FindResourcePool("", "DC0_H0", "") if err != nil { t.Fatalf("should not fail: %s", err.Error()) } @@ -47,19 +39,13 @@ func TestVCenterDriver_FindResourcePoolStandaloneESX(t *testing.T) { model.DelayConfig.MethodDelay = opts.DelayConfig.MethodDelay model.DelayConfig.DelayJitter = opts.DelayConfig.DelayJitter - s, err := NewSimulatorServer(model) + sim, err := NewCustomVCenterSimulator(model) if err != nil { t.Fatalf("should not fail: %s", err.Error()) } - defer s.Close() + defer sim.Close() - driverSim, err := NewSimulatorDriver(s) - if err != nil { - t.Fatalf("should not fail: %s", err.Error()) - } - - // - res, err := driverSim.FindResourcePool("", "localhost.localdomain", "") + res, err := sim.driver.FindResourcePool("", "localhost.localdomain", "") if err != nil { t.Fatalf("should not fail: %s", err.Error()) } @@ -72,7 +58,7 @@ func TestVCenterDriver_FindResourcePoolStandaloneESX(t *testing.T) { } // Invalid resource name should look for default resource pool - res, err = driverSim.FindResourcePool("", "localhost.localdomain", "invalid") + res, err = sim.driver.FindResourcePool("", "localhost.localdomain", "invalid") if err != nil { t.Fatalf("should not fail: %s", err.Error()) } diff --git a/builder/vsphere/driver/vm.go b/builder/vsphere/driver/vm.go index 0310af1c9..f0bbf6f6d 100644 --- a/builder/vsphere/driver/vm.go +++ b/builder/vsphere/driver/vm.go @@ -24,6 +24,7 @@ import ( type VirtualMachine interface { Info(params ...string) (*mo.VirtualMachine, error) Devices() (object.VirtualDeviceList, error) + FloppyDevices() (object.VirtualDeviceList, error) Clone(ctx context.Context, config *CloneConfig) (VirtualMachine, error) updateVAppConfig(ctx context.Context, newProps map[string]string) (*types.VmConfigSpec, error) AddPublicKeys(ctx context.Context, publicKeys string) error @@ -32,8 +33,8 @@ type VirtualMachine interface { Configure(config *HardwareConfig) error Customize(spec types.CustomizationSpec) error ResizeDisk(diskSize int64) error - PowerOn() error WaitForIP(ctx context.Context, ipNet *net.IPNet) (string, error) + PowerOn() error PowerOff() error IsPoweredOff() (bool, error) StartShutdown() error @@ -43,7 +44,6 @@ type VirtualMachine interface { ImportOvfToContentLibrary(ovf vcenter.OVF) error ImportToContentLibrary(template vcenter.Template) error GetDir() (string, error) - AddCdrom(controllerType string, datastoreIsoPath string) error AddFloppy(imgPath string) error SetBootOrder(order []string) error RemoveDevice(keepFiles bool, device ...types.BaseVirtualDevice) error @@ -53,6 +53,13 @@ type VirtualMachine interface { CreateDescriptor(m *ovf.Manager, cdp types.OvfCreateDescriptorParams) (*types.OvfCreateDescriptorResult, error) NewOvfManager() *ovf.Manager GetOvfExportOptions(m *ovf.Manager) ([]types.OvfOptionInfo, error) + + AddCdrom(controllerType string, datastoreIsoPath string) error + CreateCdrom(c *types.VirtualController) (*types.VirtualCdrom, error) + RemoveCdroms() error + EjectCdroms() error + AddSATAController() error + FindSATAController() (*types.VirtualAHCIController, error) } type VirtualMachineDriver struct { @@ -69,6 +76,7 @@ type CloneConfig struct { Datastore string LinkedClone bool Network string + MacAddress string Annotation string VAppProperties map[string]string } @@ -277,6 +285,15 @@ func (vm *VirtualMachineDriver) Devices() (object.VirtualDeviceList, error) { return vmInfo.Config.Hardware.Device, nil } +func (vm *VirtualMachineDriver) FloppyDevices() (object.VirtualDeviceList, error) { + device, err := vm.Devices() + if err != nil { + return device, err + } + floppies := device.SelectByType((*types.VirtualFloppy)(nil)) + return floppies, nil +} + func (vm *VirtualMachineDriver) Clone(ctx context.Context, config *CloneConfig) (VirtualMachine, error) { folder, err := vm.driver.FindFolder(config.Folder) if err != nil { @@ -344,7 +361,9 @@ func (vm *VirtualMachineDriver) Clone(ctx context.Context, config *CloneConfig) return nil, err } - adapter.GetVirtualEthernetCard().Backing = backing + current := adapter.GetVirtualEthernetCard() + current.Backing = backing + current.MacAddress = config.MacAddress config := &types.VirtualDeviceConfigSpec{ Device: adapter.(types.BaseVirtualDevice), diff --git a/builder/vsphere/driver/vm_cdrom_test.go b/builder/vsphere/driver/vm_cdrom_test.go new file mode 100644 index 000000000..8a7b86ba1 --- /dev/null +++ b/builder/vsphere/driver/vm_cdrom_test.go @@ -0,0 +1,167 @@ +package driver + +import ( + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/vmware/govmomi/vim25/types" +) + +func TestVirtualMachineDriver_FindAndAddSATAController(t *testing.T) { + sim, err := NewVCenterSimulator() + if err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + defer sim.Close() + + vm, _ := sim.ChooseSimulatorPreCreatedVM() + + _, err = vm.FindSATAController() + if err != nil && !strings.Contains(err.Error(), "no available SATA controller") { + t.Fatalf("unexpected error: %s", err.Error()) + } + if err == nil { + t.Fatalf("vm should not have sata controller") + } + + if err := vm.AddSATAController(); err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + + sc, err := vm.FindSATAController() + if err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + if sc == nil { + t.Fatalf("SATA controller wasn't added properly") + } +} + +func TestVirtualMachineDriver_CreateAndRemoveCdrom(t *testing.T) { + sim, err := NewVCenterSimulator() + if err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + defer sim.Close() + + vm, _ := sim.ChooseSimulatorPreCreatedVM() + + // Add SATA Controller + if err := vm.AddSATAController(); err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + + // Verify if controller was created + sc, err := vm.FindSATAController() + if err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + if sc == nil { + t.Fatalf("SATA controller wasn't added properly") + } + + // Create CDROM + controller := sc.GetVirtualController() + cdrom, err := vm.CreateCdrom(controller) + if err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + if cdrom == nil { + t.Fatalf("CDrom wasn't created properly") + } + + // Verify if CDROM was created + devices, err := vm.Devices() + if err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + cdroms := devices.SelectByType((*types.VirtualCdrom)(nil)) + if len(cdroms) != 1 { + t.Fatalf("unexpected numbers of cdrom: %d", len(cdroms)) + } + + // Remove CDROM + err = vm.RemoveCdroms() + if err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + // Verify if CDROM was removed + devices, err = vm.Devices() + if err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + cdroms = devices.SelectByType((*types.VirtualCdrom)(nil)) + if len(cdroms) != 0 { + t.Fatalf("unexpected numbers of cdrom: %d", len(cdroms)) + } +} + +func TestVirtualMachineDriver_EjectCdrom(t *testing.T) { + sim, err := NewVCenterSimulator() + if err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + defer sim.Close() + + vm, _ := sim.ChooseSimulatorPreCreatedVM() + + // Add SATA Controller + if err := vm.AddSATAController(); err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + + // Verify if controller was created + sc, err := vm.FindSATAController() + if err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + if sc == nil { + t.Fatalf("SATA controller wasn't added properly") + } + + // Create CDROM + controller := sc.GetVirtualController() + cdrom, err := vm.CreateCdrom(controller) + if err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + if cdrom == nil { + t.Fatalf("CDrom wasn't created properly") + } + + // Verify if CDROM was created + devices, err := vm.Devices() + if err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + cdroms := devices.SelectByType((*types.VirtualCdrom)(nil)) + if len(cdroms) != 1 { + t.Fatalf("unexpected numbers of cdrom: %d", len(cdroms)) + } + + // Remove CDROM + err = vm.EjectCdroms() + if err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + // Verify if CDROM was removed + devices, err = vm.Devices() + if err != nil { + t.Fatalf("should not fail: %s", err.Error()) + } + cdroms = devices.SelectByType((*types.VirtualCdrom)(nil)) + if len(cdroms) != 1 { + t.Fatalf("unexpected numbers of cdrom: %d", len(cdroms)) + } + cd, ok := cdroms[0].(*types.VirtualCdrom) + if !ok { + t.Fatalf("Wrong cdrom type") + } + if diff := cmp.Diff(cd.Backing, &types.VirtualCdromRemotePassthroughBackingInfo{}); diff != "" { + t.Fatalf("Wrong cdrom backing info: %s", diff) + } + if diff := cmp.Diff(cd.Connectable, &types.VirtualDeviceConnectInfo{}); diff != "" { + t.Fatalf("Wrong cdrom connect info: %s", diff) + } +} diff --git a/builder/vsphere/driver/vm_mock.go b/builder/vsphere/driver/vm_mock.go index 4af694d9d..5251b2030 100644 --- a/builder/vsphere/driver/vm_mock.go +++ b/builder/vsphere/driver/vm_mock.go @@ -20,6 +20,41 @@ type VirtualMachineMock struct { ConfigureError error ConfigureCalled bool ConfigureHardwareConfig *HardwareConfig + + FindSATAControllerCalled bool + FindSATAControllerErr error + + AddSATAControllerCalled bool + AddSATAControllerErr error + + AddCdromCalled bool + AddCdromCalledTimes int + AddCdromErr error + AddCdromTypes []string + AddCdromPaths []string + + GetDirCalled bool + GetDirResponse string + GetDirErr error + + AddFloppyCalled bool + AddFloppyImagePath string + AddFloppyErr error + + FloppyDevicesErr error + FloppyDevicesReturn object.VirtualDeviceList + FloppyDevicesCalled bool + + RemoveDeviceErr error + RemoveDeviceCalled bool + RemoveDeviceKeepFiles bool + RemoveDeviceDevices []types.BaseVirtualDevice + + EjectCdromsCalled bool + EjectCdromsErr error + + RemoveCdromsCalled bool + RemoveCdromsErr error } func (vm *VirtualMachineMock) Info(params ...string) (*mo.VirtualMachine, error) { @@ -30,6 +65,11 @@ func (vm *VirtualMachineMock) Devices() (object.VirtualDeviceList, error) { return object.VirtualDeviceList{}, nil } +func (vm *VirtualMachineMock) FloppyDevices() (object.VirtualDeviceList, error) { + vm.FloppyDevicesCalled = true + return vm.FloppyDevicesReturn, vm.FloppyDevicesErr +} + func (vm *VirtualMachineMock) Clone(ctx context.Context, config *CloneConfig) (VirtualMachine, error) { return nil, nil } @@ -112,15 +152,22 @@ func (vm *VirtualMachineMock) ImportToContentLibrary(template vcenter.Template) } func (vm *VirtualMachineMock) GetDir() (string, error) { - return "", nil + vm.GetDirCalled = true + return vm.GetDirResponse, vm.GetDirErr } -func (vm *VirtualMachineMock) AddCdrom(controllerType string, datastoreIsoPath string) error { - return nil +func (vm *VirtualMachineMock) AddCdrom(cdromType string, isoPath string) error { + vm.AddCdromCalledTimes++ + vm.AddCdromCalled = true + vm.AddCdromTypes = append(vm.AddCdromTypes, cdromType) + vm.AddCdromPaths = append(vm.AddCdromPaths, isoPath) + return vm.AddCdromErr } func (vm *VirtualMachineMock) AddFloppy(imgPath string) error { - return nil + vm.AddFloppyCalled = true + vm.AddFloppyImagePath = imgPath + return vm.AddFloppyErr } func (vm *VirtualMachineMock) SetBootOrder(order []string) error { @@ -128,7 +175,10 @@ func (vm *VirtualMachineMock) SetBootOrder(order []string) error { } func (vm *VirtualMachineMock) RemoveDevice(keepFiles bool, device ...types.BaseVirtualDevice) error { - return nil + vm.RemoveDeviceCalled = true + vm.RemoveDeviceKeepFiles = keepFiles + vm.RemoveDeviceDevices = device + return vm.RemoveDeviceErr } func (vm *VirtualMachineMock) addDevice(device types.BaseVirtualDevice) error { @@ -154,3 +204,27 @@ func (vm *VirtualMachineMock) NewOvfManager() *ovf.Manager { func (vm *VirtualMachineMock) GetOvfExportOptions(m *ovf.Manager) ([]types.OvfOptionInfo, error) { return nil, nil } + +func (vm *VirtualMachineMock) AddSATAController() error { + vm.AddSATAControllerCalled = true + return vm.AddSATAControllerErr +} + +func (vm *VirtualMachineMock) FindSATAController() (*types.VirtualAHCIController, error) { + vm.FindSATAControllerCalled = true + return nil, vm.FindSATAControllerErr +} + +func (vm *VirtualMachineMock) CreateCdrom(c *types.VirtualController) (*types.VirtualCdrom, error) { + return nil, nil +} + +func (vm *VirtualMachineMock) RemoveCdroms() error { + vm.RemoveCdromsCalled = true + return vm.RemoveCdromsErr +} + +func (vm *VirtualMachineMock) EjectCdroms() error { + vm.EjectCdromsCalled = true + return vm.EjectCdromsErr +} diff --git a/builder/vsphere/driver/vm_test.go b/builder/vsphere/driver/vm_test.go index e9d8a8917..3a2b5106f 100644 --- a/builder/vsphere/driver/vm_test.go +++ b/builder/vsphere/driver/vm_test.go @@ -28,25 +28,13 @@ func (vm *ReconfigureFail) ReconfigVMTask(req *types.ReconfigVM_Task) soap.HasFa } func TestVirtualMachineDriver_Configure(t *testing.T) { - model := simulator.VPX() - model.Machine = 1 - defer model.Remove() - - s, err := NewSimulatorServer(model) + sim, err := NewVCenterSimulator() if err != nil { t.Fatalf("should not fail: %s", err.Error()) } - defer s.Close() + defer sim.Close() - driverSim, err := NewSimulatorDriver(s) - if err != nil { - t.Fatalf("should not fail: %s", err.Error()) - } - - //Simulator shortcut to choose any pre created VM. - machine := simulator.Map.Any("VirtualMachine").(*simulator.VirtualMachine) - ref := machine.Reference() - vm := driverSim.NewVM(&ref) + vm, machine := sim.ChooseSimulatorPreCreatedVM() // Happy test hardwareConfig := &HardwareConfig{ diff --git a/builder/vsphere/iso/builder.go b/builder/vsphere/iso/builder.go index 0665b2088..e3fc9ec46 100644 --- a/builder/vsphere/iso/builder.go +++ b/builder/vsphere/iso/builder.go @@ -40,27 +40,23 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack &common.StepConnect{ Config: &b.config.ConnectConfig, }, - ) - - if b.config.ISOUrls != nil { - steps = append(steps, - &packerCommon.StepDownload{ - Checksum: b.config.ISOChecksum, - Description: "ISO", - Extension: b.config.TargetExtension, - ResultKey: "iso_path", - TargetPath: b.config.TargetPath, - Url: b.config.ISOUrls, - }, - &StepRemoteUpload{ - Datastore: b.config.Datastore, - Host: b.config.Host, - SetHostForDatastoreUploads: b.config.SetHostForDatastoreUploads, - }, - ) - } - - steps = append(steps, + &packerCommon.StepDownload{ + Checksum: b.config.ISOChecksum, + Description: "ISO", + Extension: b.config.TargetExtension, + ResultKey: "iso_path", + TargetPath: b.config.TargetPath, + Url: b.config.ISOUrls, + }, + &packerCommon.StepCreateCD{ + Files: b.config.CDConfig.CDFiles, + Label: b.config.CDConfig.CDLabel, + }, + &common.StepRemoteUpload{ + Datastore: b.config.Datastore, + Host: b.config.Host, + SetHostForDatastoreUploads: b.config.SetHostForDatastoreUploads, + }, &StepCreateVM{ Config: &b.config.CreateConfig, Location: &b.config.LocationConfig, @@ -69,7 +65,7 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack &common.StepConfigureHardware{ Config: &b.config.HardwareConfig, }, - &StepAddCDRom{ + &common.StepAddCDRom{ Config: &b.config.CDRomConfig, }, &common.StepConfigParams{ @@ -84,7 +80,7 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack Directories: b.config.FloppyDirectories, Label: b.config.FloppyLabel, }, - &StepAddFloppy{ + &common.StepAddFloppy{ Config: &b.config.FloppyConfig, Datastore: b.config.Datastore, Host: b.config.Host, @@ -121,7 +117,7 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack &common.StepShutdown{ Config: &b.config.ShutdownConfig, }, - &StepRemoveFloppy{ + &common.StepRemoveFloppy{ Datastore: b.config.Datastore, Host: b.config.Host, }, @@ -129,7 +125,7 @@ func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (pack } steps = append(steps, - &StepRemoveCDRom{ + &common.StepRemoveCDRom{ Config: &b.config.RemoveCDRomConfig, }, &common.StepCreateSnapshot{ diff --git a/builder/vsphere/iso/config.go b/builder/vsphere/iso/config.go index 890f10942..2d83c35d0 100644 --- a/builder/vsphere/iso/config.go +++ b/builder/vsphere/iso/config.go @@ -15,6 +15,7 @@ import ( type Config struct { packerCommon.PackerConfig `mapstructure:",squash"` packerCommon.HTTPConfig `mapstructure:",squash"` + packerCommon.CDConfig `mapstructure:",squash"` common.ConnectConfig `mapstructure:",squash"` CreateConfig `mapstructure:",squash"` @@ -24,13 +25,13 @@ type Config struct { packerCommon.ISOConfig `mapstructure:",squash"` - CDRomConfig `mapstructure:",squash"` - RemoveCDRomConfig `mapstructure:",squash"` - FloppyConfig `mapstructure:",squash"` - common.RunConfig `mapstructure:",squash"` - common.BootConfig `mapstructure:",squash"` - common.WaitIpConfig `mapstructure:",squash"` - Comm communicator.Config `mapstructure:",squash"` + common.CDRomConfig `mapstructure:",squash"` + common.RemoveCDRomConfig `mapstructure:",squash"` + common.FloppyConfig `mapstructure:",squash"` + common.RunConfig `mapstructure:",squash"` + common.BootConfig `mapstructure:",squash"` + common.WaitIpConfig `mapstructure:",squash"` + Comm communicator.Config `mapstructure:",squash"` common.ShutdownConfig `mapstructure:",squash"` @@ -80,6 +81,7 @@ func (c *Config) Prepare(raws ...interface{}) ([]string, error) { errs = packer.MultiErrorAppend(errs, c.HTTPConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.CDRomConfig.Prepare()...) + errs = packer.MultiErrorAppend(errs, c.CDConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.BootConfig.Prepare(&c.ctx)...) errs = packer.MultiErrorAppend(errs, c.WaitIpConfig.Prepare()...) errs = packer.MultiErrorAppend(errs, c.Comm.Prepare(&c.ctx)...) diff --git a/builder/vsphere/iso/config.hcl2spec.go b/builder/vsphere/iso/config.hcl2spec.go index b8c0f0115..4216438f0 100644 --- a/builder/vsphere/iso/config.hcl2spec.go +++ b/builder/vsphere/iso/config.hcl2spec.go @@ -21,6 +21,9 @@ type FlatConfig struct { HTTPPortMin *int `mapstructure:"http_port_min" cty:"http_port_min" hcl:"http_port_min"` HTTPPortMax *int `mapstructure:"http_port_max" cty:"http_port_max" hcl:"http_port_max"` HTTPAddress *string `mapstructure:"http_bind_address" cty:"http_bind_address" hcl:"http_bind_address"` + HTTPInterface *string `mapstructure:"http_interface" undocumented:"true" cty:"http_interface" hcl:"http_interface"` + CDFiles []string `mapstructure:"cd_files" cty:"cd_files" hcl:"cd_files"` + CDLabel *string `mapstructure:"cd_label" cty:"cd_label" hcl:"cd_label"` VCenterServer *string `mapstructure:"vcenter_server" cty:"vcenter_server" hcl:"vcenter_server"` Username *string `mapstructure:"username" cty:"username" hcl:"username"` Password *string `mapstructure:"password" cty:"password" hcl:"password"` @@ -156,6 +159,9 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "http_port_min": &hcldec.AttrSpec{Name: "http_port_min", Type: cty.Number, Required: false}, "http_port_max": &hcldec.AttrSpec{Name: "http_port_max", Type: cty.Number, Required: false}, "http_bind_address": &hcldec.AttrSpec{Name: "http_bind_address", Type: cty.String, Required: false}, + "http_interface": &hcldec.AttrSpec{Name: "http_interface", Type: cty.String, Required: false}, + "cd_files": &hcldec.AttrSpec{Name: "cd_files", Type: cty.List(cty.String), Required: false}, + "cd_label": &hcldec.AttrSpec{Name: "cd_label", Type: cty.String, Required: false}, "vcenter_server": &hcldec.AttrSpec{Name: "vcenter_server", Type: cty.String, Required: false}, "username": &hcldec.AttrSpec{Name: "username", Type: cty.String, Required: false}, "password": &hcldec.AttrSpec{Name: "password", Type: cty.String, Required: false}, diff --git a/builder/vsphere/iso/step_remote_upload.go b/builder/vsphere/iso/step_remote_upload.go deleted file mode 100644 index 7161962b8..000000000 --- a/builder/vsphere/iso/step_remote_upload.go +++ /dev/null @@ -1,59 +0,0 @@ -package iso - -import ( - "context" - "fmt" - "path/filepath" - - "github.com/hashicorp/packer/builder/vsphere/driver" - "github.com/hashicorp/packer/helper/multistep" - "github.com/hashicorp/packer/packer" -) - -type StepRemoteUpload struct { - Datastore string - Host string - SetHostForDatastoreUploads bool -} - -func (s *StepRemoteUpload) Run(_ context.Context, state multistep.StateBag) multistep.StepAction { - ui := state.Get("ui").(packer.Ui) - d := state.Get("driver").(driver.Driver) - - if path, ok := state.GetOk("iso_path"); ok { - filename := filepath.Base(path.(string)) - - ds, err := d.FindDatastore(s.Datastore, s.Host) - if err != nil { - state.Put("error", fmt.Errorf("datastore doesn't exist: %v", err)) - return multistep.ActionHalt - } - - remotePath := fmt.Sprintf("packer_cache/%s", filename) - remoteDirectory := fmt.Sprintf("[%s] packer_cache/", ds.Name()) - fullRemotePath := fmt.Sprintf("%s/%s", remoteDirectory, filename) - - ui.Say(fmt.Sprintf("Uploading %s to %s", filename, remotePath)) - - if exists := ds.FileExists(remotePath); exists == true { - ui.Say("File already uploaded; continuing") - state.Put("iso_remote_path", fullRemotePath) - return multistep.ActionContinue - } - - if err := ds.MakeDirectory(remoteDirectory); err != nil { - state.Put("error", err) - return multistep.ActionHalt - } - - if err := ds.UploadFile(path.(string), remotePath, s.Host, s.SetHostForDatastoreUploads); err != nil { - state.Put("error", err) - return multistep.ActionHalt - } - state.Put("iso_remote_path", fullRemotePath) - } - - return multistep.ActionContinue -} - -func (s *StepRemoteUpload) Cleanup(state multistep.StateBag) {} diff --git a/command/build_test.go b/command/build_test.go index 71be284a7..2fa5a6970 100644 --- a/command/build_test.go +++ b/command/build_test.go @@ -560,6 +560,17 @@ func TestBuildExceptFileCommaFlags(t *testing.T) { buildNotExpectedFiles: []string{"chocolate.txt", "vanilla.txt", "tomato.txt", "unnamed.txt"}, postProcNotExpectedFiles: []string{"pear.txt, banana.txt"}, }, + { + name: "HCL2-JSON: except build and post-processor", + args: []string{ + "-parallel-builds=1", + "-except=file.chocolate,file.vanilla,tomato", + filepath.Join(testFixture("build-only"), "template.pkr.json"), + }, + expectedFiles: []string{"apple.txt", "cherry.txt", "peach.txt"}, + buildNotExpectedFiles: []string{"chocolate.txt", "vanilla.txt", "tomato.txt", "unnamed.txt"}, + postProcNotExpectedFiles: []string{"pear.txt, banana.txt"}, + }, } for _, tt := range tc { diff --git a/command/command_test.go b/command/command_test.go index 34d044292..6d571b1eb 100644 --- a/command/command_test.go +++ b/command/command_test.go @@ -2,6 +2,7 @@ package command import ( "bytes" + "io/ioutil" "path/filepath" "testing" @@ -27,6 +28,15 @@ func outputCommand(t *testing.T, m Meta) (string, string) { return out.String(), err.String() } +func testFixtureContent(n ...string) string { + path := filepath.Join(append([]string{fixturesDir}, n...)...) + b, err := ioutil.ReadFile(path) + if err != nil { + panic(err) + } + return string(b) +} + func testFixture(n ...string) string { paths := []string{fixturesDir} paths = append(paths, n...) diff --git a/command/inspect_test.go b/command/inspect_test.go index 50cf31b06..5fda6c0d1 100644 --- a/command/inspect_test.go +++ b/command/inspect_test.go @@ -153,6 +153,13 @@ Note: If your build names contain user variables or template functions such as 'timestamp', these are processed at build time, and therefore only show in their raw form here. `}, + { + []string{ + "inspect", filepath.Join(testFixture("hcl-inspect-with-sensitive-vars")), + }, + nil, + testFixtureContent("hcl-inspect-with-sensitive-vars", "expected-output.txt"), + }, } for _, tc := range tc { diff --git a/command/test-fixtures/build-only/template.pkr.json b/command/test-fixtures/build-only/template.pkr.json new file mode 100644 index 000000000..c289bd6bc --- /dev/null +++ b/command/test-fixtures/build-only/template.pkr.json @@ -0,0 +1,83 @@ +{ + "source": { + "file": { + "chocolate": { + "content": "chocolate", + "target": "chocolate.txt" + } + }, + "file": { + "vanilla": { + "content": "vanilla", + "target": "vanilla.txt" + } + }, + "file": { + "cherry": { + "content": "cherry", + "target": "cherry.txt" + } + } + }, + "build": { + "sources": [ + "sources.file.chocolate", + "sources.file.vanilla", + "sources.file.cherry" + ], + "provisioner": [ + { + "shell-local": { + "name": "apple", + "inline": [ + "echo apple > apple.txt" + ] + } + } + ], + "post-processor": [ + { + "shell-local": { + "name": "peach", + "inline": [ + "echo peach > peach.txt" + ] + } + }, + { + "shell-local": { + "name": "pear", + "inline": [ + "echo pear > pear.txt" + ] + } + }, + { + "shell-local": { + "name": "banana", + "inline": [ + "echo banana > banana.txt" + ] + } + }, + { + "shell-local": { + "name": "tomato", + "inline": [ + "echo tomato > tomato.txt" + ] + } + }, + { + "shell-local": { + "only": [ + "sources.file.chocolate" + ], + "inline": [ + "echo unnamed > unnamed.txt" + ] + } + } + ] + } +} diff --git a/command/test-fixtures/hcl-inspect-with-sensitive-vars/expected-output.txt b/command/test-fixtures/hcl-inspect-with-sensitive-vars/expected-output.txt new file mode 100644 index 000000000..3d13bb4ac --- /dev/null +++ b/command/test-fixtures/hcl-inspect-with-sensitive-vars/expected-output.txt @@ -0,0 +1,16 @@ +Packer Inspect: HCL2 mode + +> input-variables: + +var.not_sensitive: "I am soooo not sensitive" +var.not_sensitive_unknown: "" +var.sensitive: "" +var.sensitive_array: "[\n \"\",\n \"\",\n]" +var.sensitive_tags: "{\n \"first_key\" = \"\"\n \"second_key\" = \"\"\n}" +var.sensitive_unknown: "" + +> local-variables: + + +> builds: + diff --git a/command/test-fixtures/hcl-inspect-with-sensitive-vars/vars.pkr.hcl b/command/test-fixtures/hcl-inspect-with-sensitive-vars/vars.pkr.hcl new file mode 100644 index 000000000..e3bd983c7 --- /dev/null +++ b/command/test-fixtures/hcl-inspect-with-sensitive-vars/vars.pkr.hcl @@ -0,0 +1,29 @@ + +variable "not_sensitive" { + default = "I am soooo not sensitive" +} + +variable "not_sensitive_unknown" { +} + +variable "sensitive" { + default = "I am soooo sensitive" + sensitive = true +} + +variable "sensitive_array" { + default = ["Im supersensitive", "me too !!!!"] + sensitive = true +} + +variable "sensitive_tags" { + default = { + first_key = "this-is-mega-sensitive" + second_key = "this-is-also-sensitive" + } + sensitive = true +} + +variable "sensitive_unknown" { + sensitive = true +} diff --git a/common/extra_iso_config.go b/common/extra_iso_config.go new file mode 100644 index 000000000..56665bbc3 --- /dev/null +++ b/common/extra_iso_config.go @@ -0,0 +1,99 @@ +//go:generate struct-markdown + +package common + +import ( + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/hashicorp/packer/template/interpolate" +) + +// An iso (CD) containing custom files can be made available for your build. +// +// By default, no extra CD will be attached. All files listed in this setting +// get placed into the root directory of the CD and the CD is attached as the +// second CD device. +// +// This config exists to work around modern operating systems that have no +// way to mount floppy disks, which was our previous go-to for adding files at +// boot time. +type CDConfig struct { + // A list of files to place onto a CD that is attached when the VM is + // booted. This can include either files or directories; any directories + // will be copied onto the CD recursively, preserving directory structure + // hierarchy. Symlinks will have the link's target copied into the directory + // tree on the CD where the symlink was. File globbing is allowed. + // + // Usage example (JSON): + // + // ```json + // "cd_files": ["./somedirectory/meta-data", "./somedirectory/user-data"], + // "cd_label": "cidata", + // ``` + // + // Usage example (HCL): + // + // ```hcl + // cd_files = ["./somedirectory/meta-data", "./somedirectory/user-data"] + // cd_label = "cidata" + // ``` + // + // The above will create a CD with two files, user-data and meta-data in the + // CD root. This specific example is how you would create a CD that can be + // used for an Ubuntu 20.04 autoinstall. + // + // Since globbing is also supported, + // + // ```hcl + // cd_files = ["./somedirectory/*"] + // cd_label = "cidata" + // ``` + // + // Would also be an acceptable way to define the above cd. The difference + // between providing the directory with or without the glob is whether the + // directory itself or its contents will be at the CD root. + // + // Use of this option assumes that you have a command line tool installed + // that can handle the iso creation. Packer will use one of the following + // tools: + // + // * xorriso + // * mkisofs + // * hdiutil (normally found in macOS) + // * oscdimg (normally found in Windows as part of the Windows ADK) + CDFiles []string `mapstructure:"cd_files"` + CDLabel string `mapstructure:"cd_label"` +} + +func (c *CDConfig) Prepare(ctx *interpolate.Context) []error { + var errs []error + var err error + + if c.CDFiles == nil { + c.CDFiles = make([]string, 0) + } + + // Create new file list based on globbing. + var files []string + for _, path := range c.CDFiles { + if strings.ContainsAny(path, "*?[") { + var globbedFiles []string + globbedFiles, err = filepath.Glob(path) + if len(globbedFiles) > 0 { + files = append(files, globbedFiles...) + } + } else { + _, err = os.Stat(path) + files = append(files, path) + } + if err != nil { + errs = append(errs, fmt.Errorf("Bad CD disk file '%s': %s", path, err)) + } + c.CDFiles = files + } + + return errs +} diff --git a/common/extra_iso_config_test.go b/common/extra_iso_config_test.go new file mode 100644 index 000000000..bcc555976 --- /dev/null +++ b/common/extra_iso_config_test.go @@ -0,0 +1,73 @@ +package common + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestCDPrepare(t *testing.T) { + type testCases struct { + CDConfig CDConfig + ErrExpected bool + Reason string + ExpectedCDFiles []string + } + tcs := []testCases{ + { + CDConfig: CDConfig{}, + ErrExpected: false, + Reason: "TestNilCD: nil CD array should not fail", + ExpectedCDFiles: []string{}, + }, + { + CDConfig: CDConfig{CDFiles: make([]string, 0)}, + ErrExpected: false, + Reason: "TestEmptyArrayCD: empty CD array should never fail", + ExpectedCDFiles: []string{}, + }, + { + CDConfig: CDConfig{CDFiles: []string{"extra_iso_config.go"}}, + ErrExpected: false, + Reason: "TestExistingCDFile: array with existing CD should not fail", + ExpectedCDFiles: []string{"extra_iso_config.go"}, + }, + { + CDConfig: CDConfig{CDFiles: []string{"does_not_exist.foo"}}, + ErrExpected: true, + Reason: "TestNonExistingCDFile: array with non existing CD should return errors", + ExpectedCDFiles: []string{"does_not_exist.foo"}, + }, + { + CDConfig: CDConfig{CDFiles: []string{"extra_iso_config*"}}, + ErrExpected: false, + Reason: "TestGlobbingCDFile: Glob should work", + ExpectedCDFiles: []string{"extra_iso_config.go", "extra_iso_config_test.go"}, + }, + } + for _, tc := range tcs { + c := tc.CDConfig + errs := c.Prepare(nil) + if (len(errs) != 0) != tc.ErrExpected { + t.Fatal(tc.Reason) + } + assert.Equal(t, c.CDFiles, tc.ExpectedCDFiles) + } +} + +func TestMultiErrorCDFiles(t *testing.T) { + c := CDConfig{ + CDFiles: []string{"extra_iso_config.foo", "extra_iso_config.go", + "extra_iso_config.bar", "extra_iso_config_test.go", "extra_iso_config.baz"}, + } + + errs := c.Prepare(nil) + if len(errs) == 0 { + t.Fatal("array with non existing CD should return errors") + } + + expectedErrors := 3 + if count := len(errs); count != expectedErrors { + t.Fatalf("array with %v non existing CD should return %v errors but it is returning %v", expectedErrors, expectedErrors, count) + } +} diff --git a/common/http_config.go b/common/http_config.go index b161e6888..4977b68ce 100644 --- a/common/http_config.go +++ b/common/http_config.go @@ -34,6 +34,10 @@ type HTTPConfig struct { // This is the bind address for the HTTP server. Defaults to 0.0.0.0 so that // it will work with any network interface. HTTPAddress string `mapstructure:"http_bind_address"` + // This is the bind interface for the HTTP server. Defaults to the first + // interface with a non-loopback address. Either `http_bind_address` or + // `http_interface` can be specified. + HTTPInterface string `mapstructure:"http_interface" undocumented:"true"` } func (c *HTTPConfig) Prepare(ctx *interpolate.Context) []error { @@ -57,5 +61,10 @@ func (c *HTTPConfig) Prepare(ctx *interpolate.Context) []error { errors.New("http_port_min must be less than http_port_max")) } + if c.HTTPInterface != "" && c.HTTPAddress == "0.0.0.0" { + errs = append(errs, + errors.New("either http_interface of http_bind_address can be specified")) + } + return errs } diff --git a/common/step_create_cdrom.go b/common/step_create_cdrom.go new file mode 100644 index 000000000..3a350cce9 --- /dev/null +++ b/common/step_create_cdrom.go @@ -0,0 +1,294 @@ +package common + +import ( + "context" + "fmt" + "io" + "log" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + + "github.com/hashicorp/packer/helper/builder/localexec" + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" + "github.com/hashicorp/packer/packer/tmp" +) + +// StepCreateCD will create a CD disk with the given files. +type StepCreateCD struct { + // Files can be either files or directories. Any files provided here will + // be written to the root of the CD. Directories will be written to the + // root of the CD as well, but will retain their subdirectory structure. + Files []string + Label string + + CDPath string + + filesAdded map[string]bool +} + +func (s *StepCreateCD) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction { + if len(s.Files) == 0 { + log.Println("No CD files specified. CD disk will not be made.") + return multistep.ActionContinue + } + + ui := state.Get("ui").(packer.Ui) + ui.Say("Creating CD disk...") + + if s.Label == "" { + s.Label = "packer" + } else { + log.Printf("CD label is set to %s", s.Label) + } + + // Track what files are added. Used for testing step. + s.filesAdded = make(map[string]bool) + + // Create a temporary file to be our CD drive + CDF, err := tmp.File("packer*.iso") + // Set the path so we can remove it later + CDPath := CDF.Name() + CDF.Close() + os.Remove(CDPath) + if err != nil { + state.Put("error", + fmt.Errorf("Error creating temporary file for CD: %s", err)) + return multistep.ActionHalt + } + + log.Printf("CD path: %s", CDPath) + s.CDPath = CDPath + + // Consolidate all files provided into a single directory to become our + // "root" directory. + rootFolder, err := tmp.Dir("packer_to_cdrom") + if err != nil { + state.Put("error", + fmt.Errorf("Error creating temporary file for CD: %s", err)) + return multistep.ActionHalt + } + + for _, toAdd := range s.Files { + err = s.AddFile(rootFolder, toAdd) + if err != nil { + state.Put("error", + fmt.Errorf("Error creating temporary file for CD: %s", err)) + return multistep.ActionHalt + } + } + + cmd, err := retrieveCDISOCreationCommand(s.Label, rootFolder, CDPath) + if err != nil { + state.Put("error", err) + return multistep.ActionHalt + } + + err = localexec.RunAndStream(cmd, ui, []string{}) + if err != nil { + state.Put("error", err) + return multistep.ActionHalt + } + + ui.Message("Done copying paths from CD_dirs") + + // Set the path to the CD so it can be used later + state.Put("cd_path", CDPath) + + if err != nil { + state.Put("error", err) + return multistep.ActionHalt + } + + return multistep.ActionContinue +} + +func (s *StepCreateCD) Cleanup(multistep.StateBag) { + if s.CDPath != "" { + log.Printf("Deleting CD disk: %s", s.CDPath) + os.Remove(s.CDPath) + } +} + +type cdISOCreationCommand struct { + Name string + Command func(path string, label string, source string, dest string) *exec.Cmd +} + +var supportedCDISOCreationCommands []cdISOCreationCommand = []cdISOCreationCommand{ + { + "xorriso", func(path string, label string, source string, dest string) *exec.Cmd { + return exec.Command( + path, + "-as", "genisoimage", + "-rock", + "-joliet", + "-volid", label, + "-output", dest, + source) + }, + }, + { + "mkisofs", func(path string, label string, source string, dest string) *exec.Cmd { + return exec.Command( + path, + "-joliet", + "-volid", label, + "-o", dest, + source) + }, + }, + { + "hdiutil", func(path string, label string, source string, dest string) *exec.Cmd { + return exec.Command( + path, + "makehybrid", + "-o", dest, + "-hfs", + "-joliet", + "-iso", + "-default-volume-name", label, + source) + }, + }, + { + "oscdimg", func(path string, label string, source string, dest string) *exec.Cmd { + return exec.Command( + path, + "-j1", + "-o", + "-m", + "-l"+label, + source, + dest) + }, + }, +} + +func isCygwinExecutable(path string) bool { + return runtime.GOOS == "windows" && strings.Contains(path, "\\usr\\bin\\") +} + +func toCygwinPath(path string) (string, error) { + c := exec.Command("cygpath", path) + cygwinPath, err := c.Output() + return strings.TrimSpace(string(cygwinPath)), err +} + +func retrieveCDISOCreationCommand(label string, source string, dest string) (*exec.Cmd, error) { + for _, c := range supportedCDISOCreationCommands { + path, err := exec.LookPath(c.Name) + if err != nil { + continue + } + // if we are running a cygwin/msys2 executable we must convert the + // native win32 path to a cygwin/msys2/unix style path. + if isCygwinExecutable(path) { + source, err = toCygwinPath(source) + if err != nil { + return nil, err + } + dest, err = toCygwinPath(dest) + if err != nil { + return nil, err + } + } + return c.Command(path, label, source, dest), nil + } + var commands = make([]string, 0, len(supportedCDISOCreationCommands)) + for _, c := range supportedCDISOCreationCommands { + commands = append(commands, c.Name) + } + return nil, fmt.Errorf( + "could not find a supported CD ISO creation command (the supported commands are: %s)", + strings.Join(commands, ", ")) +} + +func (s *StepCreateCD) AddFile(dst, src string) error { + finfo, err := os.Stat(src) + if err != nil { + return fmt.Errorf("Error adding path to CD: %s", err) + } + + // add a file + if !finfo.IsDir() { + inputF, err := os.Open(src) + if err != nil { + return err + } + defer inputF.Close() + + // Create a new file in the root directory + dest, err := os.Create(filepath.Join(dst, finfo.Name())) + if err != nil { + return fmt.Errorf("Error opening file for copy %s to CD root", src) + } + defer dest.Close() + nBytes, err := io.Copy(dest, inputF) + if err != nil { + return fmt.Errorf("Error copying %s to CD root", src) + } + s.filesAdded[src] = true + log.Printf("Wrote %d bytes to %s", nBytes, finfo.Name()) + return err + } + + // file is a directory, so we need to parse the filename into a path to + // discard and a basename + discardPath, _ := filepath.Split(src) + + // Add a directory and its subdirectories + visit := func(pathname string, fi os.FileInfo, err error) error { + if err != nil { + return err + } + + // Clean up pathing so that we preserve the base directory provided by + // the user but not the local pathing to that directory. + allDirs, base := filepath.Split(pathname) + intermediaryDirs := strings.Replace(allDirs, discardPath, "", 1) + + dstPath := filepath.Join(dst, base) + if intermediaryDirs != "" { + dstPath = filepath.Join(dst, intermediaryDirs, base) + } + + // add a file + if !fi.IsDir() { + inputF, err := os.Open(pathname) + if err != nil { + return err + } + defer inputF.Close() + + fileDst, err := os.Create(dstPath) + if err != nil { + return fmt.Errorf("Error opening file %s on CD: %s", dstPath, err) + } + defer fileDst.Close() + nBytes, err := io.Copy(fileDst, inputF) + if err != nil { + return fmt.Errorf("Error copying %s to CD: %s", dstPath, err) + } + s.filesAdded[dstPath] = true + log.Printf("Wrote %d bytes to %s", nBytes, dstPath) + return err + } + + if fi.Mode().IsDir() { + // create the directory on the CD, continue walk. + err := os.MkdirAll(dstPath, fi.Mode()) + if err != nil { + err = fmt.Errorf("error creating new directory %s: %s", + dstPath, err) + } + return err + } + return err + } + + return filepath.Walk(src, visit) +} diff --git a/common/step_create_cdrom_test.go b/common/step_create_cdrom_test.go new file mode 100644 index 000000000..bdcc83535 --- /dev/null +++ b/common/step_create_cdrom_test.go @@ -0,0 +1,119 @@ +package common + +import ( + "bytes" + "context" + "io/ioutil" + "os" + "path" + "testing" + + "github.com/hashicorp/packer/helper/multistep" + "github.com/hashicorp/packer/packer" +) + +func TestStepCreateCD_Impl(t *testing.T) { + var raw interface{} + raw = new(StepCreateCD) + if _, ok := raw.(multistep.Step); !ok { + t.Fatalf("StepCreateCD should be a step") + } +} + +func testStepCreateCDState(t *testing.T) multistep.StateBag { + state := new(multistep.BasicStateBag) + state.Put("ui", &packer.BasicUi{ + Reader: new(bytes.Buffer), + Writer: new(bytes.Buffer), + }) + return state +} + +func TestStepCreateCD(t *testing.T) { + if os.Getenv("PACKER_ACC") == "" { + t.Skip("This test is only run with PACKER_ACC=1 due to the requirement of access to the disk management binaries.") + } + state := testStepCreateCDState(t) + step := new(StepCreateCD) + + dir, err := ioutil.TempDir("", "packer") + if err != nil { + t.Fatalf("err: %s", err) + } + defer os.RemoveAll(dir) + + files := make([]string, 3) + + tempFileNames := []string{"test_cd_roms.tmp", "test cd files.tmp", + "Test-Test-Test5.tmp"} + for i, fname := range tempFileNames { + files[i] = path.Join(dir, fname) + + _, err := os.Create(files[i]) + if err != nil { + t.Fatalf("err: %s", err) + } + } + + step.Files = files + action := step.Run(context.Background(), state) + + if err, ok := state.GetOk("error"); ok { + t.Fatalf("state should be ok for %v: %s", step.Files, err) + } + + if action != multistep.ActionContinue { + t.Fatalf("bad action: %#v for %v", action, step.Files) + } + + CD_path := state.Get("cd_path").(string) + + if _, err := os.Stat(CD_path); err != nil { + t.Fatalf("file not found: %s for %v", CD_path, step.Files) + } + + if len(step.filesAdded) != 3 { + t.Fatalf("expected 3 files, found %d for %v", len(step.filesAdded), step.Files) + } + + step.Cleanup(state) + + if _, err := os.Stat(CD_path); err == nil { + t.Fatalf("file found: %s for %v", CD_path, step.Files) + } +} + +func TestStepCreateCD_missing(t *testing.T) { + if os.Getenv("PACKER_ACC") == "" { + t.Skip("This test is only run with PACKER_ACC=1 due to the requirement of access to the disk management binaries.") + } + state := testStepCreateCDState(t) + step := new(StepCreateCD) + + dir, err := ioutil.TempDir("", "packer") + if err != nil { + t.Fatalf("err: %s", err) + } + defer os.RemoveAll(dir) + + expected := 0 + + step.Files = []string{"missing file.tmp"} + if action := step.Run(context.Background(), state); action != multistep.ActionHalt { + t.Fatalf("bad action: %#v for %v", action, step.Files) + } + + if _, ok := state.GetOk("error"); !ok { + t.Fatalf("state should not be ok for %v", step.Files) + } + + CD_path := state.Get("cd_path") + + if CD_path != nil { + t.Fatalf("CD_path is not nil for %v", step.Files) + } + + if len(step.filesAdded) != expected { + t.Fatalf("expected %d, found %d for %v", expected, len(step.filesAdded), step.Files) + } +} diff --git a/common/step_download_test.go b/common/step_download_test.go index fa0e690d9..26cd026e9 100644 --- a/common/step_download_test.go +++ b/common/step_download_test.go @@ -245,6 +245,7 @@ func TestStepDownload_download(t *testing.T) { ui := &packer.BasicUi{ Reader: new(bytes.Buffer), Writer: new(bytes.Buffer), + PB: &packer.NoopProgressTracker{}, } dir := createTempDir(t) diff --git a/common/step_output_dir_test.go b/common/step_output_dir_test.go index 197977151..7a5f58d95 100644 --- a/common/step_output_dir_test.go +++ b/common/step_output_dir_test.go @@ -16,6 +16,7 @@ func testState(t *testing.T) multistep.StateBag { state.Put("ui", &packer.BasicUi{ Reader: new(bytes.Buffer), Writer: new(bytes.Buffer), + PB: &packer.NoopProgressTracker{}, }) return state } diff --git a/config.go b/config.go index 358014bc2..5ca68a193 100644 --- a/config.go +++ b/config.go @@ -15,7 +15,6 @@ import ( "github.com/hashicorp/packer/command" "github.com/hashicorp/packer/packer" "github.com/hashicorp/packer/packer/plugin" - "github.com/kardianos/osext" ) // PACKERSPACE is used to represent the spaces that separate args for a command @@ -131,7 +130,7 @@ func (c *config) Discover() error { } // Next, look in the same directory as the executable. - exePath, err := osext.Executable() + exePath, err := os.Executable() if err != nil { log.Printf("[ERR] Error loading exe directory: %s", err) } else { @@ -311,7 +310,7 @@ func (c *config) discoverSingle(glob string) (map[string]string, error) { func (c *config) discoverInternalComponents() error { // Get the packer binary path - packerPath, err := osext.Executable() + packerPath, err := os.Executable() if err != nil { log.Printf("[ERR] Error loading exe directory: %s", err) return err @@ -373,7 +372,7 @@ func (c *config) pluginClient(path string) *plugin.Client { // If that doesn't work, look for it in the same directory // as the `packer` executable (us). log.Printf("Plugin could not be found at %s (%v). Checking same directory as executable.", originalPath, err) - exePath, err := osext.Executable() + exePath, err := os.Executable() if err != nil { log.Printf("Couldn't get current exe path: %s", err) } else { diff --git a/go.mod b/go.mod index ccf98e851..fa927a09a 100644 --- a/go.mod +++ b/go.mod @@ -21,18 +21,15 @@ require ( github.com/antchfx/xquery v0.0.0-20170730121040-eb8c3c172607 // indirect github.com/approvals/go-approval-tests v0.0.0-20160714161514-ad96e53bea43 github.com/armon/go-metrics v0.0.0-20190430140413-ec5e00d3c878 // indirect - github.com/aws/aws-sdk-go v1.30.8 + github.com/aws/aws-sdk-go v1.34.26 github.com/biogo/hts v0.0.0-20160420073057-50da7d4131a3 github.com/c2h5oh/datasize v0.0.0-20200112174442-28bbd4740fee github.com/cheggaaa/pb v1.0.27 github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e - github.com/creack/goselect v0.1.0 // indirect github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/digitalocean/go-libvirt v0.0.0-20190626172931-4d226dd6c437 // indirect github.com/digitalocean/go-qemu v0.0.0-20181112162955-dd7bb9c771b8 github.com/digitalocean/godo v1.11.1 - github.com/docker/docker v0.0.0-20180422163414-57142e89befe // indirect - github.com/dustin/go-humanize v1.0.0 // indirect github.com/dylanmei/iso8601 v0.1.0 // indirect github.com/dylanmei/winrmtest v0.0.0-20170819153634-c2fbb09e6c08 github.com/exoscale/egoscale v0.18.1 @@ -52,14 +49,14 @@ require ( github.com/gophercloud/gophercloud v0.12.0 github.com/gophercloud/utils v0.0.0-20200508015959-b0167b94122c github.com/gopherjs/gopherjs v0.0.0-20181103185306-d547d1d9531e // indirect - github.com/gorilla/websocket v0.0.0-20170319172727-a91eba7f9777 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.1.0 github.com/hako/durafmt v0.0.0-20200710122514-c0fb7b4da026 + github.com/hashicorp/aws-sdk-go-base v0.6.0 github.com/hashicorp/consul/api v1.4.0 github.com/hashicorp/errwrap v1.0.0 github.com/hashicorp/go-checkpoint v0.0.0-20171009173528-1545e56e46de github.com/hashicorp/go-cleanhttp v0.5.1 - github.com/hashicorp/go-cty-funcs v0.0.0-20200520133146-0d04eb807361 + github.com/hashicorp/go-cty-funcs v0.0.0-20200930094925-2721b1e36840 github.com/hashicorp/go-getter/gcs/v2 v2.0.0-20200604122502-a6995fa1edad github.com/hashicorp/go-getter/s3/v2 v2.0.0-20200604122502-a6995fa1edad github.com/hashicorp/go-getter/v2 v2.0.0-20200604122502-a6995fa1edad @@ -81,7 +78,7 @@ require ( github.com/joyent/triton-go v0.0.0-20180628001255-830d2b111e62 github.com/json-iterator/go v1.1.6 // indirect github.com/jtolds/gls v4.2.1+incompatible // indirect - github.com/kardianos/osext v0.0.0-20170510131534-ae77be60afb1 + github.com/kardianos/osext v0.0.0-20170510131534-ae77be60afb1 // indirect github.com/klauspost/compress v0.0.0-20160131094358-f86d2e6d8a77 // indirect github.com/klauspost/cpuid v0.0.0-20160106104451-349c67577817 // indirect github.com/klauspost/crc32 v0.0.0-20160114101742-999f3125931f // indirect @@ -103,8 +100,6 @@ require ( github.com/mitchellh/reflectwalk v1.0.0 github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.1 // indirect - github.com/moul/anonuuid v0.0.0-20160222162117-609b752a95ef // indirect - github.com/moul/gotty-client v0.0.0-20180327180212-b26a57ebc215 // indirect github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d // indirect github.com/olekukonko/tablewriter v0.0.0-20180105111133-96aac992fc8b github.com/oracle/oci-go-sdk v18.0.0+incompatible @@ -115,9 +110,8 @@ require ( github.com/pkg/sftp v0.0.0-20160118190721-e84cc8c755ca github.com/posener/complete v1.2.3 github.com/profitbricks/profitbricks-sdk-go v4.0.2+incompatible - github.com/renstrom/fuzzysearch v0.0.0-20160331204855-2d205ac6ec17 // indirect github.com/satori/go.uuid v1.2.0 // indirect - github.com/scaleway/scaleway-cli v0.0.0-20180921094345-7b12c9699d70 + github.com/scaleway/scaleway-sdk-go v1.0.0-beta.6.0.20200903143645-c0ce17a0443d github.com/shirou/gopsutil v2.18.12+incompatible github.com/shirou/w32 v0.0.0-20160930032740-bb4de0191aa4 // indirect github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d // indirect diff --git a/go.sum b/go.sum index 823925a32..0b3ca6a15 100644 --- a/go.sum +++ b/go.sum @@ -114,6 +114,9 @@ github.com/aws/aws-sdk-go v1.15.78/go.mod h1:E3/ieXAlvM0XWO57iftYVDLLvQ824smPP3A github.com/aws/aws-sdk-go v1.16.22/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/aws/aws-sdk-go v1.30.8 h1:4BHbh8K3qKmcnAgToZ2LShldRF9inoqIBccpCLNCy3I= github.com/aws/aws-sdk-go v1.30.8/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0= +github.com/aws/aws-sdk-go v1.31.9/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0= +github.com/aws/aws-sdk-go v1.34.26 h1:tw4nsSfGvCDnXt2xPe8NkxIrDui+asAWinMknPLEf80= +github.com/aws/aws-sdk-go v1.34.26/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973 h1:xJ4a3vCFaGF/jqvzLMYoU8P317H5OQ+Via4RmuPwCS0= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d h1:xDfNPAt8lFiC1UJrqV3uuy861HCTo708pDMbjHHdCas= @@ -143,8 +146,6 @@ github.com/circonus-labs/circonusllhist v0.1.3/go.mod h1:kMXHVDlOchFAehlya5ePtbp github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f h1:WBZRG4aNOuI15bLRrCgN8fCq8E5Xuty6jGbmSNEvSsU= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= -github.com/creack/goselect v0.1.0 h1:4QiXIhcpSQF50XGaBsFzesjwX/1qOY5bOveQPmN9CXY= -github.com/creack/goselect v0.1.0/go.mod h1:gHrIcH/9UZDn2qgeTUeW5K9eZsVYCH6/60J/FHysWyE= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -161,10 +162,6 @@ github.com/dimchansky/utfbom v1.1.0 h1:FcM3g+nofKgUteL8dm/UpdRXNC9KmADgTpLKsu0TR github.com/dimchansky/utfbom v1.1.0/go.mod h1:rO41eb7gLfo8SF1jd9F8HplJm1Fewwi4mQvIirEdv+8= github.com/dnaeon/go-vcr v1.0.1 h1:r8L/HqC0Hje5AXMu1ooW8oyQyOFv4GxqpL0nRP7SLLY= github.com/dnaeon/go-vcr v1.0.1/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E= -github.com/docker/docker v0.0.0-20180422163414-57142e89befe h1:VW8TnWi0CZgg7oCv0wH6evNwkzcJg/emnw4HrVIWws4= -github.com/docker/docker v0.0.0-20180422163414-57142e89befe/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= -github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= -github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dylanmei/iso8601 v0.1.0 h1:812NGQDBcqquTfH5Yeo7lwR0nzx/cKdsmf3qMjPURUI= github.com/dylanmei/iso8601 v0.1.0/go.mod h1:w9KhXSgIyROl1DefbMYIE7UVSIvELTbMrCfx+QkYnoQ= github.com/dylanmei/winrmtest v0.0.0-20170819153634-c2fbb09e6c08 h1:0bp6/GrNOrTDtSXe9YYGCwf8jp5Fb/b+4a6MTRm4qzY= @@ -282,12 +279,12 @@ github.com/gophercloud/utils v0.0.0-20200508015959-b0167b94122c h1:iawx2ojEQA7c+ github.com/gophercloud/utils v0.0.0-20200508015959-b0167b94122c/go.mod h1:ehWUbLQJPqS0Ep+CxeD559hsm9pthPXadJNKwZkp43w= github.com/gopherjs/gopherjs v0.0.0-20181103185306-d547d1d9531e h1:JKmoR8x90Iww1ks85zJ1lfDGgIiMDuIptTOhJq+zKyg= github.com/gopherjs/gopherjs v0.0.0-20181103185306-d547d1d9531e/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= -github.com/gorilla/websocket v0.0.0-20170319172727-a91eba7f9777 h1:JIM+OacoOJRU30xpjMf8sulYqjr0ViA3WDrTX6j/yDI= -github.com/gorilla/websocket v0.0.0-20170319172727-a91eba7f9777/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/grpc-ecosystem/go-grpc-middleware v1.1.0 h1:THDBEeQ9xZ8JEaCLyLQqXMMdRqNr0QAUJTIkQAUtFjg= github.com/grpc-ecosystem/go-grpc-middleware v1.1.0/go.mod h1:f5nM7jw/oeRSadq3xCzHAvxcr8HZnzsqU6ILg/0NiiE= github.com/hako/durafmt v0.0.0-20200710122514-c0fb7b4da026 h1:BpJ2o0OR5FV7vrkDYfXYVJQeMNWa8RhklZOpW2ITAIQ= github.com/hako/durafmt v0.0.0-20200710122514-c0fb7b4da026/go.mod h1:5Scbynm8dF1XAPwIwkGPqzkM/shndPm79Jd1003hTjE= +github.com/hashicorp/aws-sdk-go-base v0.6.0 h1:qmUbzM36msbBF59YctwuO5w0M2oNXjlilgKpnEhx1uw= +github.com/hashicorp/aws-sdk-go-base v0.6.0/go.mod h1:2fRjWDv3jJBeN6mVWFHV6hFTNeFBx2gpDLQaZNxUVAY= github.com/hashicorp/consul/api v1.4.0 h1:jfESivXnO5uLdH650JU/6AnjRoHrLhULq0FnC3Kp9EY= github.com/hashicorp/consul/api v1.4.0/go.mod h1:xc8u05kyMa3Wjr9eEAsIAo3dg8+LywT5E/Cl7cNS5nU= github.com/hashicorp/consul/sdk v0.4.0 h1:zBtCfKJZcJDBvSCkQJch4ulp59m1rATFLKwNo/LYY30= @@ -300,8 +297,8 @@ github.com/hashicorp/go-cleanhttp v0.5.0 h1:wvCrVc9TjDls6+YGAF2hAifE1E5U1+b4tH6K github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.1 h1:dH3aiDG9Jvb5r5+bYHsikaOUIpcM0xvgMXVoDkXMzJM= github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= -github.com/hashicorp/go-cty-funcs v0.0.0-20200520133146-0d04eb807361 h1:qFuR7ZaMDC5xelTZeNwsJ90I4+4km7ACDdAP+2w84xI= -github.com/hashicorp/go-cty-funcs v0.0.0-20200520133146-0d04eb807361/go.mod h1:Abjk0jbRkDaNCzsRhOv2iDCofYpX1eVsjozoiK63qLA= +github.com/hashicorp/go-cty-funcs v0.0.0-20200930094925-2721b1e36840 h1:kgvybwEeu0SXktbB2y3uLHX9lklLo+nzUwh59A3jzQc= +github.com/hashicorp/go-cty-funcs v0.0.0-20200930094925-2721b1e36840/go.mod h1:Abjk0jbRkDaNCzsRhOv2iDCofYpX1eVsjozoiK63qLA= github.com/hashicorp/go-getter v1.4.1 h1:3A2Mh8smGFcf5M+gmcv898mZdrxpseik45IpcyISLsA= github.com/hashicorp/go-getter v1.4.1/go.mod h1:7qxyCd8rBfcShwsvxgIguu4KbS3l8bUCwg2Umn7RjeY= github.com/hashicorp/go-getter/gcs/v2 v2.0.0-20200604122502-a6995fa1edad h1:QPLyAkuTS5Uf9uqJQxCTDDFgmD+gVAzSvqkGb3h+7oQ= @@ -362,8 +359,6 @@ github.com/hashicorp/golang-lru v0.5.3 h1:YPkqC67at8FYaadspW/6uE0COsBxS2656RLEr8 github.com/hashicorp/golang-lru v0.5.3/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= -github.com/hashicorp/hcl/v2 v2.3.0 h1:iRly8YaMwTBAKhn1Ybk7VSdzbnopghktCD031P8ggUE= -github.com/hashicorp/hcl/v2 v2.3.0/go.mod h1:d+FwDBbOLvpAM3Z6J7gPj/VoAGkNe/gm352ZhjJ/Zv8= github.com/hashicorp/hcl/v2 v2.6.0 h1:3krZOfGY6SziUXa6H9PJU6TyohHn7I+ARYnhbeNBz+o= github.com/hashicorp/hcl/v2 v2.6.0/go.mod h1:bQTN5mpo+jewjJgh8jr0JUguIi7qPHUF6yIfAEN3jqY= github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64= @@ -503,10 +498,6 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/moul/anonuuid v0.0.0-20160222162117-609b752a95ef h1:E/seV1Rtsnr2juBw1Dfz4iDPT3/5s1H/BATx+ePmSyo= -github.com/moul/anonuuid v0.0.0-20160222162117-609b752a95ef/go.mod h1:LgKrp0Iss/BVwquptq4eIe6HPr0s3t1WHT5x0qOh14U= -github.com/moul/gotty-client v0.0.0-20180327180212-b26a57ebc215 h1:y6FZWUBBt1iPmJyGbGza3ncvVBMKzgd32oFChRZR7Do= -github.com/moul/gotty-client v0.0.0-20180327180212-b26a57ebc215/go.mod h1:CxM/JGtpRrEPve5H04IhxJrGhxgwxMc6jSP2T4YD60w= github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d h1:VhgPp6v9qf9Agr/56bj7Y/xa04UccTW04VP0Qed4vnQ= github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d/go.mod h1:YUTz3bUH2ZwIWBy3CJBeOBEugqcmXREj14T+iG/4k4U= github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= @@ -550,8 +541,6 @@ github.com/prometheus/common v0.0.0-20181126121408-4724e9255275 h1:PnBWHBf+6L0jO github.com/prometheus/common v0.0.0-20181126121408-4724e9255275/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a h1:9a8MnZMP0X2nLJdBg+pBmGgkJlSaKC2KaQmTCk1XDtE= github.com/prometheus/procfs v0.0.0-20181204211112-1dc9a6cbc91a/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= -github.com/renstrom/fuzzysearch v0.0.0-20160331204855-2d205ac6ec17 h1:4qPms2txLWMLXKzqlnYSulKRS4cS9aYgPtAEpUelQok= -github.com/renstrom/fuzzysearch v0.0.0-20160331204855-2d205ac6ec17/go.mod h1:SAEjPB4voP88qmWJXI7mA5m15uNlEnuHLx4Eu2mPGpQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/ryanuber/columnize v2.1.0+incompatible h1:j1Wcmh8OrK4Q7GXY+V7SVSY8nUWQxHW5TkBe7YUl+2s= @@ -560,8 +549,8 @@ github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkB github.com/ryanuber/go-glob v1.0.0/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIHxIXzX/Yc= github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= -github.com/scaleway/scaleway-cli v0.0.0-20180921094345-7b12c9699d70 h1:DaqC32ZwOuO4ctgg9qAdKnlQxwFPkKmCOEqwSNwYy7c= -github.com/scaleway/scaleway-cli v0.0.0-20180921094345-7b12c9699d70/go.mod h1:XjlXWPd6VONhsRSEuzGkV8mzRpH7ou1cdLV7IKJk96s= +github.com/scaleway/scaleway-sdk-go v1.0.0-beta.6.0.20200903143645-c0ce17a0443d h1:pK33AoOAlzj6gJs/V1vi2Ouj2u1Ww84pREwxFi1oxkM= +github.com/scaleway/scaleway-sdk-go v1.0.0-beta.6.0.20200903143645-c0ce17a0443d/go.mod h1:CJJ5VAbozOl0yEw7nHB9+7BXTJbIn6h7W+f6Gau5IP8= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 h1:nn5Wsu0esKSJiIVhscUtVbo7ada43DJhG55ua/hjS5I= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= diff --git a/hcl2template/functions.go b/hcl2template/functions.go index eca271e9c..2c4b1396a 100644 --- a/hcl2template/functions.go +++ b/hcl2template/functions.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/hashicorp/go-cty-funcs/cidr" + "github.com/hashicorp/go-cty-funcs/collection" "github.com/hashicorp/go-cty-funcs/crypto" "github.com/hashicorp/go-cty-funcs/encoding" "github.com/hashicorp/go-cty-funcs/filesystem" @@ -41,7 +42,7 @@ func Functions(basedir string) map[string]function.Function { "cidrnetmask": cidr.NetmaskFunc, "cidrsubnet": cidr.SubnetFunc, "cidrsubnets": cidr.SubnetsFunc, - "coalesce": stdlib.CoalesceFunc, + "coalesce": collection.CoalesceFunc, "coalescelist": stdlib.CoalesceListFunc, "compact": stdlib.CompactFunc, "concat": stdlib.ConcatFunc, diff --git a/hcl2template/parser.go b/hcl2template/parser.go index 776d6abec..7959fab20 100644 --- a/hcl2template/parser.go +++ b/hcl2template/parser.go @@ -9,6 +9,7 @@ import ( "github.com/hashicorp/hcl/v2/ext/dynblock" "github.com/hashicorp/hcl/v2/hclparse" "github.com/hashicorp/packer/packer" + "github.com/zclconf/go-cty/cty" ) const ( @@ -177,6 +178,19 @@ func (cfg *PackerConfig) Initialize() hcl.Diagnostics { diags = append(diags, moreDiags...) diags = append(diags, cfg.evaluateLocalVariables(cfg.LocalBlocks)...) + for _, variable := range cfg.InputVariables { + if !variable.Sensitive { + continue + } + value, _ := variable.Value() + _ = cty.Walk(value, func(_ cty.Path, nested cty.Value) (bool, error) { + if nested.IsWhollyKnown() && !nested.IsNull() && nested.Type().Equals(cty.String) { + packer.LogSecretFilter.Set(nested.AsString()) + } + return true, nil + }) + } + // decode the actual content for _, file := range cfg.files { diags = append(diags, cfg.parser.decodeConfig(file, cfg)...) diff --git a/hcl2template/testdata/build/basic.pkr.hcl b/hcl2template/testdata/build/basic.pkr.hcl index 819efde70..6b6510b7b 100644 --- a/hcl2template/testdata/build/basic.pkr.hcl +++ b/hcl2template/testdata/build/basic.pkr.hcl @@ -7,7 +7,7 @@ build { ] provisioner "shell" { - string = "string" + string = coalesce(null, "", "string") int = "${41 + 1}" int64 = "${42 + 1}" bool = "true" diff --git a/helper/communicator/config.go b/helper/communicator/config.go index 16587f13c..caa26d725 100644 --- a/helper/communicator/config.go +++ b/helper/communicator/config.go @@ -119,7 +119,8 @@ type SSH struct { // The time to wait for SSH to become available. Packer uses this to // determine when the machine has booted so this is usually quite long. // Example value: `10m`. - SSHTimeout time.Duration `mapstructure:"ssh_timeout"` + SSHTimeout time.Duration `mapstructure:"ssh_timeout"` + // Deprecated in favor of SSHTimeout SSHWaitTimeout time.Duration `mapstructure:"ssh_wait_timeout" undocumented:"true"` // If true, the local SSH agent will be used to authenticate connections to // the source instance. No temporary keypair will be created, and the diff --git a/helper/multistep/multistep.go b/helper/multistep/multistep.go index 6f0a198f8..a4629bacf 100644 --- a/helper/multistep/multistep.go +++ b/helper/multistep/multistep.go @@ -2,7 +2,10 @@ // discrete steps. package multistep -import "context" +import ( + "context" + "strconv" +) // A StepAction determines the next step to take regarding multi-step actions. type StepAction uint @@ -12,6 +15,18 @@ const ( ActionHalt ) +// Implement the stringer interface; useful for testing. +func (a StepAction) String() string { + switch a { + case ActionContinue: + return "ActionContinue" + case ActionHalt: + return "ActionHalt" + default: + return "Unexpected value: " + strconv.Itoa(int(a)) + } +} + // This is the key set in the state bag when using the basic runner to // signal that the step sequence was cancelled. const StateCancelled = "cancelled" diff --git a/main.go b/main.go index 8d4c5ee38..47f69d364 100644 --- a/main.go +++ b/main.go @@ -196,6 +196,7 @@ func wrappedMain() int { Reader: os.Stdin, Writer: os.Stdout, ErrorWriter: os.Stdout, + PB: &packer.NoopProgressTracker{}, } ui = basicUi if !inPlugin { @@ -211,6 +212,7 @@ func wrappedMain() int { fmt.Fprintf(os.Stderr, "No tty available: %s\n", err) } else { basicUi.TTY = TTY + basicUi.PB = &packer.UiProgressBar{} defer TTY.Close() } } diff --git a/packer/progressbar.go b/packer/progressbar.go index 3328ca9ce..97e781d74 100644 --- a/packer/progressbar.go +++ b/packer/progressbar.go @@ -15,25 +15,17 @@ func ProgressBarConfig(bar *pb.ProgressBar, prefix string) { bar.Prefix(prefix) } -var defaultUiProgressBar = &uiProgressBar{} - -// uiProgressBar is a self managed progress bar singleton. -// decorate your struct with a *uiProgressBar to -// give it TrackProgress capabilities. -// In TrackProgress if uiProgressBar is nil -// defaultUiProgressBar will be used as -// the progress bar. -type uiProgressBar struct { +// UiProgressBar is a progress bar compatible with go-getter used in our +// UI structs. +type UiProgressBar struct { lock sync.Mutex - pool *pb.Pool - - pbs int + pbs int } -func (p *uiProgressBar) TrackProgress(src string, currentSize, totalSize int64, stream io.ReadCloser) io.ReadCloser { +func (p *UiProgressBar) TrackProgress(src string, currentSize, totalSize int64, stream io.ReadCloser) io.ReadCloser { if p == nil { - return defaultUiProgressBar.TrackProgress(src, currentSize, totalSize, stream) + return stream } p.lock.Lock() defer p.lock.Unlock() diff --git a/packer/progressbar_solaris.go b/packer/progressbar_solaris.go index 75b40ad06..868037c38 100644 --- a/packer/progressbar_solaris.go +++ b/packer/progressbar_solaris.go @@ -1,3 +1,3 @@ package packer -type uiProgressBar = NoopProgressTracker +type UiProgressBar = NoopProgressTracker diff --git a/packer/progressbar_test.go b/packer/progressbar_test.go index 5039c48a9..40928d273 100644 --- a/packer/progressbar_test.go +++ b/packer/progressbar_test.go @@ -11,7 +11,7 @@ import ( // The following tests rarelly just happen. So we run them 100 times. func TestProgressTracking_open_close(t *testing.T) { - var bar *uiProgressBar + var bar *UiProgressBar tracker := bar.TrackProgress("1,", 1, 42, ioutil.NopCloser(nil)) tracker.Close() @@ -21,7 +21,7 @@ func TestProgressTracking_open_close(t *testing.T) { } func TestProgressTracking_multi_open_close(t *testing.T) { - var bar *uiProgressBar + var bar *UiProgressBar g := errgroup.Group{} for i := 0; i < 100; i++ { @@ -36,7 +36,7 @@ func TestProgressTracking_multi_open_close(t *testing.T) { } func TestProgressTracking_races(t *testing.T) { - var bar *uiProgressBar + var bar *UiProgressBar g := errgroup.Group{} for i := 0; i < 100; i++ { diff --git a/packer/rpc/post_processor.go b/packer/rpc/post_processor.go index 4b36f2dd4..00d492a0a 100644 --- a/packer/rpc/post_processor.go +++ b/packer/rpc/post_processor.go @@ -99,28 +99,42 @@ func (p *PostProcessorServer) PostProcess(streamId uint32, reply *PostProcessorP if err != nil { return NewBasicError(err) } - defer client.Close() if p.context == nil { p.context, p.contextCancel = context.WithCancel(context.Background()) } - streamId = 0 - artifactResult, keep, forceOverride, err := p.p.PostProcess(p.context, client.Ui(), client.Artifact()) - if err == nil && artifactResult != nil { - streamId = p.mux.NextId() - server := newServerWithMux(p.mux, streamId) - server.RegisterArtifact(artifactResult) - go server.Serve() - } - + artifact := client.Artifact() + artifactResult, keep, forceOverride, err := p.p.PostProcess(p.context, client.Ui(), artifact) *reply = PostProcessorProcessResponse{ Err: NewBasicError(err), Keep: keep, ForceOverride: forceOverride, - StreamId: streamId, + StreamId: 0, + } + if err != nil { + log.Printf("error: %v", err) + client.Close() + return nil } + if artifactResult != artifact { + // Sometimes, the artifact returned by PostProcess is the artifact from + // client.Artifact() and in that case we don't want to close client; + // otherwise the outcome is sort of undetermined. See [GH-9995] for a + // good test file. + defer client.Close() + } + + if artifactResult != nil { + streamId = p.mux.NextId() + reply.StreamId = streamId + server := newServerWithMux(p.mux, streamId) + if err := server.RegisterArtifact(artifactResult); err != nil { + return err + } + go server.Serve() + } return nil } diff --git a/packer/ui.go b/packer/ui.go index 5d8cb89ed..46bfbf235 100644 --- a/packer/ui.go +++ b/packer/ui.go @@ -40,11 +40,12 @@ type Ui interface { Message(string) Error(string) Machine(string, ...string) + // TrackProgress(src string, currentSize, totalSize int64, stream io.ReadCloser) (body io.ReadCloser) getter.ProgressTracker } type NoopUi struct { - NoopProgressTracker + PB NoopProgressTracker } var _ Ui = new(NoopUi) @@ -54,13 +55,16 @@ func (*NoopUi) Say(string) { return } func (*NoopUi) Message(string) { return } func (*NoopUi) Error(string) { return } func (*NoopUi) Machine(string, ...string) { return } +func (u *NoopUi) TrackProgress(src string, currentSize, totalSize int64, stream io.ReadCloser) io.ReadCloser { + return u.PB.TrackProgress(src, currentSize, totalSize, stream) +} // ColoredUi is a UI that is colored using terminal colors. type ColoredUi struct { Color UiColor ErrorColor UiColor Ui Ui - *uiProgressBar + PB getter.ProgressTracker } var _ Ui = new(ColoredUi) @@ -189,7 +193,7 @@ type BasicUi struct { l sync.Mutex interrupted bool TTY TTY - *uiProgressBar + PB getter.ProgressTracker } var _ Ui = new(BasicUi) @@ -304,11 +308,15 @@ func (rw *BasicUi) Machine(t string, args ...string) { log.Printf("machine readable: %s %#v", t, args) } +func (rw *BasicUi) TrackProgress(src string, currentSize, totalSize int64, stream io.ReadCloser) (body io.ReadCloser) { + return rw.PB.TrackProgress(src, currentSize, totalSize, stream) +} + // MachineReadableUi is a UI that only outputs machine-readable output // to the given Writer. type MachineReadableUi struct { Writer io.Writer - NoopProgressTracker + PB NoopProgressTracker } var _ Ui = new(MachineReadableUi) @@ -366,11 +374,15 @@ func (u *MachineReadableUi) Machine(category string, args ...string) { log.Printf("%d,%s,%s,%s\n", now.Unix(), target, category, argsString) } +func (u *MachineReadableUi) TrackProgress(src string, currentSize, totalSize int64, stream io.ReadCloser) (body io.ReadCloser) { + return u.PB.TrackProgress(src, currentSize, totalSize, stream) +} + // TimestampedUi is a UI that wraps another UI implementation and // prefixes each message with an RFC3339 timestamp type TimestampedUi struct { Ui Ui - *uiProgressBar + PB getter.ProgressTracker } var _ Ui = new(TimestampedUi) @@ -395,6 +407,10 @@ func (u *TimestampedUi) Machine(message string, args ...string) { u.Ui.Machine(message, args...) } +func (u *TimestampedUi) TrackProgress(src string, currentSize, totalSize int64, stream io.ReadCloser) (body io.ReadCloser) { + return u.Ui.TrackProgress(src, currentSize, totalSize, stream) +} + func (u *TimestampedUi) timestampLine(string string) string { return fmt.Sprintf("%v: %v", time.Now().Format(time.RFC3339), string) } @@ -404,7 +420,7 @@ func (u *TimestampedUi) timestampLine(string string) string { type SafeUi struct { Sem chan int Ui Ui - *uiProgressBar + PB getter.ProgressTracker } var _ Ui = new(SafeUi) @@ -440,3 +456,11 @@ func (u *SafeUi) Machine(t string, args ...string) { u.Ui.Machine(t, args...) <-u.Sem } + +func (u *SafeUi) TrackProgress(src string, currentSize, totalSize int64, stream io.ReadCloser) (body io.ReadCloser) { + u.Sem <- 1 + ret := u.Ui.TrackProgress(src, currentSize, totalSize, stream) + <-u.Sem + + return ret +} diff --git a/packer/ui_test.go b/packer/ui_test.go index bae2ca570..9684aaf34 100644 --- a/packer/ui_test.go +++ b/packer/ui_test.go @@ -49,7 +49,7 @@ func (tty *testTTY) ReadString() (string, error) { func TestColoredUi(t *testing.T) { bufferUi := testUi() - ui := &ColoredUi{UiColorYellow, UiColorRed, bufferUi, defaultUiProgressBar} + ui := &ColoredUi{UiColorYellow, UiColorRed, bufferUi, &UiProgressBar{}} if !ui.supportsColors() { t.Skip("skipping for ui without color support") @@ -81,7 +81,7 @@ func TestColoredUi(t *testing.T) { func TestColoredUi_noColorEnv(t *testing.T) { bufferUi := testUi() - ui := &ColoredUi{UiColorYellow, UiColorRed, bufferUi, defaultUiProgressBar} + ui := &ColoredUi{UiColorYellow, UiColorRed, bufferUi, &UiProgressBar{}} // Set the env var to get rid of the color oldenv := os.Getenv("PACKER_NO_COLOR") diff --git a/post-processor/amazon-import/post-processor.hcl2spec.go b/post-processor/amazon-import/post-processor.hcl2spec.go index b35ae92e5..9b144ea50 100644 --- a/post-processor/amazon-import/post-processor.hcl2spec.go +++ b/post-processor/amazon-import/post-processor.hcl2spec.go @@ -18,7 +18,9 @@ type FlatConfig struct { PackerUserVars map[string]string `mapstructure:"packer_user_variables" cty:"packer_user_variables" hcl:"packer_user_variables"` PackerSensitiveVars []string `mapstructure:"packer_sensitive_variables" cty:"packer_sensitive_variables" hcl:"packer_sensitive_variables"` AccessKey *string `mapstructure:"access_key" required:"true" cty:"access_key" hcl:"access_key"` + AssumeRole *common.FlatAssumeRoleConfig `mapstructure:"assume_role" required:"false" cty:"assume_role" hcl:"assume_role"` CustomEndpointEc2 *string `mapstructure:"custom_endpoint_ec2" required:"false" cty:"custom_endpoint_ec2" hcl:"custom_endpoint_ec2"` + CredsFilename *string `mapstructure:"shared_credentials_file" required:"false" cty:"shared_credentials_file" hcl:"shared_credentials_file"` DecodeAuthZMessages *bool `mapstructure:"decode_authorization_messages" required:"false" cty:"decode_authorization_messages" hcl:"decode_authorization_messages"` InsecureSkipTLSVerify *bool `mapstructure:"insecure_skip_tls_verify" required:"false" cty:"insecure_skip_tls_verify" hcl:"insecure_skip_tls_verify"` MaxRetries *int `mapstructure:"max_retries" required:"false" cty:"max_retries" hcl:"max_retries"` @@ -28,6 +30,7 @@ type FlatConfig struct { SecretKey *string `mapstructure:"secret_key" required:"true" cty:"secret_key" hcl:"secret_key"` SkipValidation *bool `mapstructure:"skip_region_validation" required:"false" cty:"skip_region_validation" hcl:"skip_region_validation"` SkipMetadataApiCheck *bool `mapstructure:"skip_metadata_api_check" cty:"skip_metadata_api_check" hcl:"skip_metadata_api_check"` + SkipCredsValidation *bool `mapstructure:"skip_credential_validation" cty:"skip_credential_validation" hcl:"skip_credential_validation"` Token *string `mapstructure:"token" required:"false" cty:"token" hcl:"token"` VaultAWSEngine *common.FlatVaultAWSEngineOptions `mapstructure:"vault_aws_engine" required:"false" cty:"vault_aws_engine" hcl:"vault_aws_engine"` PollingConfig *common.FlatAWSPollingConfig `mapstructure:"aws_polling" required:"false" cty:"aws_polling" hcl:"aws_polling"` @@ -68,7 +71,9 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "packer_user_variables": &hcldec.AttrSpec{Name: "packer_user_variables", Type: cty.Map(cty.String), Required: false}, "packer_sensitive_variables": &hcldec.AttrSpec{Name: "packer_sensitive_variables", Type: cty.List(cty.String), Required: false}, "access_key": &hcldec.AttrSpec{Name: "access_key", Type: cty.String, Required: false}, + "assume_role": &hcldec.BlockSpec{TypeName: "assume_role", Nested: hcldec.ObjectSpec((*common.FlatAssumeRoleConfig)(nil).HCL2Spec())}, "custom_endpoint_ec2": &hcldec.AttrSpec{Name: "custom_endpoint_ec2", Type: cty.String, Required: false}, + "shared_credentials_file": &hcldec.AttrSpec{Name: "shared_credentials_file", Type: cty.String, Required: false}, "decode_authorization_messages": &hcldec.AttrSpec{Name: "decode_authorization_messages", Type: cty.Bool, Required: false}, "insecure_skip_tls_verify": &hcldec.AttrSpec{Name: "insecure_skip_tls_verify", Type: cty.Bool, Required: false}, "max_retries": &hcldec.AttrSpec{Name: "max_retries", Type: cty.Number, Required: false}, @@ -78,6 +83,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "secret_key": &hcldec.AttrSpec{Name: "secret_key", Type: cty.String, Required: false}, "skip_region_validation": &hcldec.AttrSpec{Name: "skip_region_validation", Type: cty.Bool, Required: false}, "skip_metadata_api_check": &hcldec.AttrSpec{Name: "skip_metadata_api_check", Type: cty.Bool, Required: false}, + "skip_credential_validation": &hcldec.AttrSpec{Name: "skip_credential_validation", Type: cty.Bool, Required: false}, "token": &hcldec.AttrSpec{Name: "token", Type: cty.String, Required: false}, "vault_aws_engine": &hcldec.BlockSpec{TypeName: "vault_aws_engine", Nested: hcldec.ObjectSpec((*common.FlatVaultAWSEngineOptions)(nil).HCL2Spec())}, "aws_polling": &hcldec.BlockSpec{TypeName: "aws_polling", Nested: hcldec.ObjectSpec((*common.FlatAWSPollingConfig)(nil).HCL2Spec())}, diff --git a/post-processor/docker-push/post-processor.go b/post-processor/docker-push/post-processor.go index 979ea2896..97ffb8627 100644 --- a/post-processor/docker-push/post-processor.go +++ b/post-processor/docker-push/post-processor.go @@ -5,7 +5,6 @@ package dockerpush import ( "context" "fmt" - "github.com/hashicorp/hcl/v2/hcldec" "github.com/hashicorp/packer/builder/docker" "github.com/hashicorp/packer/common" @@ -103,17 +102,21 @@ func (p *PostProcessor) PostProcess(ctx context.Context, ui packer.Ui, artifact }() } - names := []string{artifact.Id()} - tags := artifact.State("docker_tags") - if tags != nil { - cast := tags.([]interface{}) - for _, name := range cast { + var tags []string + switch t := artifact.State("docker_tags").(type) { + case []string: + tags = t + case []interface{}: + for _, name := range t { if n, ok := name.(string); ok { - names = append(names, n) + tags = append(tags, n) } } } + names := []string{artifact.Id()} + names = append(names, tags...) + // Get the name. for _, name := range names { ui.Message("Pushing: " + name) diff --git a/post-processor/googlecompute-import/post-processor.go b/post-processor/googlecompute-import/post-processor.go index 7b326d9da..f3d06bb71 100644 --- a/post-processor/googlecompute-import/post-processor.go +++ b/post-processor/googlecompute-import/post-processor.go @@ -13,6 +13,7 @@ import ( "golang.org/x/oauth2/jwt" "google.golang.org/api/compute/v1" + "google.golang.org/api/option" "google.golang.org/api/storage/v1" "github.com/hashicorp/hcl/v2/hcldec" @@ -180,7 +181,7 @@ func (p *PostProcessor) PostProcess(ctx context.Context, ui packer.Ui, artifact } func UploadToBucket(client *http.Client, ui packer.Ui, artifact packer.Artifact, bucket string, gcsObjectName string) (string, error) { - service, err := storage.New(client) + service, err := storage.NewService(context.TODO(), option.WithHTTPClient(client)) if err != nil { return "", err } @@ -216,7 +217,7 @@ func UploadToBucket(client *http.Client, ui packer.Ui, artifact packer.Artifact, } func CreateGceImage(client *http.Client, ui packer.Ui, project string, rawImageURL string, imageName string, imageDescription string, imageFamily string, imageLabels map[string]string, imageGuestOsFeatures []string) (packer.Artifact, error) { - service, err := compute.New(client) + service, err := compute.NewService(context.TODO(), option.WithHTTPClient(client)) if err != nil { return nil, err } @@ -270,7 +271,7 @@ func CreateGceImage(client *http.Client, ui packer.Ui, project string, rawImageU } func DeleteFromBucket(client *http.Client, ui packer.Ui, bucket string, gcsObjectName string) error { - service, err := storage.New(client) + service, err := storage.NewService(context.TODO(), option.WithHTTPClient(client)) if err != nil { return err } diff --git a/post-processor/vagrant/post-processor.go b/post-processor/vagrant/post-processor.go index a362b2e46..43cde6855 100644 --- a/post-processor/vagrant/post-processor.go +++ b/post-processor/vagrant/post-processor.go @@ -175,7 +175,10 @@ func (p *PostProcessor) PostProcessProvider(name string, provider Provider, ui p return nil, false, err } - customVagrantfile = string(customBytes) + customVagrantfile, err = interpolate.Render(string(customBytes), &config.ctx) + if err != nil { + return nil, false, err + } } f, err := os.Create(filepath.Join(dir, "Vagrantfile")) diff --git a/post-processor/yandex-export/post-processor.go b/post-processor/yandex-export/post-processor.go index 92fa22b12..b2e88df66 100644 --- a/post-processor/yandex-export/post-processor.go +++ b/post-processor/yandex-export/post-processor.go @@ -218,6 +218,9 @@ func (p *PostProcessor) PostProcess(ctx context.Context, ui packer.Ui, artifact // Run the steps. p.runner = common.NewRunner(steps, p.config.PackerConfig, ui) p.runner.Run(ctx, state) + if rawErr, ok := state.GetOk("error"); ok { + return nil, false, false, rawErr.(error) + } result := &Artifact{ paths: p.config.Paths, diff --git a/post-processor/yandex-import/utils.go b/post-processor/yandex-import/utils.go index 74c23dbc8..00b53a4a3 100644 --- a/post-processor/yandex-import/utils.go +++ b/post-processor/yandex-import/utils.go @@ -55,6 +55,12 @@ func uploadToBucket(s3conn *s3.S3, ui packer.Ui, artifact packer.Artifact, bucke // Compute service allow only `https://storage.yandexcloud.net/...` URLs for Image create process req.Config.S3ForcePathStyle = aws.Bool(true) + err = req.Build() + if err != nil { + ui.Say(fmt.Sprintf("Failed to build S3 request: %v", err)) + return nil, err + } + return &objectSource{ url: req.HTTPRequest.URL.String(), }, nil diff --git a/provisioner/ansible/provisioner.go b/provisioner/ansible/provisioner.go index a9bcdd344..6ff90ea86 100644 --- a/provisioner/ansible/provisioner.go +++ b/provisioner/ansible/provisioner.go @@ -162,8 +162,8 @@ type Config struct { // test your playbook. this option is not used if you set an `inventory_file`. KeepInventoryFile bool `mapstructure:"keep_inventory_file"` // A requirements file which provides a way to - // install roles with the [ansible-galaxy - // cli](http://docs.ansible.com/ansible/galaxy.html#the-ansible-galaxy-command-line-tool) + // install roles or collections with the [ansible-galaxy + // cli](https://docs.ansible.com/ansible/latest/galaxy/user_guide.html#the-ansible-galaxy-command-line-tool) // on the local machine before executing `ansible-playbook`. By default, this is empty. GalaxyFile string `mapstructure:"galaxy_file"` // The command to invoke ansible-galaxy. By default, this is @@ -173,11 +173,16 @@ type Config struct { // Adds `--force` option to `ansible-galaxy` command. By default, this is // `false`. GalaxyForceInstall bool `mapstructure:"galaxy_force_install"` - // The path to the directory on your local system to - // install the roles in. Adds `--roles-path /path/to/your/roles` to + // The path to the directory on your local system in which to + // install the roles. Adds `--roles-path /path/to/your/roles` to // `ansible-galaxy` command. By default, this is empty, and thus `--roles-path` // option is not added to the command. RolesPath string `mapstructure:"roles_path"` + // The path to the directory on your local system in which to + // install the collections. Adds `--collections-path /path/to/your/collections` to + // `ansible-galaxy` command. By default, this is empty, and thus `--collections-path` + // option is not added to the command. + CollectionsPath string `mapstructure:"collections_path"` // When `true`, set up a localhost proxy adapter // so that Ansible has an IP address to connect to, even if your guest does not // have an IP address. For example, the adapter is necessary for Docker builds @@ -370,7 +375,7 @@ func (p *Provisioner) setupAdapter(ui packer.Ui, comm packer.Communicator) (stri keyChecker := ssh.CertChecker{ UserKeyFallback: func(conn ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) { if user := conn.User(); user != p.config.User { - return nil, errors.New(fmt.Sprintf("authentication failed: %s is not a valid user", user)) + return nil, fmt.Errorf("authentication failed: %s is not a valid user", user) } if !bytes.Equal(k.Marshal(), pubKey.Marshal()) { @@ -624,16 +629,52 @@ func (p *Provisioner) executeGalaxy(ui packer.Ui, comm packer.Communicator) erro galaxyFile := filepath.ToSlash(p.config.GalaxyFile) // ansible-galaxy install -r requirements.yml - args := []string{"install", "-r", galaxyFile} + roleArgs := []string{"install", "-r", galaxyFile} + // Instead of modifying args depending on config values and removing or modifying values from + // the slice between role and collection installs, just use 2 slices and simplify everything + collectionArgs := []string{"collection", "install", "-r", galaxyFile} // Add force to arguments if p.config.GalaxyForceInstall { - args = append(args, "-f") - } - // Add roles_path argument if specified - if p.config.RolesPath != "" { - args = append(args, "-p", filepath.ToSlash(p.config.RolesPath)) + roleArgs = append(roleArgs, "-f") + collectionArgs = append(collectionArgs, "-f") } + // Add roles_path argument if specified + if p.config.RolesPath != "" { + roleArgs = append(roleArgs, "-p", filepath.ToSlash(p.config.RolesPath)) + } + // Add collections_path argument if specified + if p.config.CollectionsPath != "" { + collectionArgs = append(collectionArgs, "-p", filepath.ToSlash(p.config.CollectionsPath)) + } + + // Search galaxy_file for roles and collections keywords + f, err := ioutil.ReadFile(galaxyFile) + if err != nil { + return err + } + hasRoles, _ := regexp.Match(`(?m)^roles:`, f) + hasCollections, _ := regexp.Match(`(?m)^collections:`, f) + + // If if roles keyword present (v2 format), or no collections keywork present (v1), install roles + if hasRoles || !hasCollections { + if roleInstallError := p.invokeGalaxyCommand(roleArgs, ui, comm); roleInstallError != nil { + return roleInstallError + } + } + + // If collections keyword present (v2 format), install collections + if hasCollections { + if collectionInstallError := p.invokeGalaxyCommand(collectionArgs, ui, comm); collectionInstallError != nil { + return collectionInstallError + } + } + + return nil +} + +// Intended to be invoked from p.executeGalaxy depending on the Ansible Galaxy parameters passed to Packer +func (p *Provisioner) invokeGalaxyCommand(args []string, ui packer.Ui, comm packer.Communicator) error { ui.Message(fmt.Sprintf("Executing Ansible Galaxy")) cmd := exec.Command(p.config.GalaxyCommand, args...) diff --git a/provisioner/ansible/provisioner.hcl2spec.go b/provisioner/ansible/provisioner.hcl2spec.go index 91b7fce71..61217c677 100644 --- a/provisioner/ansible/provisioner.hcl2spec.go +++ b/provisioner/ansible/provisioner.hcl2spec.go @@ -39,6 +39,7 @@ type FlatConfig struct { GalaxyCommand *string `mapstructure:"galaxy_command" cty:"galaxy_command" hcl:"galaxy_command"` GalaxyForceInstall *bool `mapstructure:"galaxy_force_install" cty:"galaxy_force_install" hcl:"galaxy_force_install"` RolesPath *string `mapstructure:"roles_path" cty:"roles_path" hcl:"roles_path"` + CollectionsPath *string `mapstructure:"collections_path" cty:"collections_path" hcl:"collections_path"` UseProxy *bool `mapstructure:"use_proxy" cty:"use_proxy" hcl:"use_proxy"` } @@ -84,6 +85,7 @@ func (*FlatConfig) HCL2Spec() map[string]hcldec.Spec { "galaxy_command": &hcldec.AttrSpec{Name: "galaxy_command", Type: cty.String, Required: false}, "galaxy_force_install": &hcldec.AttrSpec{Name: "galaxy_force_install", Type: cty.Bool, Required: false}, "roles_path": &hcldec.AttrSpec{Name: "roles_path", Type: cty.String, Required: false}, + "collections_path": &hcldec.AttrSpec{Name: "collections_path", Type: cty.String, Required: false}, "use_proxy": &hcldec.AttrSpec{Name: "use_proxy", Type: cty.Bool, Required: false}, } return s diff --git a/provisioner/elevated.go b/provisioner/elevated.go index 099d20024..71addb563 100644 --- a/provisioner/elevated.go +++ b/provisioner/elevated.go @@ -70,7 +70,7 @@ $xml = [xml]@' false false false - PT24H + PT0S 4 diff --git a/provisioner/file/provisioner_test.go b/provisioner/file/provisioner_test.go index 0986e1e05..dd1d0325c 100644 --- a/provisioner/file/provisioner_test.go +++ b/provisioner/file/provisioner_test.go @@ -126,6 +126,7 @@ func TestProvisionerProvision_SendsFile(t *testing.T) { b := bytes.NewBuffer(nil) ui := &packer.BasicUi{ Writer: b, + PB: &packer.NoopProgressTracker{}, } comm := &packer.MockCommunicator{} err = p.Provision(context.Background(), ui, comm, make(map[string]interface{})) @@ -184,6 +185,7 @@ func TestProvisionerProvision_SendsFileMultipleFiles(t *testing.T) { b := bytes.NewBuffer(nil) ui := &packer.BasicUi{ Writer: b, + PB: &packer.NoopProgressTracker{}, } comm := &packer.MockCommunicator{} err = p.Provision(context.Background(), ui, comm, make(map[string]interface{})) @@ -253,6 +255,7 @@ func TestProvisionerProvision_SendsFileMultipleDirs(t *testing.T) { b := bytes.NewBuffer(nil) ui := &packer.BasicUi{ Writer: b, + PB: &packer.NoopProgressTracker{}, } comm := &packer.MockCommunicator{} err = p.Provision(context.Background(), ui, comm, make(map[string]interface{})) @@ -304,6 +307,7 @@ func TestProvisionerProvision_SendsFileMultipleFilesToFolder(t *testing.T) { b := bytes.NewBuffer(nil) ui := &packer.BasicUi{ Writer: b, + PB: &packer.NoopProgressTracker{}, } comm := &packer.MockCommunicator{} err = p.Provision(context.Background(), ui, comm, make(map[string]interface{})) @@ -361,6 +365,7 @@ func TestProvisionDownloadMkdirAll(t *testing.T) { b := bytes.NewBuffer(nil) ui := &packer.BasicUi{ Writer: b, + PB: &packer.NoopProgressTracker{}, } comm := &packer.MockCommunicator{} err = p.ProvisionDownload(ui, comm) diff --git a/test/fixtures/provisioner-ansible/galaxy-playbook.yml b/test/fixtures/provisioner-ansible/galaxy-playbook.yml new file mode 100644 index 000000000..b91a3dab4 --- /dev/null +++ b/test/fixtures/provisioner-ansible/galaxy-playbook.yml @@ -0,0 +1,33 @@ +--- +- hosts: default:packer-test + gather_facts: no + collections: + - artis3n.github + tasks: + - name: touch + raw: touch /tmp/ansible-raw-test + - name: raw test + raw: date + - name: command test + command: echo "the command module" + - name: prepare remote directory + command: mkdir /tmp/remote-dir + args: + creates: /tmp/remote-dir + - name: transfer file.txt + copy: src=dir/file.txt dest=/tmp/remote-dir/file.txt + - name: fetch file.text + fetch: src=/tmp/remote-dir/file.txt dest=fetched-dir validate=yes fail_on_missing=yes + - name: copy contents of directory + copy: src=dir/contents-only/ dest=/tmp/remote-dir + - name: fetch contents of directory + fetch: src=/tmp/remote-dir/file.txt dest="fetched-dir/{{ inventory_hostname }}/tmp/remote-dir/contents-only/" flat=yes validate=yes fail_on_missing=yes + - name: copy directory recursively + copy: src=dir/subdir dest=/tmp/remote-dir + - name: fetch recursively copied directory + fetch: src=/tmp/remote-dir/subdir/file.txt dest=fetched-dir validate=yes fail_on_missing=yes + - copy: src=largish-file.txt dest=/tmp/largish-file.txt + - name: test collection - fetch latest repo version + set_fact: + # Ansible will fail if collection is not installed + packer_version: "{{ lookup('artis3n.github.latest_release', 'hashicorp/packer' }}" diff --git a/test/fixtures/provisioner-ansible/galaxy.json b/test/fixtures/provisioner-ansible/galaxy.json new file mode 100644 index 000000000..879c925f6 --- /dev/null +++ b/test/fixtures/provisioner-ansible/galaxy.json @@ -0,0 +1,21 @@ +{ + "variables": {}, + "provisioners": [ + { + "type": "ansible", + "playbook_file": "./galaxy-playbook.yml", + "galaxy_file": "./requirements.yml" + } + ], + "builders": [ + { + "type": "googlecompute", + "account_file": "{{user `account_file`}}", + "project_id": "{{user `project_id`}}", + "image_name": "packerbats-galaxy-{{timestamp}}", + "source_image": "debian-8-jessie-v20161027", + "zone": "us-central1-a", + "ssh_username": "debian" + } + ] +} diff --git a/test/fixtures/provisioner-ansible/requirements.yml b/test/fixtures/provisioner-ansible/requirements.yml new file mode 100644 index 000000000..4658d9204 --- /dev/null +++ b/test/fixtures/provisioner-ansible/requirements.yml @@ -0,0 +1,2 @@ +collections: + - name: artis3n.github diff --git a/test/provisioner_ansible.bats b/test/provisioner_ansible.bats index c9dc9abd9..2cc45b522 100755 --- a/test/provisioner_ansible.bats +++ b/test/provisioner_ansible.bats @@ -65,6 +65,14 @@ teardown() { diff -r dir fetched-dir/packer-test/tmp/remote-dir > /dev/null } +@test "ansible provisioner: build galaxy.json" { + cd $FIXTURE_ROOT + run packer build ${USER_VARS} $FIXTURE_ROOT/galaxy.json + [ "$status" -eq 0 ] + [ "$(gc_has_image "packerbats-galaxy")" -eq 1 ] + diff -r dir fetched-dir/default/tmp/remote-dir > /dev/null +} + @test "ansible provisioner: build scp.json" { cd $FIXTURE_ROOT run packer build ${USER_VARS} $FIXTURE_ROOT/scp.json 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 2def23fa1..3b809e847 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/config.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/config.go @@ -43,7 +43,7 @@ type Config struct { // An optional endpoint URL (hostname only or fully qualified URI) // that overrides the default generated endpoint for a client. Set this - // to `""` to use the default generated endpoint. + // to `nil` or the value to `""` to use the default generated endpoint. // // Note: You must still provide a `Region` value when specifying an // endpoint for a client. @@ -138,7 +138,7 @@ type Config struct { // `ExpectContinueTimeout` for information on adjusting the continue wait // timeout. https://golang.org/pkg/net/http/#Transport // - // You should use this flag to disble 100-Continue if you experience issues + // You should use this flag to disable 100-Continue if you experience issues // with proxies or third party S3 compatible services. S3Disable100Continue *bool @@ -183,7 +183,7 @@ type Config struct { // // Example: // sess := session.Must(session.NewSession(aws.NewConfig() - // .WithEC2MetadataDiableTimeoutOverride(true))) + // .WithEC2MetadataDisableTimeoutOverride(true))) // // svc := s3.New(sess) // @@ -194,7 +194,7 @@ type Config struct { // both IPv4 and IPv6 addressing. // // Setting this for a service which does not support dual stack will fail - // to make requets. It is not recommended to set this value on the session + // to make requests. It is not recommended to set this value on the session // as it will apply to all service clients created with the session. Even // services which don't support dual stack endpoints. // @@ -238,6 +238,7 @@ type Config struct { // EnableEndpointDiscovery will allow for endpoint discovery on operations that // have the definition in its model. By default, endpoint discovery is off. + // To use EndpointDiscovery, Endpoint should be unset or set to an empty string. // // Example: // sess := session.Must(session.NewSession(&aws.Config{ 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 aa902d708..d95a5eb54 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 @@ -225,6 +225,8 @@ var ValidateEndpointHandler = request.NamedHandler{Name: "core.ValidateEndpointH if r.ClientInfo.SigningRegion == "" && aws.StringValue(r.Config.Region) == "" { r.Error = aws.ErrMissingRegion } else if r.ClientInfo.Endpoint == "" { + // Was any endpoint provided by the user, or one was derived by the + // SDK's endpoint resolver? r.Error = aws.ErrMissingEndpoint } }} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go index e15514958..22b5c5d9f 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go @@ -17,8 +17,9 @@ var ( ErrSharedCredentialsHomeNotFound = awserr.New("UserHomeNotFound", "user home directory not found.", nil) ) -// A SharedCredentialsProvider retrieves credentials from the current user's home -// directory, and keeps track if those credentials are expired. +// A SharedCredentialsProvider retrieves access key pair (access key ID, +// secret access key, and session token if present) credentials from the current +// user's home directory, and keeps track if those credentials are expired. // // Profile ini file example: $HOME/.aws/credentials type SharedCredentialsProvider struct { 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 73d9763c9..6846ef6f8 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 @@ -169,6 +169,29 @@ type AssumeRoleProvider struct { // size. Policy *string + // The ARNs of IAM managed policies you want to use as managed session policies. + // The policies must exist in the same account as the role. + // + // This parameter is optional. You can provide up to 10 managed policy ARNs. + // However, the plain text that you use for both inline and managed session + // policies can't exceed 2,048 characters. + // + // An AWS conversion compresses the passed session policies and session tags + // into a packed binary format that has a separate limit. Your request can fail + // for this limit even if your plain text meets the other requirements. The + // PackedPolicySize response element indicates by percentage how close the policies + // and tags for your request are to the upper size limit. + // + // Passing policies to this operation returns new temporary credentials. The + // resulting session's permissions are the intersection of the role's identity-based + // policy and the session policies. You can use the role's temporary credentials + // in subsequent AWS API calls to access resources in the account that owns + // the role. You cannot use session policies to grant more permissions than + // those allowed by the identity-based policy of the role that is being assumed. + // For more information, see Session Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session) + // in the IAM User Guide. + PolicyArns []*sts.PolicyDescriptorType + // The identification number of the MFA device that is associated with the user // who is making the AssumeRole call. Specify this value if the trust policy // of the role being assumed includes a condition that requires MFA authentication. @@ -291,6 +314,7 @@ func (p *AssumeRoleProvider) RetrieveWithContext(ctx credentials.Context) (crede RoleSessionName: aws.String(p.RoleSessionName), ExternalId: p.ExternalID, Tags: p.Tags, + PolicyArns: p.PolicyArns, TransitiveTagKeys: p.TransitiveTagKeys, } if p.Policy != nil { diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/web_identity_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/web_identity_provider.go index fae6f2f65..cefe2a76d 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/web_identity_provider.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/web_identity_provider.go @@ -28,15 +28,46 @@ const ( // compare test values. var now = time.Now +// TokenFetcher shuold return WebIdentity token bytes or an error +type TokenFetcher interface { + FetchToken(credentials.Context) ([]byte, error) +} + +// FetchTokenPath is a path to a WebIdentity token file +type FetchTokenPath string + +// FetchToken returns a token by reading from the filesystem +func (f FetchTokenPath) FetchToken(ctx credentials.Context) ([]byte, error) { + data, err := ioutil.ReadFile(string(f)) + if err != nil { + errMsg := fmt.Sprintf("unable to read file at %s", f) + return nil, awserr.New(ErrCodeWebIdentity, errMsg, err) + } + return data, nil +} + // WebIdentityRoleProvider is used to retrieve credentials using // an OIDC token. type WebIdentityRoleProvider struct { credentials.Expiry + PolicyArns []*sts.PolicyDescriptorType - client stsiface.STSAPI + // Duration the STS credentials will be valid for. Truncated to seconds. + // If unset, the assumed role will use AssumeRoleWithWebIdentity's default + // expiry duration. See + // https://docs.aws.amazon.com/sdk-for-go/api/service/sts/#STS.AssumeRoleWithWebIdentity + // for more information. + Duration time.Duration + + // The amount of time the credentials will be refreshed before they expire. + // This is useful refresh credentials before they expire to reduce risk of + // using credentials as they expire. If unset, will default to no expiry + // window. ExpiryWindow time.Duration - tokenFilePath string + client stsiface.STSAPI + + tokenFetcher TokenFetcher roleARN string roleSessionName string } @@ -52,9 +83,15 @@ func NewWebIdentityCredentials(c client.ConfigProvider, roleARN, roleSessionName // NewWebIdentityRoleProvider will return a new WebIdentityRoleProvider with the // provided stsiface.STSAPI func NewWebIdentityRoleProvider(svc stsiface.STSAPI, roleARN, roleSessionName, path string) *WebIdentityRoleProvider { + return NewWebIdentityRoleProviderWithToken(svc, roleARN, roleSessionName, FetchTokenPath(path)) +} + +// NewWebIdentityRoleProviderWithToken will return a new WebIdentityRoleProvider with the +// provided stsiface.STSAPI and a TokenFetcher +func NewWebIdentityRoleProviderWithToken(svc stsiface.STSAPI, roleARN, roleSessionName string, tokenFetcher TokenFetcher) *WebIdentityRoleProvider { return &WebIdentityRoleProvider{ client: svc, - tokenFilePath: path, + tokenFetcher: tokenFetcher, roleARN: roleARN, roleSessionName: roleSessionName, } @@ -71,10 +108,9 @@ func (p *WebIdentityRoleProvider) Retrieve() (credentials.Value, error) { // 'WebIdentityTokenFilePath' specified destination and if that is empty an // error will be returned. func (p *WebIdentityRoleProvider) RetrieveWithContext(ctx credentials.Context) (credentials.Value, error) { - b, err := ioutil.ReadFile(p.tokenFilePath) + b, err := p.tokenFetcher.FetchToken(ctx) if err != nil { - errMsg := fmt.Sprintf("unable to read file at %s", p.tokenFilePath) - return credentials.Value{}, awserr.New(ErrCodeWebIdentity, errMsg, err) + return credentials.Value{}, awserr.New(ErrCodeWebIdentity, "failed fetching WebIdentity token: ", err) } sessionName := p.roleSessionName @@ -83,10 +119,18 @@ func (p *WebIdentityRoleProvider) RetrieveWithContext(ctx credentials.Context) ( // uses unix time in nanoseconds to uniquely identify sessions. sessionName = strconv.FormatInt(now().UnixNano(), 10) } + + var duration *int64 + if p.Duration != 0 { + duration = aws.Int64(int64(p.Duration / time.Second)) + } + req, resp := p.client.AssumeRoleWithWebIdentityRequest(&sts.AssumeRoleWithWebIdentityInput{ + PolicyArns: p.PolicyArns, RoleArn: &p.roleARN, RoleSessionName: &sessionName, WebIdentityToken: aws.String(string(b)), + DurationSeconds: duration, }) req.SetContext(ctx) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go index a716c021c..69fa63dc0 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go @@ -20,7 +20,7 @@ func (c *EC2Metadata) getToken(ctx aws.Context, duration time.Duration) (tokenOu op := &request.Operation{ Name: "GetToken", HTTPMethod: "PUT", - HTTPPath: "/api/token", + HTTPPath: "/latest/api/token", } var output tokenOutput @@ -62,7 +62,7 @@ func (c *EC2Metadata) GetMetadataWithContext(ctx aws.Context, p string) (string, op := &request.Operation{ Name: "GetMetadata", HTTPMethod: "GET", - HTTPPath: sdkuri.PathJoin("/meta-data", p), + HTTPPath: sdkuri.PathJoin("/latest/meta-data", p), } output := &metadataOutput{} @@ -88,7 +88,7 @@ func (c *EC2Metadata) GetUserDataWithContext(ctx aws.Context) (string, error) { op := &request.Operation{ Name: "GetUserData", HTTPMethod: "GET", - HTTPPath: "/user-data", + HTTPPath: "/latest/user-data", } output := &metadataOutput{} @@ -113,7 +113,7 @@ func (c *EC2Metadata) GetDynamicDataWithContext(ctx aws.Context, p string) (stri op := &request.Operation{ Name: "GetDynamicData", HTTPMethod: "GET", - HTTPPath: sdkuri.PathJoin("/dynamic", p), + HTTPPath: sdkuri.PathJoin("/latest/dynamic", p), } output := &metadataOutput{} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go index b8b2940d7..8f35b3464 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go @@ -5,6 +5,10 @@ // variable "AWS_EC2_METADATA_DISABLED=true". This environment variable set to // true instructs the SDK to disable the EC2 Metadata client. The client cannot // be used while the environment variable is set to true, (case insensitive). +// +// The endpoint of the EC2 IMDS client can be configured via the environment +// variable, AWS_EC2_METADATA_SERVICE_ENDPOINT when creating the client with a +// Session. See aws/session#Options.EC2IMDSEndpoint for more details. package ec2metadata import ( @@ -12,6 +16,7 @@ import ( "errors" "io" "net/http" + "net/url" "os" "strconv" "strings" @@ -41,7 +46,7 @@ const ( enableTokenProviderHandlerName = "enableTokenProviderHandler" // TTL constants - defaultTTL = 21600 * time.Second + defaultTTL = 21600 * time.Second ttlExpirationWindow = 30 * time.Second ) @@ -69,6 +74,9 @@ func New(p client.ConfigProvider, cfgs ...*aws.Config) *EC2Metadata { // a client when not using a session. Generally using just New with a session // is preferred. // +// Will remove the URL path from the endpoint provided to ensure the EC2 IMDS +// client is able to communicate with the EC2 IMDS API. +// // If an unmodified HTTP client is provided from the stdlib default, or no client // the EC2RoleProvider's EC2Metadata HTTP client's timeout will be shortened. // To disable this set Config.EC2MetadataDisableTimeoutOverride to false. Enabled by default. @@ -86,6 +94,15 @@ func NewClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegio cfg.MaxRetries = aws.Int(2) } + if u, err := url.Parse(endpoint); err == nil { + // Remove path from the endpoint since it will be added by requests. + // This is an artifact of the SDK adding `/latest` to the endpoint for + // EC2 IMDS, but this is now moved to the operation definition. + u.Path = "" + u.RawPath = "" + endpoint = u.String() + } + svc := &EC2Metadata{ Client: client.New( cfg, diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go index 343a2106f..654fb1ad5 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go @@ -93,7 +93,7 @@ func decodeV3Endpoints(modelDef modelDefinition, opts DecodeModelOptions) (Resol } func custAddS3DualStack(p *partition) { - if p.ID != "aws" { + if !(p.ID == "aws" || p.ID == "aws-cn" || p.ID == "aws-us-gov") { return } 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 0d69ad9cc..a2484a902 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 @@ -17,6 +17,7 @@ const ( // AWS Standard partition's regions. const ( + AfSouth1RegionID = "af-south-1" // Africa (Cape Town). ApEast1RegionID = "ap-east-1" // Asia Pacific (Hong Kong). ApNortheast1RegionID = "ap-northeast-1" // Asia Pacific (Tokyo). ApNortheast2RegionID = "ap-northeast-2" // Asia Pacific (Seoul). @@ -24,11 +25,12 @@ const ( ApSoutheast1RegionID = "ap-southeast-1" // Asia Pacific (Singapore). ApSoutheast2RegionID = "ap-southeast-2" // Asia Pacific (Sydney). CaCentral1RegionID = "ca-central-1" // Canada (Central). - EuCentral1RegionID = "eu-central-1" // EU (Frankfurt). - EuNorth1RegionID = "eu-north-1" // EU (Stockholm). - EuWest1RegionID = "eu-west-1" // EU (Ireland). - EuWest2RegionID = "eu-west-2" // EU (London). - EuWest3RegionID = "eu-west-3" // EU (Paris). + EuCentral1RegionID = "eu-central-1" // Europe (Frankfurt). + EuNorth1RegionID = "eu-north-1" // Europe (Stockholm). + EuSouth1RegionID = "eu-south-1" // Europe (Milan). + EuWest1RegionID = "eu-west-1" // Europe (Ireland). + EuWest2RegionID = "eu-west-2" // Europe (London). + EuWest3RegionID = "eu-west-3" // Europe (Paris). MeSouth1RegionID = "me-south-1" // Middle East (Bahrain). SaEast1RegionID = "sa-east-1" // South America (Sao Paulo). UsEast1RegionID = "us-east-1" // US East (N. Virginia). @@ -46,7 +48,7 @@ const ( // AWS GovCloud (US) partition's regions. const ( UsGovEast1RegionID = "us-gov-east-1" // AWS GovCloud (US-East). - UsGovWest1RegionID = "us-gov-west-1" // AWS GovCloud (US). + UsGovWest1RegionID = "us-gov-west-1" // AWS GovCloud (US-West). ) // AWS ISO (US) partition's regions. @@ -97,7 +99,7 @@ var awsPartition = partition{ DNSSuffix: "amazonaws.com", RegionRegex: regionRegex{ Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^(us|eu|ap|sa|ca|me)\\-\\w+\\-\\d+$") + reg, _ := regexp.Compile("^(us|eu|ap|sa|ca|me|af)\\-\\w+\\-\\d+$") return reg }(), }, @@ -107,6 +109,9 @@ var awsPartition = partition{ SignatureVersions: []string{"v4"}, }, Regions: regions{ + "af-south-1": region{ + Description: "Africa (Cape Town)", + }, "ap-east-1": region{ Description: "Asia Pacific (Hong Kong)", }, @@ -129,19 +134,22 @@ var awsPartition = partition{ Description: "Canada (Central)", }, "eu-central-1": region{ - Description: "EU (Frankfurt)", + Description: "Europe (Frankfurt)", }, "eu-north-1": region{ - Description: "EU (Stockholm)", + Description: "Europe (Stockholm)", + }, + "eu-south-1": region{ + Description: "Europe (Milan)", }, "eu-west-1": region{ - Description: "EU (Ireland)", + Description: "Europe (Ireland)", }, "eu-west-2": region{ - Description: "EU (London)", + Description: "Europe (London)", }, "eu-west-3": region{ - Description: "EU (Paris)", + Description: "Europe (Paris)", }, "me-south-1": region{ Description: "Middle East (Bahrain)", @@ -172,6 +180,7 @@ var awsPartition = partition{ "access-analyzer": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -181,20 +190,52 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, - "me-south-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "fips-ca-central-1": endpoint{ + Hostname: "access-analyzer-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, + "fips-us-east-1": endpoint{ + Hostname: "access-analyzer-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "access-analyzer-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-1": endpoint{ + Hostname: "access-analyzer-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "access-analyzer-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "acm": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -210,6 +251,7 @@ var awsPartition = partition{ }, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -250,6 +292,7 @@ var awsPartition = partition{ Protocols: []string{"https"}, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -259,6 +302,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -300,9 +344,42 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "api.detective": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + }, + Endpoints: endpoints{ + "af-south-1": endpoint{}, + "ap-east-1": 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-north-1": endpoint{}, + "eu-south-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, "api.ecr": service{ Endpoints: endpoints{ + "af-south-1": endpoint{ + Hostname: "api.ecr.af-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "af-south-1", + }, + }, "ap-east-1": endpoint{ Hostname: "api.ecr.ap-east-1.amazonaws.com", CredentialScope: credentialScope{ @@ -357,6 +434,12 @@ var awsPartition = partition{ Region: "eu-north-1", }, }, + "eu-south-1": endpoint{ + Hostname: "api.ecr.eu-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-south-1", + }, + }, "eu-west-1": endpoint{ Hostname: "api.ecr.eu-west-1.amazonaws.com", CredentialScope: credentialScope{ @@ -375,6 +458,30 @@ var awsPartition = partition{ Region: "eu-west-3", }, }, + "fips-dkr-us-east-1": endpoint{ + Hostname: "ecr-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-dkr-us-east-2": endpoint{ + Hostname: "ecr-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-dkr-us-west-1": endpoint{ + Hostname: "ecr-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "fips-dkr-us-west-2": endpoint{ + Hostname: "ecr-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, "fips-us-east-1": endpoint{ Hostname: "ecr-fips.us-east-1.amazonaws.com", CredentialScope: credentialScope{ @@ -437,6 +544,29 @@ var awsPartition = partition{ }, }, }, + "api.elastic-inference": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{ + Hostname: "api.elastic-inference.ap-northeast-1.amazonaws.com", + }, + "ap-northeast-2": endpoint{ + Hostname: "api.elastic-inference.ap-northeast-2.amazonaws.com", + }, + "eu-west-1": endpoint{ + Hostname: "api.elastic-inference.eu-west-1.amazonaws.com", + }, + "us-east-1": endpoint{ + Hostname: "api.elastic-inference.us-east-1.amazonaws.com", + }, + "us-east-2": endpoint{ + Hostname: "api.elastic-inference.us-east-2.amazonaws.com", + }, + "us-west-2": endpoint{ + Hostname: "api.elastic-inference.us-west-2.amazonaws.com", + }, + }, + }, "api.mediatailor": service{ Endpoints: endpoints{ @@ -510,6 +640,7 @@ var awsPartition = partition{ "apigateway": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -519,6 +650,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -530,11 +662,32 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "appflow": 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{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, "application-autoscaling": service{ Defaults: endpoint{ Protocols: []string{"http", "https"}, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -544,6 +697,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -588,6 +742,7 @@ 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{}, @@ -610,11 +765,17 @@ var awsPartition = partition{ "ap-south-1": endpoint{}, "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, + "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, @@ -630,6 +791,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -646,6 +808,7 @@ var awsPartition = partition{ Protocols: []string{"http", "https"}, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -655,6 +818,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -671,6 +835,7 @@ var awsPartition = partition{ Protocols: []string{"http", "https"}, }, Endpoints: endpoints{ + "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, "ap-south-1": endpoint{}, @@ -678,8 +843,12 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-1": endpoint{}, @@ -721,6 +890,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -802,6 +972,7 @@ var awsPartition = partition{ "cloud9": service{ Endpoints: endpoints{ + "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, "ap-south-1": endpoint{}, @@ -810,10 +981,15 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, + "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, @@ -834,6 +1010,7 @@ var awsPartition = partition{ "cloudformation": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -843,6 +1020,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -914,6 +1092,7 @@ var awsPartition = partition{ }, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -923,6 +1102,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -952,6 +1132,7 @@ var awsPartition = partition{ "cloudtrail": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -961,6 +1142,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -996,6 +1178,21 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "codeartifact": service{ + + Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-south-1": endpoint{}, + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, + }, + }, "codebuild": service{ Endpoints: endpoints{ @@ -1055,6 +1252,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -1075,6 +1273,7 @@ var awsPartition = partition{ "codedeploy": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -1084,6 +1283,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -1339,9 +1539,27 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, + "fips-us-east-1": endpoint{ + Hostname: "comprehendmedical-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "comprehendmedical-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "comprehendmedical-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, }, }, "config": service{ @@ -1394,6 +1612,7 @@ var awsPartition = partition{ "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, "us-east-1": endpoint{}, "us-west-2": endpoint{}, }, @@ -1427,6 +1646,7 @@ var awsPartition = partition{ "datasync": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -1436,6 +1656,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -1504,6 +1725,7 @@ var awsPartition = partition{ "directconnect": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -1513,6 +1735,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -1551,14 +1774,19 @@ var awsPartition = partition{ "discovery": service{ Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "us-east-1": endpoint{}, "us-west-2": endpoint{}, }, }, "dms": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -1574,6 +1802,7 @@ var awsPartition = partition{ }, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -1671,6 +1900,7 @@ var awsPartition = partition{ "ds": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -1680,15 +1910,46 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, - "me-south-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "fips-ca-central-1": endpoint{ + Hostname: "ds-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, + "fips-us-east-1": endpoint{ + Hostname: "ds-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "ds-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-1": endpoint{ + Hostname: "ds-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "ds-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "dynamodb": service{ @@ -1696,6 +1957,7 @@ var awsPartition = partition{ Protocols: []string{"http", "https"}, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -1711,6 +1973,7 @@ var awsPartition = partition{ }, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -1753,11 +2016,10 @@ var awsPartition = partition{ }, }, }, - "ec2": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, + "ebs": service{ + Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -1767,6 +2029,34 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "ec2": service{ + Defaults: endpoint{ + Protocols: []string{"http", "https"}, + }, + Endpoints: endpoints{ + "af-south-1": endpoint{}, + "ap-east-1": 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-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -1822,6 +2112,7 @@ var awsPartition = partition{ "ecs": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -1831,6 +2122,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -1852,7 +2144,7 @@ var awsPartition = partition{ Region: "us-west-1", }, }, - "madison-fips-us-west-2": endpoint{ + "fips-us-west-2": endpoint{ Hostname: "ecs-fips.us-west-2.amazonaws.com", CredentialScope: credentialScope{ Region: "us-west-2", @@ -1866,32 +2158,12 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, - "elastic-inference": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{ - Hostname: "api.elastic-inference.ap-northeast-1.amazonaws.com", - }, - "ap-northeast-2": endpoint{ - Hostname: "api.elastic-inference.ap-northeast-2.amazonaws.com", - }, - "eu-west-1": endpoint{ - Hostname: "api.elastic-inference.eu-west-1.amazonaws.com", - }, - "us-east-1": endpoint{ - Hostname: "api.elastic-inference.us-east-1.amazonaws.com", - }, - "us-east-2": endpoint{ - Hostname: "api.elastic-inference.us-east-2.amazonaws.com", - }, - "us-west-2": endpoint{ - Hostname: "api.elastic-inference.us-west-2.amazonaws.com", - }, + "eks": service{ + Defaults: endpoint{ + Protocols: []string{"http", "https"}, }, - }, - "elasticache": service{ - Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -1901,6 +2173,49 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "fips-us-east-1": endpoint{ + Hostname: "fips.eks.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "fips.eks.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "fips.eks.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "elasticache": service{ + + Endpoints: endpoints{ + "af-south-1": endpoint{}, + "ap-east-1": 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-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -1921,6 +2236,7 @@ var awsPartition = partition{ "elasticbeanstalk": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -1930,6 +2246,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -1968,6 +2285,7 @@ var awsPartition = partition{ "elasticfilesystem": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -1977,9 +2295,16 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, + "fips-af-south-1": endpoint{ + Hostname: "elasticfilesystem-fips.af-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "af-south-1", + }, + }, "fips-ap-east-1": endpoint{ Hostname: "elasticfilesystem-fips.ap-east-1.amazonaws.com", CredentialScope: credentialScope{ @@ -2034,6 +2359,12 @@ var awsPartition = partition{ Region: "eu-north-1", }, }, + "fips-eu-south-1": endpoint{ + Hostname: "elasticfilesystem-fips.eu-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-south-1", + }, + }, "fips-eu-west-1": endpoint{ Hostname: "elasticfilesystem-fips.eu-west-1.amazonaws.com", CredentialScope: credentialScope{ @@ -2101,6 +2432,7 @@ var awsPartition = partition{ Protocols: []string{"https"}, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -2110,6 +2442,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -2151,6 +2484,7 @@ var awsPartition = partition{ Protocols: []string{"https"}, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -2162,6 +2496,7 @@ var awsPartition = partition{ SSLCommonName: "{service}.{region}.{dnsSuffix}", }, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -2242,6 +2577,7 @@ var awsPartition = partition{ "es": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -2251,6 +2587,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -2271,6 +2608,7 @@ var awsPartition = partition{ "events": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -2280,6 +2618,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -2318,6 +2657,7 @@ var awsPartition = partition{ "firehose": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -2327,6 +2667,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -2367,6 +2708,8 @@ var awsPartition = partition{ Protocols: []string{"https"}, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, + "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, "ap-south-1": endpoint{}, @@ -2375,6 +2718,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -2468,11 +2812,12 @@ var awsPartition = partition{ Region: "us-west-2", }, }, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "forecast": service{ @@ -2510,12 +2855,17 @@ var awsPartition = partition{ Endpoints: endpoints{ "ap-east-1": 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-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-1": endpoint{}, @@ -2546,6 +2896,7 @@ var awsPartition = partition{ Protocols: []string{"http", "https"}, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -2555,6 +2906,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -2608,6 +2960,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -2667,9 +3020,22 @@ var awsPartition = partition{ Endpoints: endpoints{ "ap-southeast-2": endpoint{}, "eu-north-1": endpoint{}, - "me-south-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, + "eu-west-1": endpoint{}, + "fips-us-east-2": endpoint{ + Hostname: "groundstation-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "groundstation-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "me-south-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, }, }, "guardduty": service{ @@ -2678,6 +3044,7 @@ var awsPartition = partition{ Protocols: []string{"https"}, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -2687,6 +3054,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -2728,6 +3096,12 @@ var awsPartition = partition{ "us-east-1": endpoint{}, }, }, + "honeycode": service{ + + Endpoints: endpoints{ + "us-west-2": endpoint{}, + }, + }, "iam": service{ PartitionEndpoint: "aws-global", IsRegionalized: boxedFalse, @@ -2747,6 +3121,21 @@ var awsPartition = partition{ }, }, }, + "identitystore": service{ + + Endpoints: endpoints{ + "ap-southeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, + "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, + }, + }, "importexport": service{ PartitionEndpoint: "aws-global", IsRegionalized: boxedFalse, @@ -2834,6 +3223,7 @@ var awsPartition = partition{ Endpoints: endpoints{ "ap-northeast-1": endpoint{}, + "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, "us-east-1": endpoint{}, @@ -2971,6 +3361,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -2985,6 +3376,7 @@ var awsPartition = partition{ "kinesis": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -2994,6 +3386,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -3041,6 +3434,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -3074,6 +3468,7 @@ var awsPartition = partition{ "kms": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -3083,6 +3478,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -3104,8 +3500,12 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, "us-west-1": endpoint{}, @@ -3115,6 +3515,7 @@ var awsPartition = partition{ "lambda": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -3124,6 +3525,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -3162,6 +3564,7 @@ var awsPartition = partition{ "license-manager": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -3171,6 +3574,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -3226,6 +3630,81 @@ var awsPartition = partition{ }, "logs": service{ + Endpoints: endpoints{ + "af-south-1": endpoint{}, + "ap-east-1": 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-north-1": endpoint{}, + "eu-south-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "fips-us-east-1": endpoint{ + Hostname: "logs-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "logs-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-1": endpoint{ + Hostname: "logs-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "logs-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "machinelearning": service{ + + Endpoints: endpoints{ + "eu-west-1": endpoint{}, + "us-east-1": endpoint{}, + }, + }, + "macie": service{ + + Endpoints: endpoints{ + "fips-us-east-1": endpoint{ + Hostname: "macie-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "macie-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "us-east-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, + "macie2": service{ + Endpoints: endpoints{ "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, @@ -3239,19 +3718,35 @@ var awsPartition = partition{ "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, - "me-south-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "machinelearning": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, + "fips-us-east-1": endpoint{ + Hostname: "macie2-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "macie2-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-1": endpoint{ + Hostname: "macie2-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "macie2-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "managedblockchain": service{ @@ -3261,6 +3756,7 @@ var awsPartition = partition{ "ap-northeast-2": endpoint{}, "ap-southeast-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, "us-east-1": endpoint{}, }, }, @@ -3301,14 +3797,45 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "fips-ca-central-1": endpoint{ + Hostname: "mediaconvert-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, + "fips-us-east-1": endpoint{ + Hostname: "mediaconvert-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "mediaconvert-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-1": endpoint{ + Hostname: "mediaconvert-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "mediaconvert-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "medialive": service{ @@ -3324,10 +3851,28 @@ var awsPartition = partition{ "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, + "fips-us-east-1": endpoint{ + Hostname: "medialive-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "medialive-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "medialive-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-2": endpoint{}, }, }, "mediapackage": service{ @@ -3339,6 +3884,7 @@ var awsPartition = partition{ "ap-southeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -3357,6 +3903,7 @@ var awsPartition = partition{ "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, "us-east-1": endpoint{}, "us-west-2": endpoint{}, }, @@ -3368,6 +3915,7 @@ var awsPartition = partition{ }, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -3377,6 +3925,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -3391,8 +3940,12 @@ var awsPartition = partition{ "mgh": service{ Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, "ap-southeast-2": endpoint{}, "eu-central-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "us-east-1": endpoint{}, "us-west-2": endpoint{}, }, }, @@ -3409,8 +3962,12 @@ var awsPartition = partition{ }, }, Endpoints: endpoints{ + "ap-northeast-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-west-2": endpoint{}, }, @@ -3420,6 +3977,7 @@ var awsPartition = partition{ Protocols: []string{"http", "https"}, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -3429,6 +3987,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -3524,6 +4083,12 @@ var awsPartition = partition{ "neptune": service{ Endpoints: endpoints{ + "ap-east-1": endpoint{ + Hostname: "rds.ap-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-east-1", + }, + }, "ap-northeast-1": endpoint{ Hostname: "rds.ap-northeast-1.amazonaws.com", CredentialScope: credentialScope{ @@ -3596,6 +4161,12 @@ var awsPartition = partition{ Region: "me-south-1", }, }, + "sa-east-1": endpoint{ + Hostname: "rds.sa-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "sa-east-1", + }, + }, "us-east-1": endpoint{ Hostname: "rds.us-east-1.amazonaws.com", CredentialScope: credentialScope{ @@ -3608,6 +4179,12 @@ var awsPartition = partition{ Region: "us-east-2", }, }, + "us-west-1": endpoint{ + Hostname: "rds.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, "us-west-2": endpoint{ Hostname: "rds.us-west-2.amazonaws.com", CredentialScope: credentialScope{ @@ -3619,6 +4196,24 @@ var awsPartition = partition{ "oidc": service{ Endpoints: endpoints{ + "ap-northeast-1": endpoint{ + Hostname: "oidc.ap-northeast-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-1", + }, + }, + "ap-northeast-2": endpoint{ + Hostname: "oidc.ap-northeast-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-northeast-2", + }, + }, + "ap-south-1": endpoint{ + Hostname: "oidc.ap-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ap-south-1", + }, + }, "ap-southeast-1": endpoint{ Hostname: "oidc.ap-southeast-1.amazonaws.com", CredentialScope: credentialScope{ @@ -3643,6 +4238,12 @@ var awsPartition = partition{ Region: "eu-central-1", }, }, + "eu-north-1": endpoint{ + Hostname: "oidc.eu-north-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-north-1", + }, + }, "eu-west-1": endpoint{ Hostname: "oidc.eu-west-1.amazonaws.com", CredentialScope: credentialScope{ @@ -3731,22 +4332,56 @@ var awsPartition = partition{ "outposts": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": 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-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, - "me-south-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "fips-ca-central-1": endpoint{ + Hostname: "outposts-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, + "fips-us-east-1": endpoint{ + Hostname: "outposts-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "outposts-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-1": endpoint{ + Hostname: "outposts-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "outposts-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "pinpoint": service{ @@ -3756,10 +4391,14 @@ var awsPartition = partition{ }, }, Endpoints: endpoints{ + "ap-northeast-1": endpoint{}, + "ap-northeast-2": endpoint{}, "ap-south-1": endpoint{}, "ap-southeast-2": endpoint{}, + "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, "fips-us-east-1": endpoint{ Hostname: "pinpoint-fips.us-east-1.amazonaws.com", CredentialScope: credentialScope{ @@ -3921,6 +4560,7 @@ var awsPartition = partition{ "ram": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -3930,6 +4570,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -3944,6 +4585,7 @@ var awsPartition = partition{ "rds": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -3953,11 +4595,42 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, "me-south-1": endpoint{}, - "sa-east-1": endpoint{}, + "rds-fips.ca-central-1": endpoint{ + Hostname: "rds-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, + "rds-fips.us-east-1": endpoint{ + Hostname: "rds-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "rds-fips.us-east-2": endpoint{ + Hostname: "rds-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "rds-fips.us-west-1": endpoint{ + Hostname: "rds-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "rds-fips.us-west-2": endpoint{ + Hostname: "rds-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "sa-east-1": endpoint{}, "us-east-1": endpoint{ SSLCommonName: "{service}.{dnsSuffix}", }, @@ -3969,6 +4642,7 @@ var awsPartition = partition{ "redshift": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -3978,6 +4652,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -4027,18 +4702,44 @@ 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{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "rekognition-fips.us-east-1": endpoint{ + Hostname: "rekognition-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "rekognition-fips.us-east-2": endpoint{ + Hostname: "rekognition-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "rekognition-fips.us-west-1": endpoint{ + Hostname: "rekognition-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "rekognition-fips.us-west-2": endpoint{ + Hostname: "rekognition-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "resource-groups": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -4048,6 +4749,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -4119,6 +4821,7 @@ var awsPartition = partition{ Protocols: []string{"https"}, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -4128,6 +4831,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -4146,8 +4850,12 @@ var awsPartition = partition{ }, }, Endpoints: endpoints{ + "ap-northeast-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-west-2": endpoint{}, }, @@ -4210,7 +4918,8 @@ var awsPartition = partition{ DualStackHostname: "{service}.dualstack.{region}.{dnsSuffix}", }, Endpoints: endpoints{ - "ap-east-1": endpoint{}, + "af-south-1": endpoint{}, + "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{ Hostname: "s3.ap-northeast-1.amazonaws.com", SignatureVersions: []string{"s3", "s3v4"}, @@ -4235,6 +4944,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{ Hostname: "s3.eu-west-1.amazonaws.com", SignatureVersions: []string{"s3", "s3v4"}, @@ -4319,6 +5029,13 @@ var awsPartition = partition{ Region: "ca-central-1", }, }, + "ca-central-1-fips": endpoint{ + Hostname: "s3-control-fips.ca-central-1.amazonaws.com", + SignatureVersions: []string{"s3v4"}, + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, "eu-central-1": endpoint{ Hostname: "s3-control.eu-central-1.amazonaws.com", SignatureVersions: []string{"s3v4"}, @@ -4435,10 +5152,22 @@ var awsPartition = partition{ "schemas": service{ Endpoints: endpoints{ + "ap-east-1": 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-north-1": endpoint{}, "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "sa-east-1": endpoint{}, "us-east-1": endpoint{}, "us-east-2": endpoint{}, + "us-west-1": endpoint{}, "us-west-2": endpoint{}, }, }, @@ -4463,6 +5192,7 @@ var awsPartition = partition{ "secretsmanager": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -4472,6 +5202,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -4510,6 +5241,7 @@ var awsPartition = partition{ "securityhub": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -4519,15 +5251,40 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, - "me-south-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "fips-us-east-1": endpoint{ + Hostname: "securityhub-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "securityhub-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-1": endpoint{ + Hostname: "securityhub-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "securityhub-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "serverlessrepo": service{ @@ -4594,6 +5351,7 @@ var awsPartition = partition{ "servicecatalog": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -4603,6 +5361,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -4661,6 +5420,33 @@ var awsPartition = partition{ "us-west-2": endpoint{}, }, }, + "servicequotas": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + }, + Endpoints: endpoints{ + "af-south-1": endpoint{}, + "ap-east-1": 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-north-1": endpoint{}, + "eu-south-1": endpoint{}, + "eu-west-1": endpoint{}, + "eu-west-2": endpoint{}, + "eu-west-3": endpoint{}, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, + }, + }, "session.qldb": service{ Endpoints: endpoints{ @@ -4676,20 +5462,21 @@ var awsPartition = partition{ }, }, "shield": service{ - IsRegionalized: boxedFalse, + PartitionEndpoint: "aws-global", + IsRegionalized: boxedFalse, Defaults: endpoint{ SSLCommonName: "shield.us-east-1.amazonaws.com", Protocols: []string{"https"}, }, Endpoints: endpoints{ - "fips-us-east-1": endpoint{ - Hostname: "shield-fips.us-east-1.amazonaws.com", + "aws-global": endpoint{ + Hostname: "shield.us-east-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-east-1", }, }, - "us-east-1": endpoint{ - Hostname: "shield.us-east-1.amazonaws.com", + "fips-aws-global": endpoint{ + Hostname: "shield-fips.us-east-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-east-1", }, @@ -4699,6 +5486,7 @@ var awsPartition = partition{ "sms": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -4708,6 +5496,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -4746,6 +5535,7 @@ var awsPartition = partition{ "snowball": service{ Endpoints: endpoints{ + "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, "ap-south-1": endpoint{}, @@ -4753,6 +5543,7 @@ var awsPartition = partition{ "ap-southeast-2": endpoint{}, "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, + "eu-north-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -4858,6 +5649,7 @@ var awsPartition = partition{ Protocols: []string{"http", "https"}, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -4867,6 +5659,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -4908,6 +5701,7 @@ var awsPartition = partition{ Protocols: []string{"http", "https"}, }, Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -4917,6 +5711,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -4957,6 +5752,7 @@ var awsPartition = partition{ "ssm": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -4966,6 +5762,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -5028,6 +5825,7 @@ var awsPartition = partition{ "states": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -5037,6 +5835,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -5075,6 +5874,7 @@ var awsPartition = partition{ "storagegateway": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -5084,15 +5884,22 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, - "me-south-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "fips": endpoint{ + Hostname: "storagegateway-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, + "me-south-1": endpoint{}, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "streams.dynamodb": service{ @@ -5163,6 +5970,7 @@ var awsPartition = partition{ PartitionEndpoint: "aws-global", Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -5178,6 +5986,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -5228,6 +6037,7 @@ var awsPartition = partition{ "swf": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -5237,6 +6047,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -5275,6 +6086,7 @@ var awsPartition = partition{ "tagging": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -5284,6 +6096,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -5368,11 +6181,41 @@ var awsPartition = partition{ "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, + "fips-ca-central-1": endpoint{ + Hostname: "transfer-fips.ca-central-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "ca-central-1", + }, + }, + "fips-us-east-1": endpoint{ + Hostname: "transfer-fips.us-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-1", + }, + }, + "fips-us-east-2": endpoint{ + Hostname: "transfer-fips.us-east-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-east-2", + }, + }, + "fips-us-west-1": endpoint{ + Hostname: "transfer-fips.us-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-1", + }, + }, + "fips-us-west-2": endpoint{ + Hostname: "transfer-fips.us-west-2.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-west-2", + }, + }, + "sa-east-1": endpoint{}, + "us-east-1": endpoint{}, + "us-east-2": endpoint{}, + "us-west-1": endpoint{}, + "us-west-2": endpoint{}, }, }, "translate": service{ @@ -5438,6 +6281,12 @@ var awsPartition = partition{ "waf-regional": service{ Endpoints: endpoints{ + "af-south-1": endpoint{ + Hostname: "waf-regional.af-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "af-south-1", + }, + }, "ap-east-1": endpoint{ Hostname: "waf-regional.ap-east-1.amazonaws.com", CredentialScope: credentialScope{ @@ -5492,6 +6341,12 @@ var awsPartition = partition{ Region: "eu-north-1", }, }, + "eu-south-1": endpoint{ + Hostname: "waf-regional.eu-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-south-1", + }, + }, "eu-west-1": endpoint{ Hostname: "waf-regional.eu-west-1.amazonaws.com", CredentialScope: credentialScope{ @@ -5510,6 +6365,12 @@ var awsPartition = partition{ Region: "eu-west-3", }, }, + "fips-af-south-1": endpoint{ + Hostname: "waf-regional-fips.af-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "af-south-1", + }, + }, "fips-ap-east-1": endpoint{ Hostname: "waf-regional-fips.ap-east-1.amazonaws.com", CredentialScope: credentialScope{ @@ -5564,6 +6425,12 @@ var awsPartition = partition{ Region: "eu-north-1", }, }, + "fips-eu-south-1": endpoint{ + Hostname: "waf-regional-fips.eu-south-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "eu-south-1", + }, + }, "fips-eu-west-1": endpoint{ Hostname: "waf-regional-fips.eu-west-1.amazonaws.com", CredentialScope: credentialScope{ @@ -5708,6 +6575,7 @@ var awsPartition = partition{ "xray": service{ Endpoints: endpoints{ + "af-south-1": endpoint{}, "ap-east-1": endpoint{}, "ap-northeast-1": endpoint{}, "ap-northeast-2": endpoint{}, @@ -5717,6 +6585,7 @@ var awsPartition = partition{ "ca-central-1": endpoint{}, "eu-central-1": endpoint{}, "eu-north-1": endpoint{}, + "eu-south-1": endpoint{}, "eu-west-1": endpoint{}, "eu-west-2": endpoint{}, "eu-west-3": endpoint{}, @@ -5760,6 +6629,13 @@ var awscnPartition = partition{ }, }, Services: services{ + "access-analyzer": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, "acm": service{ Endpoints: endpoints{ @@ -5829,6 +6705,15 @@ var awscnPartition = partition{ "cn-northwest-1": endpoint{}, }, }, + "autoscaling-plans": service{ + Defaults: endpoint{ + Protocols: []string{"http", "https"}, + }, + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, "backup": service{ Endpoints: endpoints{ @@ -5843,6 +6728,32 @@ var awscnPartition = partition{ "cn-northwest-1": endpoint{}, }, }, + "budgets": service{ + PartitionEndpoint: "aws-cn-global", + IsRegionalized: boxedFalse, + + Endpoints: endpoints{ + "aws-cn-global": endpoint{ + Hostname: "budgets.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + }, + }, + "ce": service{ + PartitionEndpoint: "aws-cn-global", + IsRegionalized: boxedFalse, + + Endpoints: endpoints{ + "aws-cn-global": endpoint{ + Hostname: "ce.cn-northwest-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + }, + }, "cloudformation": service{ Endpoints: endpoints{ @@ -5878,6 +6789,13 @@ var awscnPartition = partition{ "cn-northwest-1": endpoint{}, }, }, + "codecommit": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, "codedeploy": service{ Endpoints: endpoints{ @@ -5898,6 +6816,12 @@ var awscnPartition = partition{ "cn-northwest-1": endpoint{}, }, }, + "cur": service{ + + Endpoints: endpoints{ + "cn-northwest-1": endpoint{}, + }, + }, "dax": service{ Endpoints: endpoints{ @@ -5934,6 +6858,13 @@ var awscnPartition = partition{ "cn-northwest-1": endpoint{}, }, }, + "ebs": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, "ec2": service{ Defaults: endpoint{ Protocols: []string{"http", "https"}, @@ -5961,6 +6892,15 @@ var awscnPartition = partition{ "cn-northwest-1": endpoint{}, }, }, + "eks": service{ + Defaults: endpoint{ + Protocols: []string{"http", "https"}, + }, + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, "elasticache": service{ Endpoints: endpoints{ @@ -6116,6 +7056,13 @@ var awscnPartition = partition{ "cn-northwest-1": endpoint{}, }, }, + "kinesisanalytics": service{ + + Endpoints: endpoints{ + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, + }, + }, "kms": service{ Endpoints: endpoints{ @@ -6175,6 +7122,25 @@ var awscnPartition = partition{ }, }, }, + "organizations": service{ + PartitionEndpoint: "aws-cn-global", + IsRegionalized: boxedFalse, + + Endpoints: endpoints{ + "aws-cn-global": endpoint{ + Hostname: "organizations.cn-northwest-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + "fips-aws-cn-global": endpoint{ + Hostname: "organizations.cn-northwest-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + }, + }, "polly": service{ Endpoints: endpoints{ @@ -6195,6 +7161,19 @@ var awscnPartition = partition{ "cn-northwest-1": endpoint{}, }, }, + "route53": service{ + PartitionEndpoint: "aws-cn-global", + IsRegionalized: boxedFalse, + + Endpoints: endpoints{ + "aws-cn-global": endpoint{ + Hostname: "route53.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, + }, + }, "runtime.sagemaker": service{ Endpoints: endpoints{ @@ -6206,6 +7185,9 @@ var awscnPartition = partition{ Defaults: endpoint{ Protocols: []string{"http", "https"}, SignatureVersions: []string{"s3v4"}, + + HasDualStack: boxedTrue, + DualStackHostname: "{service}.dualstack.{region}.{dnsSuffix}", }, Endpoints: endpoints{ "cn-north-1": endpoint{}, @@ -6216,6 +7198,9 @@ var awscnPartition = partition{ Defaults: endpoint{ Protocols: []string{"https"}, SignatureVersions: []string{"s3v4"}, + + HasDualStack: boxedTrue, + DualStackHostname: "{service}.dualstack.{region}.{dnsSuffix}", }, Endpoints: endpoints{ "cn-north-1": endpoint{ @@ -6264,13 +7249,20 @@ var awscnPartition = partition{ "snowball": service{ Endpoints: endpoints{ - "cn-north-1": endpoint{}, + "cn-north-1": endpoint{}, + "cn-northwest-1": endpoint{}, "fips-cn-north-1": endpoint{ Hostname: "snowball-fips.cn-north-1.amazonaws.com.cn", CredentialScope: credentialScope{ Region: "cn-north-1", }, }, + "fips-cn-northwest-1": endpoint{ + Hostname: "snowball-fips.cn-northwest-1.amazonaws.com.cn", + CredentialScope: credentialScope{ + Region: "cn-northwest-1", + }, + }, }, }, "sns": service{ @@ -6418,15 +7410,25 @@ var awsusgovPartition = partition{ Description: "AWS GovCloud (US-East)", }, "us-gov-west-1": region{ - Description: "AWS GovCloud (US)", + Description: "AWS GovCloud (US-West)", }, }, Services: services{ "access-analyzer": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, - "us-gov-west-1": endpoint{}, + "us-gov-east-1": endpoint{ + Hostname: "access-analyzer.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "us-gov-west-1": endpoint{ + Hostname: "access-analyzer.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "acm": service{ @@ -6441,6 +7443,18 @@ var awsusgovPartition = partition{ Protocols: []string{"https"}, }, Endpoints: endpoints{ + "fips-us-gov-east-1": endpoint{ + Hostname: "acm-pca.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "fips-us-gov-west-1": endpoint{ + Hostname: "acm-pca.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, @@ -6448,6 +7462,18 @@ var awsusgovPartition = partition{ "api.ecr": service{ Endpoints: endpoints{ + "fips-dkr-us-gov-east-1": endpoint{ + Hostname: "ecr-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "fips-dkr-us-gov-west-1": endpoint{ + Hostname: "ecr-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "fips-us-gov-east-1": endpoint{ Hostname: "ecr-fips.us-gov-east-1.amazonaws.com", CredentialScope: credentialScope{ @@ -6478,6 +7504,18 @@ var awsusgovPartition = partition{ Endpoints: endpoints{ "us-gov-west-1": endpoint{}, + "us-gov-west-1-fips": endpoint{ + Hostname: "api-fips.sagemaker.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + "us-gov-west-1-fips-secondary": endpoint{ + Hostname: "api.sagemaker.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "apigateway": service{ @@ -6539,7 +7577,9 @@ var awsusgovPartition = partition{ "autoscaling": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, + "us-gov-east-1": endpoint{ + Protocols: []string{"http", "https"}, + }, "us-gov-west-1": endpoint{ Protocols: []string{"http", "https"}, }, @@ -6554,21 +7594,30 @@ var awsusgovPartition = partition{ "us-gov-west-1": endpoint{}, }, }, + "backup": service{ + + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, "batch": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{ + "fips-us-gov-east-1": endpoint{ Hostname: "batch.us-gov-east-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-gov-east-1", }, }, - "us-gov-west-1": endpoint{ + "fips-us-gov-west-1": endpoint{ Hostname: "batch.us-gov-west-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-gov-west-1", }, }, + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, }, }, "clouddirectory": service{ @@ -6580,8 +7629,18 @@ var awsusgovPartition = partition{ "cloudformation": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, - "us-gov-west-1": endpoint{}, + "us-gov-east-1": endpoint{ + Hostname: "cloudformation.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "us-gov-west-1": endpoint{ + Hostname: "cloudformation.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "cloudhsm": service{ @@ -6604,8 +7663,18 @@ var awsusgovPartition = partition{ "cloudtrail": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, - "us-gov-west-1": endpoint{}, + "us-gov-east-1": endpoint{ + Hostname: "cloudtrail.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "us-gov-west-1": endpoint{ + Hostname: "cloudtrail.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "codebuild": service{ @@ -6671,6 +7740,24 @@ var awsusgovPartition = partition{ "us-gov-west-1": endpoint{}, }, }, + "cognito-identity": service{ + + Endpoints: endpoints{ + "us-gov-west-1": endpoint{}, + }, + }, + "cognito-idp": service{ + + Endpoints: endpoints{ + "fips-us-gov-west-1": endpoint{ + Hostname: "cognito-idp-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + "us-gov-west-1": endpoint{}, + }, + }, "comprehend": service{ Defaults: endpoint{ Protocols: []string{"https"}, @@ -6688,6 +7775,12 @@ var awsusgovPartition = partition{ "comprehendmedical": service{ Endpoints: endpoints{ + "fips-us-gov-west-1": endpoint{ + Hostname: "comprehendmedical-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "us-gov-west-1": endpoint{}, }, }, @@ -6747,9 +7840,32 @@ var awsusgovPartition = partition{ "us-gov-west-1": endpoint{}, }, }, + "docdb": service{ + + Endpoints: endpoints{ + "us-gov-west-1": endpoint{ + Hostname: "rds.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + }, + }, "ds": service{ Endpoints: endpoints{ + "fips-us-gov-east-1": endpoint{ + Hostname: "ds-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "fips-us-gov-west-1": endpoint{ + Hostname: "ds-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, @@ -6773,6 +7889,13 @@ var awsusgovPartition = partition{ }, }, }, + "ebs": service{ + + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, "ec2": service{ Endpoints: endpoints{ @@ -6820,11 +7943,20 @@ var awsusgovPartition = partition{ "us-gov-west-1": endpoint{}, }, }, + "eks": service{ + Defaults: endpoint{ + Protocols: []string{"http", "https"}, + }, + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, "elasticache": service{ Endpoints: endpoints{ "fips": endpoint{ - Hostname: "elasticache-fips.us-gov-west-1.amazonaws.com", + Hostname: "elasticache.us-gov-west-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-gov-west-1", }, @@ -6872,6 +8004,18 @@ var awsusgovPartition = partition{ "elasticloadbalancing": service{ Endpoints: endpoints{ + "fips-us-gov-east-1": endpoint{ + Hostname: "elasticloadbalancing.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "fips-us-gov-west-1": endpoint{ + Hostname: "elasticloadbalancing.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{ Protocols: []string{"http", "https"}, @@ -6881,12 +8025,36 @@ var awsusgovPartition = partition{ "elasticmapreduce": service{ Endpoints: endpoints{ + "fips-us-gov-east-1": endpoint{ + Hostname: "elasticmapreduce.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "fips-us-gov-west-1": endpoint{ + Hostname: "elasticmapreduce.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{ Protocols: []string{"https"}, }, }, }, + "email": service{ + + Endpoints: endpoints{ + "fips-us-gov-west-1": endpoint{ + Hostname: "email-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + "us-gov-west-1": endpoint{}, + }, + }, "es": service{ Endpoints: endpoints{ @@ -6903,8 +8071,18 @@ var awsusgovPartition = partition{ "events": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, - "us-gov-west-1": endpoint{}, + "us-gov-east-1": endpoint{ + Hostname: "events.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "us-gov-west-1": endpoint{ + Hostname: "events.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "firehose": service{ @@ -6969,7 +8147,12 @@ var awsusgovPartition = partition{ Protocols: []string{"https"}, }, Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, + "us-gov-west-1": endpoint{ + Hostname: "greengrass.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "guardduty": service{ @@ -6979,6 +8162,12 @@ var awsusgovPartition = partition{ }, Endpoints: endpoints{ "us-gov-west-1": endpoint{}, + "us-gov-west-1-fips": endpoint{ + Hostname: "guardduty.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "health": service{ @@ -6998,6 +8187,12 @@ var awsusgovPartition = partition{ Region: "us-gov-west-1", }, }, + "iam-govcloud-fips": endpoint{ + Hostname: "iam.us-gov.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "inspector": service{ @@ -7026,17 +8221,43 @@ var awsusgovPartition = partition{ }, }, Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, }, "iotsecuredtunneling": service{ Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, + "kafka": service{ + + Endpoints: endpoints{ + "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, }, "kinesis": service{ + Endpoints: endpoints{ + "us-gov-east-1": endpoint{ + Hostname: "kinesis.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "us-gov-west-1": endpoint{ + Hostname: "kinesis.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + }, + }, + "kinesisanalytics": service{ + Endpoints: endpoints{ "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, @@ -7096,14 +8317,29 @@ var awsusgovPartition = partition{ "logs": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, - "us-gov-west-1": endpoint{}, + "us-gov-east-1": endpoint{ + Hostname: "logs.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "us-gov-west-1": endpoint{ + Hostname: "logs.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "mediaconvert": service{ Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, + "us-gov-west-1": endpoint{ + Hostname: "mediaconvert.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "metering.marketplace": service{ @@ -7164,12 +8400,38 @@ var awsusgovPartition = partition{ Region: "us-gov-west-1", }, }, + "fips-aws-us-gov-global": endpoint{ + Hostname: "organizations.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "outposts": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, + "us-gov-east-1": endpoint{ + Hostname: "outposts.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "us-gov-west-1": endpoint{ + Hostname: "outposts.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + }, + }, + "pinpoint": service{ + Defaults: endpoint{ + CredentialScope: credentialScope{ + Service: "mobiletargeting", + }, + }, + Endpoints: endpoints{ "us-gov-west-1": endpoint{}, }, }, @@ -7195,6 +8457,18 @@ var awsusgovPartition = partition{ "rds": service{ Endpoints: endpoints{ + "rds.us-gov-east-1": endpoint{ + Hostname: "rds.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "rds.us-gov-west-1": endpoint{ + Hostname: "rds.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, @@ -7219,6 +8493,12 @@ var awsusgovPartition = partition{ "rekognition": service{ Endpoints: endpoints{ + "rekognition-fips.us-gov-west-1": endpoint{ + Hostname: "rekognition-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "us-gov-west-1": endpoint{}, }, }, @@ -7270,10 +8550,13 @@ var awsusgovPartition = partition{ "s3": service{ Defaults: endpoint{ SignatureVersions: []string{"s3", "s3v4"}, + + HasDualStack: boxedTrue, + DualStackHostname: "{service}.dualstack.{region}.{dnsSuffix}", }, Endpoints: endpoints{ "fips-us-gov-west-1": endpoint{ - Hostname: "s3-fips-us-gov-west-1.amazonaws.com", + Hostname: "s3-fips.us-gov-west-1.amazonaws.com", CredentialScope: credentialScope{ Region: "us-gov-west-1", }, @@ -7292,6 +8575,9 @@ var awsusgovPartition = partition{ Defaults: endpoint{ Protocols: []string{"https"}, SignatureVersions: []string{"s3v4"}, + + HasDualStack: boxedTrue, + DualStackHostname: "{service}.dualstack.{region}.{dnsSuffix}", }, Endpoints: endpoints{ "us-gov-east-1": endpoint{ @@ -7343,16 +8629,43 @@ var awsusgovPartition = partition{ }, }, }, + "securityhub": service{ + + Endpoints: endpoints{ + "fips-us-gov-east-1": endpoint{ + Hostname: "securityhub-fips.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "fips-us-gov-west-1": endpoint{ + Hostname: "securityhub-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + "us-gov-east-1": endpoint{}, + "us-gov-west-1": endpoint{}, + }, + }, "serverlessrepo": service{ Defaults: endpoint{ Protocols: []string{"https"}, }, Endpoints: endpoints{ "us-gov-east-1": endpoint{ + Hostname: "serverlessrepo.us-gov-east-1.amazonaws.com", Protocols: []string{"https"}, + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, }, "us-gov-west-1": endpoint{ + Hostname: "serverlessrepo.us-gov-west-1.amazonaws.com", Protocols: []string{"https"}, + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, }, }, }, @@ -7416,25 +8729,67 @@ var awsusgovPartition = partition{ "sns": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, + "us-gov-east-1": endpoint{ + Hostname: "sns.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, "us-gov-west-1": endpoint{ + Hostname: "sns.us-gov-west-1.amazonaws.com", Protocols: []string{"http", "https"}, + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, }, }, }, "sqs": service{ Endpoints: endpoints{ - "us-gov-east-1": endpoint{}, + "us-gov-east-1": endpoint{ + Hostname: "sqs.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, "us-gov-west-1": endpoint{ + Hostname: "sqs.us-gov-west-1.amazonaws.com", SSLCommonName: "{region}.queue.{dnsSuffix}", Protocols: []string{"http", "https"}, + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, }, }, }, "ssm": service{ Endpoints: endpoints{ + "fips-us-gov-east-1": endpoint{ + Hostname: "ssm.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "fips-us-gov-west-1": endpoint{ + Hostname: "ssm.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, + "ssm-facade-fips-us-gov-east-1": endpoint{ + Hostname: "ssm-facade.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, + "ssm-facade-fips-us-gov-west-1": endpoint{ + Hostname: "ssm-facade.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, @@ -7461,6 +8816,12 @@ var awsusgovPartition = partition{ "storagegateway": service{ Endpoints: endpoints{ + "fips": endpoint{ + Hostname: "storagegateway-fips.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, "us-gov-east-1": endpoint{}, "us-gov-west-1": endpoint{}, }, @@ -7492,7 +8853,19 @@ var awsusgovPartition = partition{ Endpoints: endpoints{ "us-gov-east-1": endpoint{}, + "us-gov-east-1-fips": endpoint{ + Hostname: "sts.us-gov-east-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-east-1", + }, + }, "us-gov-west-1": endpoint{}, + "us-gov-west-1-fips": endpoint{ + Hostname: "sts.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "support": service{ @@ -7505,6 +8878,12 @@ var awsusgovPartition = partition{ Region: "us-gov-west-1", }, }, + "fips-us-gov-west-1": endpoint{ + Hostname: "support.us-gov-west-1.amazonaws.com", + CredentialScope: credentialScope{ + Region: "us-gov-west-1", + }, + }, }, }, "swf": service{ @@ -7682,6 +9061,14 @@ var awsisoPartition = partition{ "us-iso-east-1": endpoint{}, }, }, + "comprehend": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + }, + Endpoints: endpoints{ + "us-iso-east-1": endpoint{}, + }, + }, "config": service{ Endpoints: endpoints{ @@ -7771,6 +9158,12 @@ var awsisoPartition = partition{ }, }, }, + "es": service{ + + Endpoints: endpoints{ + "us-iso-east-1": endpoint{}, + }, + }, "events": service{ Endpoints: endpoints{ @@ -7947,6 +9340,20 @@ var awsisoPartition = partition{ "us-iso-east-1": endpoint{}, }, }, + "transcribe": service{ + Defaults: endpoint{ + Protocols: []string{"https"}, + }, + Endpoints: endpoints{ + "us-iso-east-1": endpoint{}, + }, + }, + "transcribestreaming": service{ + + Endpoints: endpoints{ + "us-iso-east-1": endpoint{}, + }, + }, "workspaces": service{ Endpoints: endpoints{ @@ -8130,6 +9537,12 @@ var awsisobPartition = partition{ "us-isob-east-1": endpoint{}, }, }, + "lambda": service{ + + Endpoints: endpoints{ + "us-isob-east-1": endpoint{}, + }, + }, "license-manager": service{ Endpoints: endpoints{ 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 eb2ac83c9..773613722 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 @@ -7,6 +7,8 @@ import ( "strings" ) +var regionValidationRegex = regexp.MustCompile(`^[[:alnum:]]([[:alnum:]\-]*[[:alnum:]])?$`) + type partitions []partition func (ps partitions) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) { @@ -124,7 +126,7 @@ func (p partition) EndpointFor(service, region string, opts ...func(*Options)) ( defs := []endpoint{p.Defaults, s.Defaults} - return e.resolve(service, p.ID, region, p.DNSSuffix, defs, opt), nil + return e.resolve(service, p.ID, region, p.DNSSuffix, defs, opt) } func serviceList(ss services) []string { @@ -233,7 +235,7 @@ func getByPriority(s []string, p []string, def string) string { return s[0] } -func (e endpoint) resolve(service, partitionID, region, dnsSuffix string, defs []endpoint, opts Options) ResolvedEndpoint { +func (e endpoint) resolve(service, partitionID, region, dnsSuffix string, defs []endpoint, opts Options) (ResolvedEndpoint, error) { var merged endpoint for _, def := range defs { merged.mergeIn(def) @@ -260,6 +262,10 @@ func (e endpoint) resolve(service, partitionID, region, dnsSuffix string, defs [ region = signingRegion } + if !validateInputRegion(region) { + return ResolvedEndpoint{}, fmt.Errorf("invalid region identifier format provided") + } + u := strings.Replace(hostname, "{service}", service, 1) u = strings.Replace(u, "{region}", region, 1) u = strings.Replace(u, "{dnsSuffix}", dnsSuffix, 1) @@ -274,7 +280,7 @@ func (e endpoint) resolve(service, partitionID, region, dnsSuffix string, defs [ SigningName: signingName, SigningNameDerived: signingNameDerived, SigningMethod: getByPriority(e.SignatureVersions, signerPriority, defaultSigner), - } + }, nil } func getEndpointScheme(protocols []string, disableSSL bool) string { @@ -339,3 +345,7 @@ const ( boxedFalse boxedTrue ) + +func validateInputRegion(region string) bool { + return regionValidationRegex.MatchString(region) +} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go b/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go index d9b37f4d3..2ba3c56c1 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go @@ -9,7 +9,8 @@ func isErrConnectionReset(err error) bool { return false } - if strings.Contains(err.Error(), "connection reset") || + if strings.Contains(err.Error(), "use of closed network connection") || + strings.Contains(err.Error(), "connection reset") || strings.Contains(err.Error(), "broken pipe") { return true } 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 7ec66e7e5..cc461bd32 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 @@ -241,5 +241,22 @@ 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. + +The endpoint of the EC2 IMDS client can be configured via the environment +variable, AWS_EC2_METADATA_SERVICE_ENDPOINT when creating the client with a +Session. See Options.EC2IMDSEndpoint for more details. + + AWS_EC2_METADATA_SERVICE_ENDPOINT=http://169.254.169.254 + +If using an URL with an IPv6 address literal, the IPv6 address +component must be enclosed in square brackets. + + AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1] + +The custom EC2 IMDS endpoint can also be specified via the Session options. + + sess, err := session.NewSessionWithOptions(session.Options{ + EC2IMDSEndpoint: "http://[::1]", + }) */ 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 c1e0e9c95..d67c261d7 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 @@ -148,6 +148,11 @@ type envConfig struct { // // AWS_S3_USE_ARN_REGION=true S3UseARNRegion bool + + // Specifies the alternative endpoint to use for EC2 IMDS. + // + // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1] + EC2IMDSEndpoint string } var ( @@ -211,6 +216,9 @@ var ( s3UseARNRegionEnvKey = []string{ "AWS_S3_USE_ARN_REGION", } + ec2IMDSEndpointEnvKey = []string{ + "AWS_EC2_METADATA_SERVICE_ENDPOINT", + } ) // loadEnvConfig retrieves the SDK's environment configuration. @@ -332,6 +340,8 @@ func envConfigLoad(enableSharedConfig bool) (envConfig, error) { } } + setFromEnvVal(&cfg.EC2IMDSEndpoint, ec2IMDSEndpointEnvKey) + return cfg, nil } 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 0ff499605..6430a7f15 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 @@ -48,6 +48,8 @@ var ErrSharedConfigInvalidCredSource = awserr.New(ErrCodeSharedConfig, "credenti type Session struct { Config *aws.Config Handlers request.Handlers + + options Options } // New creates a new instance of the handlers merging in the provided configs @@ -99,7 +101,7 @@ func New(cfgs ...*aws.Config) *Session { return s } - s := deprecatedNewSession(cfgs...) + s := deprecatedNewSession(envCfg, cfgs...) if envErr != nil { msg := "failed to load env config" s.logDeprecatedNewSessionError(msg, envErr, cfgs) @@ -243,6 +245,23 @@ type Options struct { // function to initialize this value before changing the handlers to be // used by the SDK. Handlers request.Handlers + + // Allows specifying a custom endpoint to be used by the EC2 IMDS client + // when making requests to the EC2 IMDS API. The must endpoint value must + // include protocol prefix. + // + // If unset, will the EC2 IMDS client will use its default endpoint. + // + // Can also be specified via the environment variable, + // AWS_EC2_METADATA_SERVICE_ENDPOINT. + // + // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://169.254.169.254 + // + // If using an URL with an IPv6 address literal, the IPv6 address + // component must be enclosed in square brackets. + // + // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1] + EC2IMDSEndpoint string } // NewSessionWithOptions returns a new Session created from SDK defaults, config files, @@ -329,7 +348,25 @@ func Must(sess *Session, err error) *Session { return sess } -func deprecatedNewSession(cfgs ...*aws.Config) *Session { +// Wraps the endpoint resolver with a resolver that will return a custom +// endpoint for EC2 IMDS. +func wrapEC2IMDSEndpoint(resolver endpoints.Resolver, endpoint string) endpoints.Resolver { + return endpoints.ResolverFunc( + func(service, region string, opts ...func(*endpoints.Options)) ( + endpoints.ResolvedEndpoint, error, + ) { + if service == ec2MetadataServiceID { + return endpoints.ResolvedEndpoint{ + URL: endpoint, + SigningName: ec2MetadataServiceID, + SigningRegion: region, + }, nil + } + return resolver.EndpointFor(service, region) + }) +} + +func deprecatedNewSession(envCfg envConfig, cfgs ...*aws.Config) *Session { cfg := defaults.Config() handlers := defaults.Handlers() @@ -341,6 +378,11 @@ func deprecatedNewSession(cfgs ...*aws.Config) *Session { // endpoints for service client configurations. cfg.EndpointResolver = endpoints.DefaultResolver() } + + if len(envCfg.EC2IMDSEndpoint) != 0 { + cfg.EndpointResolver = wrapEC2IMDSEndpoint(cfg.EndpointResolver, envCfg.EC2IMDSEndpoint) + } + cfg.Credentials = defaults.CredChain(cfg, handlers) // Reapply any passed in configs to override credentials if set @@ -349,6 +391,9 @@ func deprecatedNewSession(cfgs ...*aws.Config) *Session { s := &Session{ Config: cfg, Handlers: handlers, + options: Options{ + EC2IMDSEndpoint: envCfg.EC2IMDSEndpoint, + }, } initHandlers(s) @@ -418,6 +463,7 @@ func newSession(opts Options, envCfg envConfig, cfgs ...*aws.Config) (*Session, s := &Session{ Config: cfg, Handlers: handlers, + options: opts, } initHandlers(s) @@ -570,6 +616,14 @@ func mergeConfigSrcs(cfg, userCfg *aws.Config, endpoints.LegacyS3UsEast1Endpoint, }) + ec2IMDSEndpoint := sessOpts.EC2IMDSEndpoint + if len(ec2IMDSEndpoint) == 0 { + ec2IMDSEndpoint = envCfg.EC2IMDSEndpoint + } + if len(ec2IMDSEndpoint) != 0 { + cfg.EndpointResolver = wrapEC2IMDSEndpoint(cfg.EndpointResolver, ec2IMDSEndpoint) + } + // Configure credentials if not already set by the user when creating the // Session. if cfg.Credentials == credentials.AnonymousCredentials && userCfg.Credentials == nil { @@ -627,6 +681,7 @@ func (s *Session) Copy(cfgs ...*aws.Config) *Session { newSession := &Session{ Config: s.Config.Copy(cfgs...), Handlers: s.Handlers.Copy(), + options: s.options, } initHandlers(newSession) @@ -665,6 +720,8 @@ func (s *Session) ClientConfig(service string, cfgs ...*aws.Config) client.Confi } } +const ec2MetadataServiceID = "ec2metadata" + func (s *Session) resolveEndpoint(service, region string, cfg *aws.Config) (endpoints.ResolvedEndpoint, error) { if ep := aws.StringValue(cfg.Endpoint); len(ep) != 0 { 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 d542ef01b..98751ee84 100644 --- a/vendor/github.com/aws/aws-sdk-go/aws/types.go +++ b/vendor/github.com/aws/aws-sdk-go/aws/types.go @@ -239,3 +239,26 @@ func (es errors) Error() string { return strings.Join(parts, "\n") } + +// CopySeekableBody copies the seekable body to an io.Writer +func CopySeekableBody(dst io.Writer, src io.ReadSeeker) (int64, error) { + curPos, err := src.Seek(0, sdkio.SeekCurrent) + if err != nil { + return 0, err + } + + // copy errors may be assumed to be from the body. + n, err := io.Copy(dst, src) + if err != nil { + return n, err + } + + // seek back to the first position after reading to reset + // the body for transmission. + _, err = src.Seek(curPos, sdkio.SeekStart) + if err != nil { + return n, err + } + + return n, nil +} 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 a972f14a1..e1173b7b5 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.30.8" +const SDKVersion = "1.34.26" diff --git a/vendor/github.com/aws/aws-sdk-go/private/checksum/content_md5.go b/vendor/github.com/aws/aws-sdk-go/private/checksum/content_md5.go new file mode 100644 index 000000000..e045f38d8 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/private/checksum/content_md5.go @@ -0,0 +1,53 @@ +package checksum + +import ( + "crypto/md5" + "encoding/base64" + "fmt" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" + "github.com/aws/aws-sdk-go/aws/request" +) + +const contentMD5Header = "Content-Md5" + +// AddBodyContentMD5Handler computes and sets the HTTP Content-MD5 header for requests that +// require it. +func AddBodyContentMD5Handler(r *request.Request) { + // if Content-MD5 header is already present, return + if v := r.HTTPRequest.Header.Get(contentMD5Header); len(v) != 0 { + return + } + + // if S3DisableContentMD5Validation flag is set, return + if aws.BoolValue(r.Config.S3DisableContentMD5Validation) { + return + } + + // if request is presigned, return + if r.IsPresigned() { + return + } + + // if body is not seekable, return + if !aws.IsReaderSeekable(r.Body) { + if r.Config.Logger != nil { + r.Config.Logger.Log(fmt.Sprintf( + "Unable to compute Content-MD5 for unseekable body, S3.%s", + r.Operation.Name)) + } + return + } + + h := md5.New() + + if _, err := aws.CopySeekableBody(h, r.Body); err != nil { + r.Error = awserr.New("ContentMD5", "failed to compute body MD5", err) + return + } + + // encode the md5 checksum in base64 and set the request header. + v := base64.StdEncoding.EncodeToString(h.Sum(nil)) + r.HTTPRequest.Header.Set(contentMD5Header, v) +} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/reader.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/reader.go index bb8ea5da1..0e4aa42f3 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/reader.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi/reader.go @@ -69,10 +69,23 @@ func (r *EventReader) ReadEvent() (event interface{}, err error) { case ErrorMessageType: return nil, r.unmarshalErrorMessage(msg) default: - return nil, fmt.Errorf("unknown eventstream message type, %v", typ) + return nil, &UnknownMessageTypeError{ + Type: typ, Message: msg.Clone(), + } } } +// UnknownMessageTypeError provides an error when a message is received from +// the stream, but the reader is unable to determine what kind of message it is. +type UnknownMessageTypeError struct { + Type string + Message eventstream.Message +} + +func (e *UnknownMessageTypeError) Error() string { + return "unknown eventstream message type, " + e.Type +} + func (r *EventReader) unmarshalEventMessage( msg eventstream.Message, ) (event interface{}, err error) { diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header.go index 3b44dde2f..f6f8c5674 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/header.go @@ -52,6 +52,15 @@ func (hs *Headers) Del(name string) { } } +// Clone returns a deep copy of the headers +func (hs Headers) Clone() Headers { + o := make(Headers, 0, len(hs)) + for _, h := range hs { + o.Set(h.Name, h.Value) + } + return o +} + func decodeHeaders(r io.Reader) (Headers, error) { hs := Headers{} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/message.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/message.go index 25c9783cd..f7427da03 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/message.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/message.go @@ -57,6 +57,20 @@ func (m *Message) rawMessage() (rawMessage, error) { return raw, nil } +// Clone returns a deep copy of the message. +func (m Message) Clone() Message { + var payload []byte + if m.Payload != nil { + payload = make([]byte, len(m.Payload)) + copy(payload, m.Payload) + } + + return Message{ + Headers: m.Headers.Clone(), + Payload: payload, + } +} + type messagePrelude struct { Length uint32 HeadersLen uint32 diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go index 5e9499699..8b2c9bbeb 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "io" + "math/big" "reflect" "strings" "time" @@ -15,6 +16,8 @@ import ( "github.com/aws/aws-sdk-go/private/protocol" ) +var millisecondsFloat = new(big.Float).SetInt64(1e3) + // UnmarshalJSONError unmarshal's the reader's JSON document into the passed in // type. The value to unmarshal the json document into must be a pointer to the // type. @@ -39,7 +42,9 @@ func UnmarshalJSONError(v interface{}, stream io.Reader) error { func UnmarshalJSON(v interface{}, stream io.Reader) error { var out interface{} - err := json.NewDecoder(stream).Decode(&out) + decoder := json.NewDecoder(stream) + decoder.UseNumber() + err := decoder.Decode(&out) if err == io.EOF { return nil } else if err != nil { @@ -54,7 +59,9 @@ func UnmarshalJSON(v interface{}, stream io.Reader) error { func UnmarshalJSONCaseInsensitive(v interface{}, stream io.Reader) error { var out interface{} - err := json.NewDecoder(stream).Decode(&out) + decoder := json.NewDecoder(stream) + decoder.UseNumber() + err := decoder.Decode(&out) if err == io.EOF { return nil } else if err != nil { @@ -254,16 +261,31 @@ func (u unmarshaler) unmarshalScalar(value reflect.Value, data interface{}, tag default: return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type()) } - case float64: + case json.Number: switch value.Interface().(type) { case *int64: - di := int64(d) + // Retain the old behavior where we would just truncate the float64 + // calling d.Int64() here could cause an invalid syntax error due to the usage of strconv.ParseInt + f, err := d.Float64() + if err != nil { + return err + } + di := int64(f) value.Set(reflect.ValueOf(&di)) case *float64: - value.Set(reflect.ValueOf(&d)) + f, err := d.Float64() + if err != nil { + return err + } + value.Set(reflect.ValueOf(&f)) case *time.Time: - // Time unmarshaled from a float64 can only be epoch seconds - t := time.Unix(int64(d), 0).UTC() + float, ok := new(big.Float).SetString(d.String()) + if !ok { + return fmt.Errorf("unsupported float time representation: %v", d.String()) + } + float = float.Mul(float, millisecondsFloat) + ms, _ := float.Int64() + t := time.Unix(0, ms*1e6).UTC() value.Set(reflect.ValueOf(&t)) default: return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type()) diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go index 05d4ff519..98f4caed9 100644 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go +++ b/vendor/github.com/aws/aws-sdk-go/private/protocol/timestamp.go @@ -27,8 +27,8 @@ const ( // RFC3339 a subset of the ISO8601 timestamp format. e.g 2014-04-29T18:30:38Z ISO8601TimeFormat = "2006-01-02T15:04:05.999999999Z" - // This format is used for output time without seconds precision - ISO8601OutputTimeFormat = "2006-01-02T15:04:05Z" + // This format is used for output time with fractional second precision up to milliseconds + ISO8601OutputTimeFormat = "2006-01-02T15:04:05.999999999Z" ) // IsKnownTimestampFormat returns if the timestamp format name @@ -48,7 +48,7 @@ func IsKnownTimestampFormat(name string) bool { // FormatTime returns a string value of the time. func FormatTime(name string, t time.Time) string { - t = t.UTC() + t = t.UTC().Truncate(time.Millisecond) switch name { case RFC822TimeFormatName: @@ -56,7 +56,8 @@ func FormatTime(name string, t time.Time) string { case ISO8601TimeFormatName: return t.Format(ISO8601OutputTimeFormat) case UnixTimeFormatName: - return strconv.FormatInt(t.Unix(), 10) + ms := t.UnixNano() / int64(time.Millisecond) + return strconv.FormatFloat(float64(ms)/1e3, 'f', -1, 64) default: panic("unknown timestamp format name, " + name) } diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/api.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/api.go index 3d1d444aa..b3d79603e 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ec2/api.go @@ -554,6 +554,10 @@ func (c *EC2) AllocateAddressRequest(input *AllocateAddressInput) (req *request. // For more information, see Elastic IP Addresses (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) // in the Amazon Elastic Compute Cloud User Guide. // +// You can allocate a carrier IP address which is a public IP address from a +// telecommunication carrier, to a network interface which resides in a subnet +// in a Wavelength Zone (for example an EC2 instance). +// // 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. @@ -955,7 +959,8 @@ func (c *EC2) AssociateAddressRequest(input *AssociateAddressInput) (req *reques // AssociateAddress API operation for Amazon Elastic Compute Cloud. // -// Associates an Elastic IP address with an instance or a network interface. +// Associates an Elastic IP address, or carrier IP address (for instances that +// are in subnets in Wavelength Zones) with an instance or a network interface. // Before you can use an Elastic IP address, you must allocate it to your account. // // An Elastic IP address is for use in either the EC2-Classic platform or in @@ -976,6 +981,9 @@ func (c *EC2) AssociateAddressRequest(input *AssociateAddressInput) (req *reques // an Elastic IP address with an instance or network interface that has an existing // Elastic IP address. // +// [Subnets in Wavelength Zones] You can associate an IP address from the telecommunication +// carrier to the instance or network interface. +// // You cannot associate an Elastic IP address with an interface in a different // network border group. // @@ -1943,7 +1951,7 @@ func (c *EC2) AttachVolumeRequest(input *AttachVolumeInput) (req *request.Reques // in the Amazon Elastic Compute Cloud User Guide. // // After you attach an EBS volume, you must make it available. For more information, -// see Making an EBS Volume Available For Use (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html). +// see Making an EBS volume available for use (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-using-volumes.html). // // If a volume has an AWS Marketplace product code: // @@ -1957,7 +1965,7 @@ func (c *EC2) AttachVolumeRequest(input *AttachVolumeInput) (req *request.Reques // the product. For example, you can't detach a volume from a Windows instance // and attach it to a Linux instance. // -// For more information, see Attaching Amazon EBS Volumes (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-attaching-volume.html) +// For more information, see Attaching Amazon EBS volumes (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-attaching-volume.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -3325,7 +3333,7 @@ func (c *EC2) CopySnapshotRequest(input *CopySnapshotInput) (req *request.Reques // Snapshots created by copying another snapshot have an arbitrary volume ID // that should not be used for any purpose. // -// For more information, see Copying an Amazon EBS Snapshot (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-copy-snapshot.html) +// For more information, see Copying an Amazon EBS snapshot (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-copy-snapshot.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -3453,6 +3461,82 @@ func (c *EC2) CreateCapacityReservationWithContext(ctx aws.Context, input *Creat return out, req.Send() } +const opCreateCarrierGateway = "CreateCarrierGateway" + +// CreateCarrierGatewayRequest generates a "aws/request.Request" representing the +// client's request for the CreateCarrierGateway operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateCarrierGateway for more information on using the CreateCarrierGateway +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateCarrierGatewayRequest method. +// req, resp := client.CreateCarrierGatewayRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateCarrierGateway +func (c *EC2) CreateCarrierGatewayRequest(input *CreateCarrierGatewayInput) (req *request.Request, output *CreateCarrierGatewayOutput) { + op := &request.Operation{ + Name: opCreateCarrierGateway, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateCarrierGatewayInput{} + } + + output = &CreateCarrierGatewayOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateCarrierGateway API operation for Amazon Elastic Compute Cloud. +// +// Creates a carrier gateway. For more information about carrier gateways, see +// Carrier gateways (https://docs.aws.amazon.com/wavelength/latest/developerguide/how-wavelengths-work.html#wavelength-carrier-gateway) +// in the AWS Wavelength 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 Elastic Compute Cloud's +// API operation CreateCarrierGateway for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateCarrierGateway +func (c *EC2) CreateCarrierGateway(input *CreateCarrierGatewayInput) (*CreateCarrierGatewayOutput, error) { + req, out := c.CreateCarrierGatewayRequest(input) + return out, req.Send() +} + +// CreateCarrierGatewayWithContext is the same as CreateCarrierGateway with the addition of +// the ability to pass a context and additional request options. +// +// See CreateCarrierGateway 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 *EC2) CreateCarrierGatewayWithContext(ctx aws.Context, input *CreateCarrierGatewayInput, opts ...request.Option) (*CreateCarrierGatewayOutput, error) { + req, out := c.CreateCarrierGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateClientVpnEndpoint = "CreateClientVpnEndpoint" // CreateClientVpnEndpointRequest generates a "aws/request.Request" representing the @@ -3653,7 +3737,7 @@ func (c *EC2) CreateCustomerGatewayRequest(input *CreateCustomerGatewayInput) (r // Provides information to AWS about your VPN customer gateway device. The customer // gateway is the appliance at your end of the VPN connection. (The device on // the AWS side of the VPN connection is the virtual private gateway.) You must -// provide the Internet-routable IP address of the customer gateway's external +// provide the internet-routable IP address of the customer gateway's external // interface. The IP address must be static and can be behind a device performing // network address translation (NAT). // @@ -3662,9 +3746,16 @@ func (c *EC2) CreateCustomerGatewayRequest(input *CreateCustomerGatewayInput) (r // ASN assigned to your network. If you don't have an ASN already, you can use // a private ASN (in the 64512 - 65534 range). // -// Amazon EC2 supports all 2-byte ASN numbers in the range of 1 - 65534, with -// the exception of 7224, which is reserved in the us-east-1 Region, and 9059, -// which is reserved in the eu-west-1 Region. +// Amazon EC2 supports all 4-byte ASN numbers in the range of 1 - 2147483647, +// with the exception of the following: +// +// * 7224 - reserved in the us-east-1 Region +// +// * 9059 - reserved in the eu-west-1 Region +// +// * 17943 - reserved in the ap-southeast-1 Region +// +// * 10124 - reserved in the ap-northeast-1 Region // // For more information, see AWS Site-to-Site VPN (https://docs.aws.amazon.com/vpn/latest/s2svpn/VPC_VPN.html) // in the AWS Site-to-Site VPN User Guide. @@ -3926,13 +4017,13 @@ func (c *EC2) CreateDhcpOptionsRequest(input *CreateDhcpOptionsInput) (req *requ // * domain-name - If you're using AmazonProvidedDNS in us-east-1, specify // ec2.internal. If you're using AmazonProvidedDNS in another Region, specify // region.compute.internal (for example, ap-northeast-1.compute.internal). -// Otherwise, specify a domain name (for example, MyCompany.com). This value -// is used to complete unqualified DNS hostnames. Important: Some Linux operating -// systems accept multiple domain names separated by spaces. However, Windows -// and other Linux operating systems treat the value as a single domain, -// which results in unexpected behavior. If your DHCP options set is associated -// with a VPC that has instances with multiple operating systems, specify -// only one domain name. +// Otherwise, specify a domain name (for example, ExampleCompany.com). This +// value is used to complete unqualified DNS hostnames. Important: Some Linux +// operating systems accept multiple domain names separated by spaces. However, +// Windows and other Linux operating systems treat the value as a single +// domain, which results in unexpected behavior. If your DHCP options set +// is associated with a VPC that has instances with multiple operating systems, +// specify only one domain name. // // * ntp-servers - The IP addresses of up to four Network Time Protocol (NTP) // servers. @@ -4432,7 +4523,7 @@ func (c *EC2) CreateInstanceExportTaskRequest(input *CreateInstanceExportTaskInp // CreateInstanceExportTask API operation for Amazon Elastic Compute Cloud. // -// Exports a running or stopped instance to an S3 bucket. +// Exports a running or stopped instance to an Amazon S3 bucket. // // For information about the supported operating systems, image formats, and // known limitations for the types of instances you can export, see Exporting @@ -4678,6 +4769,8 @@ func (c *EC2) CreateLaunchTemplateRequest(input *CreateLaunchTemplateInput) (req // Creates a launch template. A launch template contains the parameters to launch // an instance. When you launch an instance using RunInstances, you can specify // a launch template instead of providing the launch parameters in the request. +// For more information, see Launching an instance from a launch template (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html)in +// the Amazon Elastic Compute Cloud User 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 @@ -4757,6 +4850,9 @@ func (c *EC2) CreateLaunchTemplateVersionRequest(input *CreateLaunchTemplateVers // Launch template versions are numbered in the order in which they are created. // You cannot specify, change, or replace the numbering of launch template versions. // +// For more information, see Managing launch template versions (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html#manage-launch-template-versions)in +// the Amazon Elastic Compute Cloud User 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. @@ -4933,6 +5029,84 @@ func (c *EC2) CreateLocalGatewayRouteTableVpcAssociationWithContext(ctx aws.Cont return out, req.Send() } +const opCreateManagedPrefixList = "CreateManagedPrefixList" + +// CreateManagedPrefixListRequest generates a "aws/request.Request" representing the +// client's request for the CreateManagedPrefixList operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateManagedPrefixList for more information on using the CreateManagedPrefixList +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateManagedPrefixListRequest method. +// req, resp := client.CreateManagedPrefixListRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateManagedPrefixList +func (c *EC2) CreateManagedPrefixListRequest(input *CreateManagedPrefixListInput) (req *request.Request, output *CreateManagedPrefixListOutput) { + op := &request.Operation{ + Name: opCreateManagedPrefixList, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateManagedPrefixListInput{} + } + + output = &CreateManagedPrefixListOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateManagedPrefixList API operation for Amazon Elastic Compute Cloud. +// +// Creates a managed prefix list. You can specify one or more entries for the +// prefix list. Each entry consists of a CIDR block and an optional description. +// +// You must specify the maximum number of entries for the prefix list. The maximum +// number of entries cannot be changed later. +// +// 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 Elastic Compute Cloud's +// API operation CreateManagedPrefixList for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateManagedPrefixList +func (c *EC2) CreateManagedPrefixList(input *CreateManagedPrefixListInput) (*CreateManagedPrefixListOutput, error) { + req, out := c.CreateManagedPrefixListRequest(input) + return out, req.Send() +} + +// CreateManagedPrefixListWithContext is the same as CreateManagedPrefixList with the addition of +// the ability to pass a context and additional request options. +// +// See CreateManagedPrefixList 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 *EC2) CreateManagedPrefixListWithContext(ctx aws.Context, input *CreateManagedPrefixListInput, opts ...request.Option) (*CreateManagedPrefixListOutput, error) { + req, out := c.CreateManagedPrefixListRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateNatGateway = "CreateNatGateway" // CreateNatGatewayRequest generates a "aws/request.Request" representing the @@ -5392,7 +5566,7 @@ func (c *EC2) CreatePlacementGroupRequest(input *CreatePlacementGroupInput) (req // instances in one partition do not share the same hardware with instances // in another partition. // -// For more information, see Placement Groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) +// For more information, see Placement groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -5859,7 +6033,7 @@ func (c *EC2) CreateSnapshotRequest(input *CreateSnapshotInput) (req *request.Re // protected. // // You can tag your snapshots during creation. For more information, see Tagging -// Your Amazon EC2 Resources (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) +// your Amazon EC2 resources (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) // in the Amazon Elastic Compute Cloud User Guide. // // For more information, see Amazon Elastic Block Store (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html) @@ -6017,7 +6191,7 @@ func (c *EC2) CreateSpotDatafeedSubscriptionRequest(input *CreateSpotDatafeedSub // // Creates a data feed for Spot Instances, enabling you to view Spot Instance // usage logs. You can create one data feed per AWS account. For more information, -// see Spot Instance Data Feed (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-data-feeds.html) +// see Spot Instance data feed (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-data-feeds.html) // in the Amazon EC2 User Guide for Linux Instances. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -6092,15 +6266,12 @@ func (c *EC2) CreateSubnetRequest(input *CreateSubnetInput) (req *request.Reques // CreateSubnet API operation for Amazon Elastic Compute Cloud. // -// Creates a subnet in an existing VPC. +// Creates a subnet in a specified VPC. // -// When you create each subnet, you provide the VPC ID and IPv4 CIDR block for -// the subnet. After you create a subnet, you can't change its CIDR block. The -// size of the subnet's IPv4 CIDR block can be the same as a VPC's IPv4 CIDR -// block, or a subset of a VPC's IPv4 CIDR block. If you create more than one -// subnet in a VPC, the subnets' CIDR blocks must not overlap. The smallest -// IPv4 subnet (and VPC) you can create uses a /28 netmask (16 IPv4 addresses), -// and the largest uses a /16 netmask (65,536 IPv4 addresses). +// You must specify an IPv4 CIDR block for the subnet. After you create a subnet, +// you can't change its CIDR block. The allowed block size is between a /16 +// netmask (65,536 IP addresses) and /28 netmask (16 IP addresses). The CIDR +// block must not overlap with the CIDR block of an existing subnet in the VPC. // // If you've associated an IPv6 CIDR block with your VPC, you can create a subnet // with an IPv6 CIDR block that uses a /64 prefix length. @@ -6111,9 +6282,7 @@ func (c *EC2) CreateSubnetRequest(input *CreateSubnetInput) (req *request.Reques // If you add more than one subnet to a VPC, they're set up in a star topology // with a logical router in the middle. // -// If you launch an instance in a VPC using an Amazon EBS-backed AMI, the IP -// address doesn't change if you stop and restart the instance (unlike a similar -// instance launched outside a VPC, which gets a new IP address when restarted). +// When you stop an instance in a subnet, it retains its private IPv4 address. // It's therefore possible to have a subnet with no running instances (they're // all stopped), but no remaining IP addresses available. // @@ -6193,9 +6362,10 @@ func (c *EC2) CreateTagsRequest(input *CreateTagsInput) (req *request.Request, o // CreateTags API operation for Amazon Elastic Compute Cloud. // -// Adds or overwrites the specified tags for the specified Amazon EC2 resource -// or resources. Each resource can have a maximum of 50 tags. Each tag consists -// of a key and optional value. Tag keys must be unique per resource. +// Adds or overwrites only the specified tags for the specified Amazon EC2 resource +// or resources. When you specify an existing tag key, the value is overwritten +// with the new value. Each resource can have a maximum of 50 tags. Each tag +// consists of a key and optional value. Tag keys must be unique per resource. // // For more information about tags, see Tagging Your Resources (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) // in the Amazon Elastic Compute Cloud User Guide. For more information about @@ -6812,6 +6982,81 @@ func (c *EC2) CreateTransitGatewayPeeringAttachmentWithContext(ctx aws.Context, return out, req.Send() } +const opCreateTransitGatewayPrefixListReference = "CreateTransitGatewayPrefixListReference" + +// CreateTransitGatewayPrefixListReferenceRequest generates a "aws/request.Request" representing the +// client's request for the CreateTransitGatewayPrefixListReference operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See CreateTransitGatewayPrefixListReference for more information on using the CreateTransitGatewayPrefixListReference +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the CreateTransitGatewayPrefixListReferenceRequest method. +// req, resp := client.CreateTransitGatewayPrefixListReferenceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTransitGatewayPrefixListReference +func (c *EC2) CreateTransitGatewayPrefixListReferenceRequest(input *CreateTransitGatewayPrefixListReferenceInput) (req *request.Request, output *CreateTransitGatewayPrefixListReferenceOutput) { + op := &request.Operation{ + Name: opCreateTransitGatewayPrefixListReference, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &CreateTransitGatewayPrefixListReferenceInput{} + } + + output = &CreateTransitGatewayPrefixListReferenceOutput{} + req = c.newRequest(op, input, output) + return +} + +// CreateTransitGatewayPrefixListReference API operation for Amazon Elastic Compute Cloud. +// +// Creates a reference (route) to a prefix list in a specified transit gateway +// route 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 Elastic Compute Cloud's +// API operation CreateTransitGatewayPrefixListReference for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CreateTransitGatewayPrefixListReference +func (c *EC2) CreateTransitGatewayPrefixListReference(input *CreateTransitGatewayPrefixListReferenceInput) (*CreateTransitGatewayPrefixListReferenceOutput, error) { + req, out := c.CreateTransitGatewayPrefixListReferenceRequest(input) + return out, req.Send() +} + +// CreateTransitGatewayPrefixListReferenceWithContext is the same as CreateTransitGatewayPrefixListReference with the addition of +// the ability to pass a context and additional request options. +// +// See CreateTransitGatewayPrefixListReference 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 *EC2) CreateTransitGatewayPrefixListReferenceWithContext(ctx aws.Context, input *CreateTransitGatewayPrefixListReferenceInput, opts ...request.Option) (*CreateTransitGatewayPrefixListReferenceOutput, error) { + req, out := c.CreateTransitGatewayPrefixListReferenceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opCreateTransitGatewayRoute = "CreateTransitGatewayRoute" // CreateTransitGatewayRouteRequest generates a "aws/request.Request" representing the @@ -7100,10 +7345,10 @@ func (c *EC2) CreateVolumeRequest(input *CreateVolumeInput) (req *request.Reques // in the Amazon Elastic Compute Cloud User Guide. // // You can tag your volumes during creation. For more information, see Tagging -// Your Amazon EC2 Resources (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) +// your Amazon EC2 resources (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) // in the Amazon Elastic Compute Cloud User Guide. // -// For more information, see Creating an Amazon EBS Volume (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-creating-volume.html) +// For more information, see Creating an Amazon EBS volume (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-creating-volume.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -7616,15 +7861,15 @@ func (c *EC2) CreateVpnConnectionRequest(input *CreateVpnConnectionInput) (req * // CreateVpnConnection API operation for Amazon Elastic Compute Cloud. // -// Creates a VPN connection between an existing virtual private gateway and -// a VPN customer gateway. The supported connection type is ipsec.1. +// Creates a VPN connection between an existing virtual private gateway or transit +// gateway and a customer gateway. The supported connection type is ipsec.1. // // The response includes information that you need to give to your network administrator // to configure your customer gateway. // // We strongly recommend that you use HTTPS when calling this operation because // the response contains sensitive cryptographic information for configuring -// your customer gateway. +// your customer gateway device. // // If you decide to shut down your VPN connection for any reason and later create // a new VPN connection, you must reconfigure your customer gateway with the @@ -7824,6 +8069,84 @@ func (c *EC2) CreateVpnGatewayWithContext(ctx aws.Context, input *CreateVpnGatew return out, req.Send() } +const opDeleteCarrierGateway = "DeleteCarrierGateway" + +// DeleteCarrierGatewayRequest generates a "aws/request.Request" representing the +// client's request for the DeleteCarrierGateway operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteCarrierGateway for more information on using the DeleteCarrierGateway +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteCarrierGatewayRequest method. +// req, resp := client.DeleteCarrierGatewayRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteCarrierGateway +func (c *EC2) DeleteCarrierGatewayRequest(input *DeleteCarrierGatewayInput) (req *request.Request, output *DeleteCarrierGatewayOutput) { + op := &request.Operation{ + Name: opDeleteCarrierGateway, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteCarrierGatewayInput{} + } + + output = &DeleteCarrierGatewayOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteCarrierGateway API operation for Amazon Elastic Compute Cloud. +// +// Deletes a carrier gateway. +// +// If you do not delete the route that contains the carrier gateway as the Target, +// the route is a blackhole route. For information about how to delete a route, +// see DeleteRoute (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeleteRoute.html). +// +// 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 Elastic Compute Cloud's +// API operation DeleteCarrierGateway for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteCarrierGateway +func (c *EC2) DeleteCarrierGateway(input *DeleteCarrierGatewayInput) (*DeleteCarrierGatewayOutput, error) { + req, out := c.DeleteCarrierGatewayRequest(input) + return out, req.Send() +} + +// DeleteCarrierGatewayWithContext is the same as DeleteCarrierGateway with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteCarrierGateway 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 *EC2) DeleteCarrierGatewayWithContext(ctx aws.Context, input *DeleteCarrierGatewayInput, opts ...request.Option) (*DeleteCarrierGatewayOutput, error) { + req, out := c.DeleteCarrierGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteClientVpnEndpoint = "DeleteClientVpnEndpoint" // DeleteClientVpnEndpointRequest generates a "aws/request.Request" representing the @@ -8884,6 +9207,81 @@ func (c *EC2) DeleteLocalGatewayRouteTableVpcAssociationWithContext(ctx aws.Cont return out, req.Send() } +const opDeleteManagedPrefixList = "DeleteManagedPrefixList" + +// DeleteManagedPrefixListRequest generates a "aws/request.Request" representing the +// client's request for the DeleteManagedPrefixList operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteManagedPrefixList for more information on using the DeleteManagedPrefixList +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteManagedPrefixListRequest method. +// req, resp := client.DeleteManagedPrefixListRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteManagedPrefixList +func (c *EC2) DeleteManagedPrefixListRequest(input *DeleteManagedPrefixListInput) (req *request.Request, output *DeleteManagedPrefixListOutput) { + op := &request.Operation{ + Name: opDeleteManagedPrefixList, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteManagedPrefixListInput{} + } + + output = &DeleteManagedPrefixListOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteManagedPrefixList API operation for Amazon Elastic Compute Cloud. +// +// Deletes the specified managed prefix list. You must first remove all references +// to the prefix list in your resources. +// +// 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 Elastic Compute Cloud's +// API operation DeleteManagedPrefixList for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteManagedPrefixList +func (c *EC2) DeleteManagedPrefixList(input *DeleteManagedPrefixListInput) (*DeleteManagedPrefixListOutput, error) { + req, out := c.DeleteManagedPrefixListRequest(input) + return out, req.Send() +} + +// DeleteManagedPrefixListWithContext is the same as DeleteManagedPrefixList with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteManagedPrefixList 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 *EC2) DeleteManagedPrefixListWithContext(ctx aws.Context, input *DeleteManagedPrefixListInput, opts ...request.Option) (*DeleteManagedPrefixListOutput, error) { + req, out := c.DeleteManagedPrefixListRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteNatGateway = "DeleteNatGateway" // DeleteNatGatewayRequest generates a "aws/request.Request" representing the @@ -9312,7 +9710,7 @@ func (c *EC2) DeletePlacementGroupRequest(input *DeletePlacementGroupInput) (req // // Deletes the specified placement group. You must terminate all instances in // the placement group before you can delete the placement group. For more information, -// see Placement Groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) +// see Placement groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -9706,7 +10104,7 @@ func (c *EC2) DeleteSnapshotRequest(input *DeleteSnapshotInput) (req *request.Re // a registered AMI. You must first de-register the AMI before you can delete // the snapshot. // -// For more information, see Deleting an Amazon EBS Snapshot (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-deleting-snapshot.html) +// For more information, see Deleting an Amazon EBS snapshot (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-deleting-snapshot.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -10491,6 +10889,81 @@ func (c *EC2) DeleteTransitGatewayPeeringAttachmentWithContext(ctx aws.Context, return out, req.Send() } +const opDeleteTransitGatewayPrefixListReference = "DeleteTransitGatewayPrefixListReference" + +// DeleteTransitGatewayPrefixListReferenceRequest generates a "aws/request.Request" representing the +// client's request for the DeleteTransitGatewayPrefixListReference operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DeleteTransitGatewayPrefixListReference for more information on using the DeleteTransitGatewayPrefixListReference +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DeleteTransitGatewayPrefixListReferenceRequest method. +// req, resp := client.DeleteTransitGatewayPrefixListReferenceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTransitGatewayPrefixListReference +func (c *EC2) DeleteTransitGatewayPrefixListReferenceRequest(input *DeleteTransitGatewayPrefixListReferenceInput) (req *request.Request, output *DeleteTransitGatewayPrefixListReferenceOutput) { + op := &request.Operation{ + Name: opDeleteTransitGatewayPrefixListReference, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &DeleteTransitGatewayPrefixListReferenceInput{} + } + + output = &DeleteTransitGatewayPrefixListReferenceOutput{} + req = c.newRequest(op, input, output) + return +} + +// DeleteTransitGatewayPrefixListReference API operation for Amazon Elastic Compute Cloud. +// +// Deletes a reference (route) to a prefix list in a specified transit gateway +// route 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 Elastic Compute Cloud's +// API operation DeleteTransitGatewayPrefixListReference for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DeleteTransitGatewayPrefixListReference +func (c *EC2) DeleteTransitGatewayPrefixListReference(input *DeleteTransitGatewayPrefixListReferenceInput) (*DeleteTransitGatewayPrefixListReferenceOutput, error) { + req, out := c.DeleteTransitGatewayPrefixListReferenceRequest(input) + return out, req.Send() +} + +// DeleteTransitGatewayPrefixListReferenceWithContext is the same as DeleteTransitGatewayPrefixListReference with the addition of +// the ability to pass a context and additional request options. +// +// See DeleteTransitGatewayPrefixListReference 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 *EC2) DeleteTransitGatewayPrefixListReferenceWithContext(ctx aws.Context, input *DeleteTransitGatewayPrefixListReferenceInput, opts ...request.Option) (*DeleteTransitGatewayPrefixListReferenceOutput, error) { + req, out := c.DeleteTransitGatewayPrefixListReferenceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opDeleteTransitGatewayRoute = "DeleteTransitGatewayRoute" // DeleteTransitGatewayRouteRequest generates a "aws/request.Request" representing the @@ -10765,7 +11238,7 @@ func (c *EC2) DeleteVolumeRequest(input *DeleteVolumeInput) (req *request.Reques // // The volume can remain in the deleting state for several minutes. // -// For more information, see Deleting an Amazon EBS Volume (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-deleting-volume.html) +// For more information, see Deleting an Amazon EBS volume (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-deleting-volume.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -11234,9 +11707,13 @@ func (c *EC2) DeleteVpnConnectionRequest(input *DeleteVpnConnectionInput) (req * // your VPN connection have been compromised, you can delete the VPN connection // and create a new one that has new keys, without needing to delete the VPC // or virtual private gateway. If you create a new VPN connection, you must -// reconfigure the customer gateway using the new configuration information +// reconfigure the customer gateway device using the new configuration information // returned with the new VPN connection ID. // +// For certificate-based authentication, delete all AWS Certificate Manager +// (ACM) private certificates used for the AWS-side tunnel endpoints for the +// VPN connection before deleting the VPN connection. +// // 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. @@ -12113,13 +12590,12 @@ func (c *EC2) DescribeAvailabilityZonesRequest(input *DescribeAvailabilityZonesI // DescribeAvailabilityZones API operation for Amazon Elastic Compute Cloud. // -// Describes the Availability Zones and Local Zones that are available to you. -// If there is an event impacting an Availability Zone or Local Zone, you can -// use this request to view the state and any provided messages for that Availability -// Zone or Local Zone. +// Describes the Availability Zones, Local Zones, and Wavelength Zones that +// are available to you. If there is an event impacting a zone, you can use +// this request to view the state and any provided messages for that zone. // -// For more information about Availability Zones and Local Zones, see Regions -// and Availability Zones (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) +// For more information about Availability Zones, Local Zones, and Wavelength +// Zones, see Regions, Zones and Outposts (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -12497,6 +12973,138 @@ func (c *EC2) DescribeCapacityReservationsPagesWithContext(ctx aws.Context, inpu return p.Err() } +const opDescribeCarrierGateways = "DescribeCarrierGateways" + +// DescribeCarrierGatewaysRequest generates a "aws/request.Request" representing the +// client's request for the DescribeCarrierGateways operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeCarrierGateways for more information on using the DescribeCarrierGateways +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeCarrierGatewaysRequest method. +// req, resp := client.DescribeCarrierGatewaysRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeCarrierGateways +func (c *EC2) DescribeCarrierGatewaysRequest(input *DescribeCarrierGatewaysInput) (req *request.Request, output *DescribeCarrierGatewaysOutput) { + op := &request.Operation{ + Name: opDescribeCarrierGateways, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeCarrierGatewaysInput{} + } + + output = &DescribeCarrierGatewaysOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeCarrierGateways API operation for Amazon Elastic Compute Cloud. +// +// Describes one or more of your carrier gateways. +// +// 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 Elastic Compute Cloud's +// API operation DescribeCarrierGateways for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeCarrierGateways +func (c *EC2) DescribeCarrierGateways(input *DescribeCarrierGatewaysInput) (*DescribeCarrierGatewaysOutput, error) { + req, out := c.DescribeCarrierGatewaysRequest(input) + return out, req.Send() +} + +// DescribeCarrierGatewaysWithContext is the same as DescribeCarrierGateways with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeCarrierGateways 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 *EC2) DescribeCarrierGatewaysWithContext(ctx aws.Context, input *DescribeCarrierGatewaysInput, opts ...request.Option) (*DescribeCarrierGatewaysOutput, error) { + req, out := c.DescribeCarrierGatewaysRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// DescribeCarrierGatewaysPages iterates over the pages of a DescribeCarrierGateways operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeCarrierGateways method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeCarrierGateways operation. +// pageNum := 0 +// err := client.DescribeCarrierGatewaysPages(params, +// func(page *ec2.DescribeCarrierGatewaysOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *EC2) DescribeCarrierGatewaysPages(input *DescribeCarrierGatewaysInput, fn func(*DescribeCarrierGatewaysOutput, bool) bool) error { + return c.DescribeCarrierGatewaysPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeCarrierGatewaysPagesWithContext same as DescribeCarrierGatewaysPages 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 *EC2) DescribeCarrierGatewaysPagesWithContext(ctx aws.Context, input *DescribeCarrierGatewaysInput, fn func(*DescribeCarrierGatewaysOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeCarrierGatewaysInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeCarrierGatewaysRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeCarrierGatewaysOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeClassicLinkInstances = "DescribeClassicLinkInstances" // DescribeClassicLinkInstancesRequest generates a "aws/request.Request" representing the @@ -13974,7 +14582,7 @@ func (c *EC2) DescribeExportImageTasksRequest(input *DescribeExportImageTasksInp // DescribeExportImageTasks API operation for Amazon Elastic Compute Cloud. // -// Describes the specified export image tasks or all your export image tasks. +// Describes the specified export image tasks or all of your export image tasks. // // 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 @@ -14100,7 +14708,7 @@ func (c *EC2) DescribeExportTasksRequest(input *DescribeExportTasksInput) (req * // DescribeExportTasks API operation for Amazon Elastic Compute Cloud. // -// Describes the specified export instance tasks or all your export instance +// Describes the specified export instance tasks or all of your export instance // tasks. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -16185,7 +16793,7 @@ func (c *EC2) DescribeInstanceCreditSpecificationsRequest(input *DescribeInstanc // all, the call fails. If you specify only instance IDs in an unaffected zone, // the call works normally. // -// For more information, see Burstable Performance Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) +// For more information, see Burstable performance instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -16401,18 +17009,18 @@ func (c *EC2) DescribeInstanceStatusRequest(input *DescribeInstanceStatusInput) // // * Status checks - Amazon EC2 performs status checks on running EC2 instances // to identify hardware and software issues. For more information, see Status -// Checks for Your Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-system-instance-status-check.html) -// and Troubleshooting Instances with Failed Status Checks (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstances.html) +// checks for your instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-system-instance-status-check.html) +// and Troubleshooting instances with failed status checks (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstances.html) // in the Amazon Elastic Compute Cloud User Guide. // // * Scheduled events - Amazon EC2 can schedule events (such as reboot, stop, // or terminate) for your instances related to hardware issues, software -// updates, or system maintenance. For more information, see Scheduled Events -// for Your Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-instances-status-check_sched.html) +// updates, or system maintenance. For more information, see Scheduled events +// for your instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-instances-status-check_sched.html) // in the Amazon Elastic Compute Cloud User Guide. // // * Instance state - You can manage your instances from the moment you launch -// them through their termination. For more information, see Instance Lifecycle +// them through their termination. For more information, see Instance lifecycle // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) // in the Amazon Elastic Compute Cloud User Guide. // @@ -16680,7 +17288,7 @@ func (c *EC2) DescribeInstanceTypesRequest(input *DescribeInstanceTypesInput) (r // DescribeInstanceTypes API operation for Amazon Elastic Compute Cloud. // -// Returns a list of all instance types offered in your current AWS Region. +// Describes the details of the instance types that are offered in a location. // The results can be filtered by the attributes of the instance types. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -16813,13 +17421,17 @@ func (c *EC2) DescribeInstancesRequest(input *DescribeInstancesInput) (req *requ // DescribeInstances API operation for Amazon Elastic Compute Cloud. // -// Describes the specified instances or all of AWS account's instances. +// Describes the specified instances or all instances. // -// If you specify one or more instance IDs, Amazon EC2 returns information for -// those instances. If you do not specify instance IDs, Amazon EC2 returns information -// for all relevant instances. If you specify an instance ID that is not valid, -// an error is returned. If you specify an instance that you do not own, it -// is not included in the returned results. +// If you specify instance IDs, the output includes information for only the +// specified instances. If you specify filters, the output includes information +// for only those instances that meet the filter criteria. If you do not specify +// instance IDs or filters, the output includes information for all instances, +// which can affect performance. We recommend that you use pagination to ensure +// that the operation returns quickly and successfully. +// +// If you specify an instance ID that is not valid, an error is returned. If +// you specify an instance that you do not own, it is not included in the output. // // Recently terminated instances might appear in the returned results. This // interval is usually less than one hour. @@ -17302,7 +17914,9 @@ func (c *EC2) DescribeLaunchTemplateVersionsRequest(input *DescribeLaunchTemplat // DescribeLaunchTemplateVersions API operation for Amazon Elastic Compute Cloud. // // Describes one or more versions of a specified launch template. You can describe -// all versions, individual versions, or a range of versions. +// all versions, individual versions, or a range of versions. You can also describe +// all the latest versions or all the default versions of all the launch templates +// in your account. // // 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 @@ -18312,6 +18926,140 @@ func (c *EC2) DescribeLocalGatewaysPagesWithContext(ctx aws.Context, input *Desc return p.Err() } +const opDescribeManagedPrefixLists = "DescribeManagedPrefixLists" + +// DescribeManagedPrefixListsRequest generates a "aws/request.Request" representing the +// client's request for the DescribeManagedPrefixLists operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See DescribeManagedPrefixLists for more information on using the DescribeManagedPrefixLists +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the DescribeManagedPrefixListsRequest method. +// req, resp := client.DescribeManagedPrefixListsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeManagedPrefixLists +func (c *EC2) DescribeManagedPrefixListsRequest(input *DescribeManagedPrefixListsInput) (req *request.Request, output *DescribeManagedPrefixListsOutput) { + op := &request.Operation{ + Name: opDescribeManagedPrefixLists, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &DescribeManagedPrefixListsInput{} + } + + output = &DescribeManagedPrefixListsOutput{} + req = c.newRequest(op, input, output) + return +} + +// DescribeManagedPrefixLists API operation for Amazon Elastic Compute Cloud. +// +// Describes your managed prefix lists and any AWS-managed prefix lists. +// +// To view the entries for your prefix list, use GetManagedPrefixListEntries. +// +// 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 Elastic Compute Cloud's +// API operation DescribeManagedPrefixLists for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/DescribeManagedPrefixLists +func (c *EC2) DescribeManagedPrefixLists(input *DescribeManagedPrefixListsInput) (*DescribeManagedPrefixListsOutput, error) { + req, out := c.DescribeManagedPrefixListsRequest(input) + return out, req.Send() +} + +// DescribeManagedPrefixListsWithContext is the same as DescribeManagedPrefixLists with the addition of +// the ability to pass a context and additional request options. +// +// See DescribeManagedPrefixLists 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 *EC2) DescribeManagedPrefixListsWithContext(ctx aws.Context, input *DescribeManagedPrefixListsInput, opts ...request.Option) (*DescribeManagedPrefixListsOutput, error) { + req, out := c.DescribeManagedPrefixListsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// DescribeManagedPrefixListsPages iterates over the pages of a DescribeManagedPrefixLists operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeManagedPrefixLists method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeManagedPrefixLists operation. +// pageNum := 0 +// err := client.DescribeManagedPrefixListsPages(params, +// func(page *ec2.DescribeManagedPrefixListsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *EC2) DescribeManagedPrefixListsPages(input *DescribeManagedPrefixListsInput, fn func(*DescribeManagedPrefixListsOutput, bool) bool) error { + return c.DescribeManagedPrefixListsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeManagedPrefixListsPagesWithContext same as DescribeManagedPrefixListsPages 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 *EC2) DescribeManagedPrefixListsPagesWithContext(ctx aws.Context, input *DescribeManagedPrefixListsInput, fn func(*DescribeManagedPrefixListsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeManagedPrefixListsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeManagedPrefixListsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeManagedPrefixListsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMovingAddresses = "DescribeMovingAddresses" // DescribeMovingAddressesRequest generates a "aws/request.Request" representing the @@ -19097,7 +19845,7 @@ func (c *EC2) DescribePlacementGroupsRequest(input *DescribePlacementGroupsInput // DescribePlacementGroups API operation for Amazon Elastic Compute Cloud. // // Describes the specified placement groups or all of your placement groups. -// For more information, see Placement Groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) +// For more information, see Placement groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -19180,10 +19928,9 @@ func (c *EC2) DescribePrefixListsRequest(input *DescribePrefixListsInput) (req * // // Describes available AWS services in a prefix list format, which includes // the prefix list name and prefix list ID of the service and the IP address -// range for the service. A prefix list ID is required for creating an outbound -// security group rule that allows traffic from a VPC to access an AWS service -// through a gateway VPC endpoint. Currently, the services that support this -// action are Amazon S3 and Amazon DynamoDB. +// range for the service. +// +// We recommend that you use DescribeManagedPrefixLists instead. // // 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 @@ -20870,12 +21617,12 @@ func (c *EC2) DescribeSnapshotsRequest(input *DescribeSnapshotsInput) (req *requ // (if you own the snapshots), self for snapshots for which you own or have // explicit permissions, or all for public snapshots. // -// If you are describing a long list of snapshots, you can paginate the output -// to make the list more manageable. The MaxResults parameter sets the maximum -// number of results returned in a single page. If the list of results exceeds -// your MaxResults value, then that number of results is returned along with -// a NextToken value that can be passed to a subsequent DescribeSnapshots request -// to retrieve the remaining results. +// If you are describing a long list of snapshots, we recommend that you paginate +// the output to make the list more manageable. The MaxResults parameter sets +// the maximum number of results returned in a single page. If the list of results +// exceeds your MaxResults value, then that number of results is returned along +// with a NextToken value that can be passed to a subsequent DescribeSnapshots +// request to retrieve the remaining results. // // To get the state of fast snapshot restores for a snapshot, use DescribeFastSnapshotRestores. // @@ -21007,7 +21754,7 @@ func (c *EC2) DescribeSpotDatafeedSubscriptionRequest(input *DescribeSpotDatafee // DescribeSpotDatafeedSubscription API operation for Amazon Elastic Compute Cloud. // // Describes the data feed for Spot Instances. For more information, see Spot -// Instance Data Feed (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-data-feeds.html) +// Instance data feed (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-data-feeds.html) // in the Amazon EC2 User Guide for Linux Instances. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -21525,7 +22272,7 @@ func (c *EC2) DescribeSpotPriceHistoryRequest(input *DescribeSpotPriceHistoryInp // DescribeSpotPriceHistory API operation for Amazon Elastic Compute Cloud. // // Describes the Spot price history. For more information, see Spot Instance -// Pricing History (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances-history.html) +// pricing history (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances-history.html) // in the Amazon EC2 User Guide for Linux Instances. // // When you specify a start and end time, this operation returns the prices @@ -23358,7 +24105,7 @@ func (c *EC2) DescribeVolumeStatusRequest(input *DescribeVolumeStatusInput) (req // status of the volume is ok. If the check fails, the overall status is impaired. // If the status is insufficient-data, then the checks may still be taking place // on your volume at the time. We recommend that you retry the request. For -// more information about volume status, see Monitoring the Status of Your Volumes +// more information about volume status, see Monitoring the status of your volumes // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-volume-status.html) // in the Amazon Elastic Compute Cloud User Guide. // @@ -23510,12 +24257,12 @@ func (c *EC2) DescribeVolumesRequest(input *DescribeVolumesInput) (req *request. // // Describes the specified EBS volumes or all of your EBS volumes. // -// If you are describing a long list of volumes, you can paginate the output -// to make the list more manageable. The MaxResults parameter sets the maximum -// number of results returned in a single page. If the list of results exceeds -// your MaxResults value, then that number of results is returned along with -// a NextToken value that can be passed to a subsequent DescribeVolumes request -// to retrieve the remaining results. +// If you are describing a long list of volumes, we recommend that you paginate +// the output to make the list more manageable. The MaxResults parameter sets +// the maximum number of results returned in a single page. If the list of results +// exceeds your MaxResults value, then that number of results is returned along +// with a NextToken value that can be passed to a subsequent DescribeVolumes +// request to retrieve the remaining results. // // For more information about EBS volumes, see Amazon EBS Volumes (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumes.html) // in the Amazon Elastic Compute Cloud User Guide. @@ -23650,19 +24397,17 @@ func (c *EC2) DescribeVolumesModificationsRequest(input *DescribeVolumesModifica // DescribeVolumesModifications API operation for Amazon Elastic Compute Cloud. // -// Reports the current modification status of EBS volumes. +// Describes the most recent volume modification request for the specified EBS +// volumes. // -// Current-generation EBS volumes support modification of attributes including -// type, size, and (for io1 volumes) IOPS provisioning while either attached -// to or detached from an instance. Following an action from the API or the -// console to modify a volume, the status of the modification may be modifying, -// optimizing, completed, or failed. If a volume has never been modified, then -// certain elements of the returned VolumeModification objects are null. +// If a volume has never been modified, some information in the output will +// be null. If a volume has been modified more than once, the output includes +// only the most recent modification request. // // You can also use CloudWatch Events to check the status of a modification // to an EBS volume. For information about CloudWatch Events, see the Amazon // CloudWatch Events User Guide (https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/). -// For more information, see Monitoring Volume Modifications" (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html#monitoring_mods) +// For more information, see Monitoring volume modifications (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html#monitoring_mods) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -25471,7 +26216,7 @@ func (c *EC2) DetachVolumeRequest(input *DetachVolumeInput) (req *request.Reques // When a volume with an AWS Marketplace product code is detached from an instance, // the product code is no longer associated with the instance. // -// For more information, see Detaching an Amazon EBS Volume (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html) +// For more information, see Detaching an Amazon EBS volume (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -26018,6 +26763,8 @@ func (c *EC2) DisableVpcClassicLinkDnsSupportRequest(input *DisableVpcClassicLin // ClassicLink (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html) // in the Amazon Elastic Compute Cloud User Guide. // +// You must specify a VPC ID in the request. +// // 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. @@ -26334,7 +27081,7 @@ func (c *EC2) DisassociateRouteTableRequest(input *DisassociateRouteTableInput) // DisassociateRouteTable API operation for Amazon Elastic Compute Cloud. // -// Disassociates a subnet from a route table. +// Disassociates a subnet or gateway from a route table. // // After you perform this action, the subnet no longer uses the routes in the // route table. Instead, it uses the routes in the VPC's main route table. For @@ -26733,7 +27480,7 @@ func (c *EC2) EnableEbsEncryptionByDefaultRequest(input *EnableEbsEncryptionByDe // // After you enable encryption by default, you can no longer launch instances // using instance types that do not support encryption. For more information, -// see Supported Instance Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances). +// see Supported instance types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances). // // 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 @@ -26814,7 +27561,7 @@ func (c *EC2) EnableFastSnapshotRestoresRequest(input *EnableFastSnapshotRestore // state. To get the current state of fast snapshot restores, use DescribeFastSnapshotRestores. // To disable fast snapshot restores, use DisableFastSnapshotRestores. // -// For more information, see Amazon EBS Fast Snapshot Restore (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-fast-snapshot-restore.html) +// For more information, see Amazon EBS fast snapshot restore (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-fast-snapshot-restore.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -27204,6 +27951,8 @@ func (c *EC2) EnableVpcClassicLinkDnsSupportRequest(input *EnableVpcClassicLinkD // see ClassicLink (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html) // in the Amazon Elastic Compute Cloud User Guide. // +// You must specify a VPC ID in the request. +// // 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. @@ -28038,7 +28787,7 @@ func (c *EC2) GetDefaultCreditSpecificationRequest(input *GetDefaultCreditSpecif // Describes the default credit option for CPU usage of a burstable performance // instance family. // -// For more information, see Burstable Performance Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) +// For more information, see Burstable performance instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -28226,6 +28975,138 @@ func (c *EC2) GetEbsEncryptionByDefaultWithContext(ctx aws.Context, input *GetEb return out, req.Send() } +const opGetGroupsForCapacityReservation = "GetGroupsForCapacityReservation" + +// GetGroupsForCapacityReservationRequest generates a "aws/request.Request" representing the +// client's request for the GetGroupsForCapacityReservation operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetGroupsForCapacityReservation for more information on using the GetGroupsForCapacityReservation +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetGroupsForCapacityReservationRequest method. +// req, resp := client.GetGroupsForCapacityReservationRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetGroupsForCapacityReservation +func (c *EC2) GetGroupsForCapacityReservationRequest(input *GetGroupsForCapacityReservationInput) (req *request.Request, output *GetGroupsForCapacityReservationOutput) { + op := &request.Operation{ + Name: opGetGroupsForCapacityReservation, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetGroupsForCapacityReservationInput{} + } + + output = &GetGroupsForCapacityReservationOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetGroupsForCapacityReservation API operation for Amazon Elastic Compute Cloud. +// +// Lists the resource groups to which a Capacity Reservation has been added. +// +// 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 Elastic Compute Cloud's +// API operation GetGroupsForCapacityReservation for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetGroupsForCapacityReservation +func (c *EC2) GetGroupsForCapacityReservation(input *GetGroupsForCapacityReservationInput) (*GetGroupsForCapacityReservationOutput, error) { + req, out := c.GetGroupsForCapacityReservationRequest(input) + return out, req.Send() +} + +// GetGroupsForCapacityReservationWithContext is the same as GetGroupsForCapacityReservation with the addition of +// the ability to pass a context and additional request options. +// +// See GetGroupsForCapacityReservation 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 *EC2) GetGroupsForCapacityReservationWithContext(ctx aws.Context, input *GetGroupsForCapacityReservationInput, opts ...request.Option) (*GetGroupsForCapacityReservationOutput, error) { + req, out := c.GetGroupsForCapacityReservationRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetGroupsForCapacityReservationPages iterates over the pages of a GetGroupsForCapacityReservation operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetGroupsForCapacityReservation method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a GetGroupsForCapacityReservation operation. +// pageNum := 0 +// err := client.GetGroupsForCapacityReservationPages(params, +// func(page *ec2.GetGroupsForCapacityReservationOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *EC2) GetGroupsForCapacityReservationPages(input *GetGroupsForCapacityReservationInput, fn func(*GetGroupsForCapacityReservationOutput, bool) bool) error { + return c.GetGroupsForCapacityReservationPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetGroupsForCapacityReservationPagesWithContext same as GetGroupsForCapacityReservationPages 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 *EC2) GetGroupsForCapacityReservationPagesWithContext(ctx aws.Context, input *GetGroupsForCapacityReservationInput, fn func(*GetGroupsForCapacityReservationOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetGroupsForCapacityReservationInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetGroupsForCapacityReservationRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetGroupsForCapacityReservationOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetHostReservationPurchasePreview = "GetHostReservationPurchasePreview" // GetHostReservationPurchasePreviewRequest generates a "aws/request.Request" representing the @@ -28352,6 +29233,12 @@ func (c *EC2) GetLaunchTemplateDataRequest(input *GetLaunchTemplateDataInput) (r // Retrieves the configuration data of the specified instance. You can use this // data to create a launch template. // +// This action calls on other describe actions to get instance information. +// Depending on your instance configuration, you may need to allow the following +// actions in your IAM policy: DescribeSpotInstanceRequests, DescribeInstanceCreditSpecifications, +// DescribeVolumes, DescribeInstanceAttribute, and DescribeElasticGpus. Or, +// you can allow describe* depending on your instance requirements. +// // 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. @@ -28380,6 +29267,271 @@ func (c *EC2) GetLaunchTemplateDataWithContext(ctx aws.Context, input *GetLaunch return out, req.Send() } +const opGetManagedPrefixListAssociations = "GetManagedPrefixListAssociations" + +// GetManagedPrefixListAssociationsRequest generates a "aws/request.Request" representing the +// client's request for the GetManagedPrefixListAssociations operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetManagedPrefixListAssociations for more information on using the GetManagedPrefixListAssociations +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetManagedPrefixListAssociationsRequest method. +// req, resp := client.GetManagedPrefixListAssociationsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetManagedPrefixListAssociations +func (c *EC2) GetManagedPrefixListAssociationsRequest(input *GetManagedPrefixListAssociationsInput) (req *request.Request, output *GetManagedPrefixListAssociationsOutput) { + op := &request.Operation{ + Name: opGetManagedPrefixListAssociations, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetManagedPrefixListAssociationsInput{} + } + + output = &GetManagedPrefixListAssociationsOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetManagedPrefixListAssociations API operation for Amazon Elastic Compute Cloud. +// +// Gets information about the resources that are associated with the specified +// managed prefix list. +// +// 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 Elastic Compute Cloud's +// API operation GetManagedPrefixListAssociations for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetManagedPrefixListAssociations +func (c *EC2) GetManagedPrefixListAssociations(input *GetManagedPrefixListAssociationsInput) (*GetManagedPrefixListAssociationsOutput, error) { + req, out := c.GetManagedPrefixListAssociationsRequest(input) + return out, req.Send() +} + +// GetManagedPrefixListAssociationsWithContext is the same as GetManagedPrefixListAssociations with the addition of +// the ability to pass a context and additional request options. +// +// See GetManagedPrefixListAssociations 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 *EC2) GetManagedPrefixListAssociationsWithContext(ctx aws.Context, input *GetManagedPrefixListAssociationsInput, opts ...request.Option) (*GetManagedPrefixListAssociationsOutput, error) { + req, out := c.GetManagedPrefixListAssociationsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetManagedPrefixListAssociationsPages iterates over the pages of a GetManagedPrefixListAssociations operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetManagedPrefixListAssociations method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a GetManagedPrefixListAssociations operation. +// pageNum := 0 +// err := client.GetManagedPrefixListAssociationsPages(params, +// func(page *ec2.GetManagedPrefixListAssociationsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *EC2) GetManagedPrefixListAssociationsPages(input *GetManagedPrefixListAssociationsInput, fn func(*GetManagedPrefixListAssociationsOutput, bool) bool) error { + return c.GetManagedPrefixListAssociationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetManagedPrefixListAssociationsPagesWithContext same as GetManagedPrefixListAssociationsPages 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 *EC2) GetManagedPrefixListAssociationsPagesWithContext(ctx aws.Context, input *GetManagedPrefixListAssociationsInput, fn func(*GetManagedPrefixListAssociationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetManagedPrefixListAssociationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetManagedPrefixListAssociationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetManagedPrefixListAssociationsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + +const opGetManagedPrefixListEntries = "GetManagedPrefixListEntries" + +// GetManagedPrefixListEntriesRequest generates a "aws/request.Request" representing the +// client's request for the GetManagedPrefixListEntries operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetManagedPrefixListEntries for more information on using the GetManagedPrefixListEntries +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetManagedPrefixListEntriesRequest method. +// req, resp := client.GetManagedPrefixListEntriesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetManagedPrefixListEntries +func (c *EC2) GetManagedPrefixListEntriesRequest(input *GetManagedPrefixListEntriesInput) (req *request.Request, output *GetManagedPrefixListEntriesOutput) { + op := &request.Operation{ + Name: opGetManagedPrefixListEntries, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetManagedPrefixListEntriesInput{} + } + + output = &GetManagedPrefixListEntriesOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetManagedPrefixListEntries API operation for Amazon Elastic Compute Cloud. +// +// Gets information about the entries for a specified managed prefix list. +// +// 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 Elastic Compute Cloud's +// API operation GetManagedPrefixListEntries for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetManagedPrefixListEntries +func (c *EC2) GetManagedPrefixListEntries(input *GetManagedPrefixListEntriesInput) (*GetManagedPrefixListEntriesOutput, error) { + req, out := c.GetManagedPrefixListEntriesRequest(input) + return out, req.Send() +} + +// GetManagedPrefixListEntriesWithContext is the same as GetManagedPrefixListEntries with the addition of +// the ability to pass a context and additional request options. +// +// See GetManagedPrefixListEntries 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 *EC2) GetManagedPrefixListEntriesWithContext(ctx aws.Context, input *GetManagedPrefixListEntriesInput, opts ...request.Option) (*GetManagedPrefixListEntriesOutput, error) { + req, out := c.GetManagedPrefixListEntriesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetManagedPrefixListEntriesPages iterates over the pages of a GetManagedPrefixListEntries operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetManagedPrefixListEntries method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a GetManagedPrefixListEntries operation. +// pageNum := 0 +// err := client.GetManagedPrefixListEntriesPages(params, +// func(page *ec2.GetManagedPrefixListEntriesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *EC2) GetManagedPrefixListEntriesPages(input *GetManagedPrefixListEntriesInput, fn func(*GetManagedPrefixListEntriesOutput, bool) bool) error { + return c.GetManagedPrefixListEntriesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetManagedPrefixListEntriesPagesWithContext same as GetManagedPrefixListEntriesPages 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 *EC2) GetManagedPrefixListEntriesPagesWithContext(ctx aws.Context, input *GetManagedPrefixListEntriesInput, fn func(*GetManagedPrefixListEntriesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetManagedPrefixListEntriesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetManagedPrefixListEntriesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetManagedPrefixListEntriesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetPasswordData = "GetPasswordData" // GetPasswordDataRequest generates a "aws/request.Request" representing the @@ -28814,6 +29966,139 @@ func (c *EC2) GetTransitGatewayMulticastDomainAssociationsPagesWithContext(ctx a return p.Err() } +const opGetTransitGatewayPrefixListReferences = "GetTransitGatewayPrefixListReferences" + +// GetTransitGatewayPrefixListReferencesRequest generates a "aws/request.Request" representing the +// client's request for the GetTransitGatewayPrefixListReferences operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See GetTransitGatewayPrefixListReferences for more information on using the GetTransitGatewayPrefixListReferences +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the GetTransitGatewayPrefixListReferencesRequest method. +// req, resp := client.GetTransitGatewayPrefixListReferencesRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetTransitGatewayPrefixListReferences +func (c *EC2) GetTransitGatewayPrefixListReferencesRequest(input *GetTransitGatewayPrefixListReferencesInput) (req *request.Request, output *GetTransitGatewayPrefixListReferencesOutput) { + op := &request.Operation{ + Name: opGetTransitGatewayPrefixListReferences, + HTTPMethod: "POST", + HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, + } + + if input == nil { + input = &GetTransitGatewayPrefixListReferencesInput{} + } + + output = &GetTransitGatewayPrefixListReferencesOutput{} + req = c.newRequest(op, input, output) + return +} + +// GetTransitGatewayPrefixListReferences API operation for Amazon Elastic Compute Cloud. +// +// Gets information about the prefix list references in a specified transit +// gateway route 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 Elastic Compute Cloud's +// API operation GetTransitGatewayPrefixListReferences for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/GetTransitGatewayPrefixListReferences +func (c *EC2) GetTransitGatewayPrefixListReferences(input *GetTransitGatewayPrefixListReferencesInput) (*GetTransitGatewayPrefixListReferencesOutput, error) { + req, out := c.GetTransitGatewayPrefixListReferencesRequest(input) + return out, req.Send() +} + +// GetTransitGatewayPrefixListReferencesWithContext is the same as GetTransitGatewayPrefixListReferences with the addition of +// the ability to pass a context and additional request options. +// +// See GetTransitGatewayPrefixListReferences 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 *EC2) GetTransitGatewayPrefixListReferencesWithContext(ctx aws.Context, input *GetTransitGatewayPrefixListReferencesInput, opts ...request.Option) (*GetTransitGatewayPrefixListReferencesOutput, error) { + req, out := c.GetTransitGatewayPrefixListReferencesRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +// GetTransitGatewayPrefixListReferencesPages iterates over the pages of a GetTransitGatewayPrefixListReferences operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetTransitGatewayPrefixListReferences method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a GetTransitGatewayPrefixListReferences operation. +// pageNum := 0 +// err := client.GetTransitGatewayPrefixListReferencesPages(params, +// func(page *ec2.GetTransitGatewayPrefixListReferencesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *EC2) GetTransitGatewayPrefixListReferencesPages(input *GetTransitGatewayPrefixListReferencesInput, fn func(*GetTransitGatewayPrefixListReferencesOutput, bool) bool) error { + return c.GetTransitGatewayPrefixListReferencesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetTransitGatewayPrefixListReferencesPagesWithContext same as GetTransitGatewayPrefixListReferencesPages 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 *EC2) GetTransitGatewayPrefixListReferencesPagesWithContext(ctx aws.Context, input *GetTransitGatewayPrefixListReferencesInput, fn func(*GetTransitGatewayPrefixListReferencesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetTransitGatewayPrefixListReferencesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetTransitGatewayPrefixListReferencesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetTransitGatewayPrefixListReferencesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetTransitGatewayRouteTableAssociations = "GetTransitGatewayRouteTableAssociations" // GetTransitGatewayRouteTableAssociationsRequest generates a "aws/request.Request" representing the @@ -29592,9 +30877,10 @@ func (c *EC2) ModifyAvailabilityZoneGroupRequest(input *ModifyAvailabilityZoneGr // ModifyAvailabilityZoneGroup API operation for Amazon Elastic Compute Cloud. // -// Enables or disables an Availability Zone group for your account. +// Changes the opt-in status of the Local Zone and Wavelength Zone group for +// your account. // -// Use describe-availability-zones (https://docs.aws.amazon.com/AWSEC2ApiDocReef/build/server-root/AWSEC2/latest/APIReference/API_DescribeAvailabilityZones.html) +// Use DescribeAvailabilityZones (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeAvailabilityZones.html) // to view the value for GroupName. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -29836,7 +31122,7 @@ func (c *EC2) ModifyDefaultCreditSpecificationRequest(input *ModifyDefaultCredit // can call GetDefaultCreditSpecification and check DefaultCreditSpecification // for updates. // -// For more information, see Burstable Performance Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) +// For more information, see Burstable performance instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -30548,7 +31834,7 @@ func (c *EC2) ModifyInstanceAttributeRequest(input *ModifyInstanceAttributeInput // we recommend that you use the ModifyNetworkInterfaceAttribute action. // // To modify some attributes, the instance must be stopped. For more information, -// see Modifying Attributes of a Stopped Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_ChangingAttributesWhileInstanceStopped.html) +// see Modifying attributes of a stopped instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_ChangingAttributesWhileInstanceStopped.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -30703,7 +31989,7 @@ func (c *EC2) ModifyInstanceCreditSpecificationRequest(input *ModifyInstanceCred // Modifies the credit option for CPU usage on a running or stopped burstable // performance instance. The credit options are standard and unlimited. // -// For more information, see Burstable Performance Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) +// For more information, see Burstable performance instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -30858,7 +32144,7 @@ func (c *EC2) ModifyInstanceMetadataOptionsRequest(input *ModifyInstanceMetadata // the API responds with a state of “pending”. After the parameter modifications // are successfully applied to the instance, the state of the modifications // changes from “pending” to “applied” in subsequent describe-instances -// API calls. For more information, see Instance Metadata and User Data (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html). +// API calls. For more information, see Instance metadata and user data (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html). // // 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 @@ -31059,6 +32345,86 @@ func (c *EC2) ModifyLaunchTemplateWithContext(ctx aws.Context, input *ModifyLaun return out, req.Send() } +const opModifyManagedPrefixList = "ModifyManagedPrefixList" + +// ModifyManagedPrefixListRequest generates a "aws/request.Request" representing the +// client's request for the ModifyManagedPrefixList operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ModifyManagedPrefixList for more information on using the ModifyManagedPrefixList +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ModifyManagedPrefixListRequest method. +// req, resp := client.ModifyManagedPrefixListRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyManagedPrefixList +func (c *EC2) ModifyManagedPrefixListRequest(input *ModifyManagedPrefixListInput) (req *request.Request, output *ModifyManagedPrefixListOutput) { + op := &request.Operation{ + Name: opModifyManagedPrefixList, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ModifyManagedPrefixListInput{} + } + + output = &ModifyManagedPrefixListOutput{} + req = c.newRequest(op, input, output) + return +} + +// ModifyManagedPrefixList API operation for Amazon Elastic Compute Cloud. +// +// Modifies the specified managed prefix list. +// +// Adding or removing entries in a prefix list creates a new version of the +// prefix list. Changing the name of the prefix list does not affect the version. +// +// If you specify a current version number that does not match the true current +// version number, the request fails. +// +// 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 Elastic Compute Cloud's +// API operation ModifyManagedPrefixList for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyManagedPrefixList +func (c *EC2) ModifyManagedPrefixList(input *ModifyManagedPrefixListInput) (*ModifyManagedPrefixListOutput, error) { + req, out := c.ModifyManagedPrefixListRequest(input) + return out, req.Send() +} + +// ModifyManagedPrefixListWithContext is the same as ModifyManagedPrefixList with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyManagedPrefixList 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 *EC2) ModifyManagedPrefixListWithContext(ctx aws.Context, input *ModifyManagedPrefixListInput, opts ...request.Option) (*ModifyManagedPrefixListOutput, error) { + req, out := c.ModifyManagedPrefixListRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opModifyNetworkInterfaceAttribute = "ModifyNetworkInterfaceAttribute" // ModifyNetworkInterfaceAttributeRequest generates a "aws/request.Request" representing the @@ -31271,7 +32637,7 @@ func (c *EC2) ModifySnapshotAttributeRequest(input *ModifySnapshotAttributeInput // be made public. Snapshots encrypted with your default CMK cannot be shared // with other accounts. // -// For more information about modifying snapshot permissions, see Sharing Snapshots +// For more information about modifying snapshot permissions, see Sharing snapshots // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modifying-snapshot-permissions.html) // in the Amazon Elastic Compute Cloud User Guide. // @@ -31716,6 +33082,157 @@ func (c *EC2) ModifyTrafficMirrorSessionWithContext(ctx aws.Context, input *Modi return out, req.Send() } +const opModifyTransitGateway = "ModifyTransitGateway" + +// ModifyTransitGatewayRequest generates a "aws/request.Request" representing the +// client's request for the ModifyTransitGateway operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ModifyTransitGateway for more information on using the ModifyTransitGateway +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ModifyTransitGatewayRequest method. +// req, resp := client.ModifyTransitGatewayRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyTransitGateway +func (c *EC2) ModifyTransitGatewayRequest(input *ModifyTransitGatewayInput) (req *request.Request, output *ModifyTransitGatewayOutput) { + op := &request.Operation{ + Name: opModifyTransitGateway, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ModifyTransitGatewayInput{} + } + + output = &ModifyTransitGatewayOutput{} + req = c.newRequest(op, input, output) + return +} + +// ModifyTransitGateway API operation for Amazon Elastic Compute Cloud. +// +// Modifies the specified transit gateway. When you modify a transit gateway, +// the modified options are applied to new transit gateway attachments only. +// Your existing transit gateway attachments are not modified. +// +// 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 Elastic Compute Cloud's +// API operation ModifyTransitGateway for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyTransitGateway +func (c *EC2) ModifyTransitGateway(input *ModifyTransitGatewayInput) (*ModifyTransitGatewayOutput, error) { + req, out := c.ModifyTransitGatewayRequest(input) + return out, req.Send() +} + +// ModifyTransitGatewayWithContext is the same as ModifyTransitGateway with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyTransitGateway 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 *EC2) ModifyTransitGatewayWithContext(ctx aws.Context, input *ModifyTransitGatewayInput, opts ...request.Option) (*ModifyTransitGatewayOutput, error) { + req, out := c.ModifyTransitGatewayRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + +const opModifyTransitGatewayPrefixListReference = "ModifyTransitGatewayPrefixListReference" + +// ModifyTransitGatewayPrefixListReferenceRequest generates a "aws/request.Request" representing the +// client's request for the ModifyTransitGatewayPrefixListReference operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ModifyTransitGatewayPrefixListReference for more information on using the ModifyTransitGatewayPrefixListReference +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ModifyTransitGatewayPrefixListReferenceRequest method. +// req, resp := client.ModifyTransitGatewayPrefixListReferenceRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyTransitGatewayPrefixListReference +func (c *EC2) ModifyTransitGatewayPrefixListReferenceRequest(input *ModifyTransitGatewayPrefixListReferenceInput) (req *request.Request, output *ModifyTransitGatewayPrefixListReferenceOutput) { + op := &request.Operation{ + Name: opModifyTransitGatewayPrefixListReference, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ModifyTransitGatewayPrefixListReferenceInput{} + } + + output = &ModifyTransitGatewayPrefixListReferenceOutput{} + req = c.newRequest(op, input, output) + return +} + +// ModifyTransitGatewayPrefixListReference API operation for Amazon Elastic Compute Cloud. +// +// Modifies a reference (route) to a prefix list in a specified transit gateway +// route 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 Elastic Compute Cloud's +// API operation ModifyTransitGatewayPrefixListReference for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyTransitGatewayPrefixListReference +func (c *EC2) ModifyTransitGatewayPrefixListReference(input *ModifyTransitGatewayPrefixListReferenceInput) (*ModifyTransitGatewayPrefixListReferenceOutput, error) { + req, out := c.ModifyTransitGatewayPrefixListReferenceRequest(input) + return out, req.Send() +} + +// ModifyTransitGatewayPrefixListReferenceWithContext is the same as ModifyTransitGatewayPrefixListReference with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyTransitGatewayPrefixListReference 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 *EC2) ModifyTransitGatewayPrefixListReferenceWithContext(ctx aws.Context, input *ModifyTransitGatewayPrefixListReferenceInput, opts ...request.Option) (*ModifyTransitGatewayPrefixListReferenceOutput, error) { + req, out := c.ModifyTransitGatewayPrefixListReferenceRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opModifyTransitGatewayVpcAttachment = "ModifyTransitGatewayVpcAttachment" // ModifyTransitGatewayVpcAttachmentRequest generates a "aws/request.Request" representing the @@ -31838,30 +33355,30 @@ func (c *EC2) ModifyVolumeRequest(input *ModifyVolumeInput) (req *request.Reques // size, volume type, and IOPS capacity. If your EBS volume is attached to a // current-generation EC2 instance type, you may be able to apply these changes // without stopping the instance or detaching the volume from it. For more information -// about modifying an EBS volume running Linux, see Modifying the Size, IOPS, -// or Type of an EBS Volume on Linux (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html). +// about modifying an EBS volume running Linux, see Modifying the size, IOPS, +// or type of an EBS volume on Linux (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html). // For more information about modifying an EBS volume running Windows, see Modifying -// the Size, IOPS, or Type of an EBS Volume on Windows (https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ebs-expand-volume.html). +// the size, IOPS, or type of an EBS volume on Windows (https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ebs-expand-volume.html). // // When you complete a resize operation on your volume, you need to extend the // volume's file-system size to take advantage of the new storage capacity. // For information about extending a Linux file system, see Extending a Linux -// File System (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html#recognize-expanded-volume-linux). +// file system (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html#recognize-expanded-volume-linux). // For information about extending a Windows file system, see Extending a Windows -// File System (https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ebs-expand-volume.html#recognize-expanded-volume-windows). +// file system (https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ebs-expand-volume.html#recognize-expanded-volume-windows). // // You can use CloudWatch Events to check the status of a modification to an // EBS volume. For information about CloudWatch Events, see the Amazon CloudWatch // Events User Guide (https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/). // You can also track the status of a modification using DescribeVolumesModifications. // For information about tracking status changes using either method, see Monitoring -// Volume Modifications (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html#monitoring_mods). +// volume modifications (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html#monitoring_mods). // // With previous-generation instance types, resizing an EBS volume may require // detaching and reattaching the volume or stopping and restarting the instance. -// For more information, see Modifying the Size, IOPS, or Type of an EBS Volume +// For more information, see Modifying the size, IOPS, or type of an EBS volume // on Linux (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html) -// and Modifying the Size, IOPS, or Type of an EBS Volume on Windows (https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ebs-expand-volume.html). +// and Modifying the size, IOPS, or type of an EBS volume on Windows (https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ebs-expand-volume.html). // // If you reach the maximum volume modification rate per volume limit, you will // need to wait at least six hours before applying further modifications to @@ -32594,8 +34111,9 @@ func (c *EC2) ModifyVpnConnectionRequest(input *ModifyVpnConnectionInput) (req * // ModifyVpnConnection API operation for Amazon Elastic Compute Cloud. // -// Modifies the target gateway of an AWS Site-to-Site VPN connection. The following -// migration options are available: +// Modifies the customer gateway or the target gateway of an AWS Site-to-Site +// VPN connection. To modify the target gateway, the following migration options +// are available: // // * An existing virtual private gateway to a new virtual private gateway // @@ -32663,6 +34181,85 @@ func (c *EC2) ModifyVpnConnectionWithContext(ctx aws.Context, input *ModifyVpnCo return out, req.Send() } +const opModifyVpnConnectionOptions = "ModifyVpnConnectionOptions" + +// ModifyVpnConnectionOptionsRequest generates a "aws/request.Request" representing the +// client's request for the ModifyVpnConnectionOptions operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ModifyVpnConnectionOptions for more information on using the ModifyVpnConnectionOptions +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ModifyVpnConnectionOptionsRequest method. +// req, resp := client.ModifyVpnConnectionOptionsRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpnConnectionOptions +func (c *EC2) ModifyVpnConnectionOptionsRequest(input *ModifyVpnConnectionOptionsInput) (req *request.Request, output *ModifyVpnConnectionOptionsOutput) { + op := &request.Operation{ + Name: opModifyVpnConnectionOptions, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ModifyVpnConnectionOptionsInput{} + } + + output = &ModifyVpnConnectionOptionsOutput{} + req = c.newRequest(op, input, output) + return +} + +// ModifyVpnConnectionOptions API operation for Amazon Elastic Compute Cloud. +// +// Modifies the connection options for your Site-to-Site VPN VPN connection. +// +// When you modify the VPN connection options, the VPN endpoint IP addresses +// on the AWS side do not change, and the tunnel options do not change. Your +// VPN connection will be temporarily unavailable for a brief period while the +// VPN connection is updated. +// +// 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 Elastic Compute Cloud's +// API operation ModifyVpnConnectionOptions for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/ModifyVpnConnectionOptions +func (c *EC2) ModifyVpnConnectionOptions(input *ModifyVpnConnectionOptionsInput) (*ModifyVpnConnectionOptionsOutput, error) { + req, out := c.ModifyVpnConnectionOptionsRequest(input) + return out, req.Send() +} + +// ModifyVpnConnectionOptionsWithContext is the same as ModifyVpnConnectionOptions with the addition of +// the ability to pass a context and additional request options. +// +// See ModifyVpnConnectionOptions 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 *EC2) ModifyVpnConnectionOptionsWithContext(ctx aws.Context, input *ModifyVpnConnectionOptionsInput, opts ...request.Option) (*ModifyVpnConnectionOptionsOutput, error) { + req, out := c.ModifyVpnConnectionOptionsRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opModifyVpnTunnelCertificate = "ModifyVpnTunnelCertificate" // ModifyVpnTunnelCertificateRequest generates a "aws/request.Request" representing the @@ -32860,7 +34457,7 @@ func (c *EC2) MonitorInstancesRequest(input *MonitorInstancesInput) (req *reques // MonitorInstances API operation for Amazon Elastic Compute Cloud. // // Enables detailed monitoring for a running instance. Otherwise, basic monitoring -// is enabled. For more information, see Monitoring Your Instances and Volumes +// is enabled. For more information, see Monitoring your instances and volumes // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) // in the Amazon Elastic Compute Cloud User Guide. // @@ -33364,8 +34961,8 @@ func (c *EC2) RebootInstancesRequest(input *RebootInstancesInput) (req *request. // If an instance does not cleanly shut down within four minutes, Amazon EC2 // performs a hard reboot. // -// For more information about troubleshooting, see Getting Console Output and -// Rebooting Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) +// For more information about troubleshooting, see Getting console output and +// rebooting instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -33442,7 +35039,7 @@ func (c *EC2) RegisterImageRequest(input *RegisterImageInput) (req *request.Requ // // Registers an AMI. When you're creating an AMI, this is the final step you // must complete before you can launch an instance from the AMI. For more information -// about creating AMIs, see Creating Your Own AMIs (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami.html) +// about creating AMIs, see Creating your own AMIs (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami.html) // in the Amazon Elastic Compute Cloud User Guide. // // For Amazon EBS-backed instances, CreateImage creates and registers the AMI @@ -33450,12 +35047,12 @@ func (c *EC2) RegisterImageRequest(input *RegisterImageInput) (req *request.Requ // // You can also use RegisterImage to create an Amazon EBS-backed Linux AMI from // a snapshot of a root device volume. You specify the snapshot using the block -// device mapping. For more information, see Launching a Linux Instance from -// a Backup (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-launch-snapshot.html) +// device mapping. For more information, see Launching a Linux instance from +// a backup (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-launch-snapshot.html) // in the Amazon Elastic Compute Cloud User Guide. // -// You can't register an image where a secondary (non-root) snapshot has AWS -// Marketplace product codes. +// If any snapshots have AWS Marketplace product codes, they are copied to the +// new AMI. // // Windows and some Linux distributions, such as Red Hat Enterprise Linux (RHEL) // and SUSE Linux Enterprise Server (SLES), use the EC2 billing product code @@ -33476,7 +35073,7 @@ func (c *EC2) RegisterImageRequest(input *RegisterImageInput) (req *request.Requ // a Reserved Instance without the matching billing product code, the Reserved // Instance will not be applied to the On-Demand Instance. For information about // how to obtain the platform details and billing information of an AMI, see -// Obtaining Billing Information (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-billing-info.html) +// Obtaining billing information (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-billing-info.html) // in the Amazon Elastic Compute Cloud User Guide. // // If needed, you can deregister an AMI at any time. Any modifications you make @@ -34854,7 +36451,7 @@ func (c *EC2) RequestSpotFleetRequest(input *RequestSpotFleetInput) (req *reques // the fleet. You cannot tag other resource types in a Spot Fleet request because // only the spot-fleet-request and instance resource types are supported. // -// For more information, see Spot Fleet Requests (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet-requests.html) +// For more information, see Spot Fleet requests (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet-requests.html) // in the Amazon EC2 User Guide for Linux Instances. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -34931,7 +36528,7 @@ func (c *EC2) RequestSpotInstancesRequest(input *RequestSpotInstancesInput) (req // // Creates a Spot Instance request. // -// For more information, see Spot Instance Requests (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-requests.html) +// For more information, see Spot Instance requests (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-requests.html) // in the Amazon EC2 User Guide for Linux Instances. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -35400,7 +36997,7 @@ func (c *EC2) ResetSnapshotAttributeRequest(input *ResetSnapshotAttributeInput) // // Resets permission settings for the specified snapshot. // -// For more information about modifying snapshot permissions, see Sharing Snapshots +// For more information about modifying snapshot permissions, see Sharing snapshots // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modifying-snapshot-permissions.html) // in the Amazon Elastic Compute Cloud User Guide. // @@ -35509,6 +37106,81 @@ func (c *EC2) RestoreAddressToClassicWithContext(ctx aws.Context, input *Restore return out, req.Send() } +const opRestoreManagedPrefixListVersion = "RestoreManagedPrefixListVersion" + +// RestoreManagedPrefixListVersionRequest generates a "aws/request.Request" representing the +// client's request for the RestoreManagedPrefixListVersion operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See RestoreManagedPrefixListVersion for more information on using the RestoreManagedPrefixListVersion +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the RestoreManagedPrefixListVersionRequest method. +// req, resp := client.RestoreManagedPrefixListVersionRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RestoreManagedPrefixListVersion +func (c *EC2) RestoreManagedPrefixListVersionRequest(input *RestoreManagedPrefixListVersionInput) (req *request.Request, output *RestoreManagedPrefixListVersionOutput) { + op := &request.Operation{ + Name: opRestoreManagedPrefixListVersion, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &RestoreManagedPrefixListVersionInput{} + } + + output = &RestoreManagedPrefixListVersionOutput{} + req = c.newRequest(op, input, output) + return +} + +// RestoreManagedPrefixListVersion API operation for Amazon Elastic Compute Cloud. +// +// Restores the entries from a previous version of a managed prefix list to +// a new version of the prefix list. +// +// 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 Elastic Compute Cloud's +// API operation RestoreManagedPrefixListVersion for usage and error information. +// See also, https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/RestoreManagedPrefixListVersion +func (c *EC2) RestoreManagedPrefixListVersion(input *RestoreManagedPrefixListVersionInput) (*RestoreManagedPrefixListVersionOutput, error) { + req, out := c.RestoreManagedPrefixListVersionRequest(input) + return out, req.Send() +} + +// RestoreManagedPrefixListVersionWithContext is the same as RestoreManagedPrefixListVersion with the addition of +// the ability to pass a context and additional request options. +// +// See RestoreManagedPrefixListVersion 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 *EC2) RestoreManagedPrefixListVersionWithContext(ctx aws.Context, input *RestoreManagedPrefixListVersionInput, opts ...request.Option) (*RestoreManagedPrefixListVersionOutput, error) { + req, out := c.RestoreManagedPrefixListVersionRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + const opRevokeClientVpnIngress = "RevokeClientVpnIngress" // RevokeClientVpnIngressRequest generates a "aws/request.Request" representing the @@ -35819,17 +37491,17 @@ func (c *EC2) RunInstancesRequest(input *RunInstancesInput) (req *request.Reques // // * Some instance types must be launched into a VPC. If you do not have // a default VPC, or if you do not specify a subnet ID, the request fails. -// For more information, see Instance Types Available Only in a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-vpc.html#vpc-only-instance-types). +// For more information, see Instance types available only in a VPC (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-vpc.html#vpc-only-instance-types). // // * [EC2-VPC] All instances have a network interface with a primary private // IPv4 address. If you don't specify this address, we choose one from the // IPv4 range of your subnet. // // * Not all instance types support IPv6 addresses. For more information, -// see Instance Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html). +// see Instance types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html). // // * If you don't specify a security group ID, we use the default security -// group. For more information, see Security Groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html). +// group. For more information, see Security groups (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html). // // * If any of the AMIs have a product code attached for which the user has // not subscribed, the request fails. @@ -35846,17 +37518,17 @@ func (c *EC2) RunInstancesRequest(input *RunInstancesInput) (req *request.Reques // An instance is ready for you to use when it's in the running state. You can // check the state of your instance using DescribeInstances. You can tag instances // and EBS volumes during launch, after launch, or both. For more information, -// see CreateTags and Tagging Your Amazon EC2 Resources (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html). +// see CreateTags and Tagging your Amazon EC2 resources (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html). // // Linux instances have access to the public key of the key pair at boot. You // can use this key to provide secure access to the instance. Amazon EC2 public // images use this feature to provide secure access without passwords. For more -// information, see Key Pairs (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) +// information, see Key pairs (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) // in the Amazon Elastic Compute Cloud User Guide. // -// For troubleshooting, see What To Do If An Instance Immediately Terminates +// For troubleshooting, see What to do if an instance immediately terminates // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_InstanceStraightToTerminated.html), -// and Troubleshooting Connecting to Your Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html) +// and Troubleshooting connecting to your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -36369,8 +38041,8 @@ func (c *EC2) SendDiagnosticInterruptRequest(input *SendDiagnosticInterruptInput // system is configured to perform the required diagnostic tasks. // // For more information about configuring your operating system to generate -// a crash dump when a kernel panic or stop error occurs, see Send a Diagnostic -// Interrupt (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/diagnostic-interrupt.html) +// a crash dump when a kernel panic or stop error occurs, see Send a diagnostic +// interrupt (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/diagnostic-interrupt.html) // (Linux instances) or Send a Diagnostic Interrupt (https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/diagnostic-interrupt.html) // (Windows instances). // @@ -36467,7 +38139,7 @@ func (c *EC2) StartInstancesRequest(input *StartInstancesInput) (req *request.Re // Performing this operation on an instance that uses an instance store as its // root device returns an error. // -// For more information, see Stopping Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) +// For more information, see Stopping instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -36630,7 +38302,7 @@ func (c *EC2) StopInstancesRequest(input *StopInstancesInput) (req *request.Requ // You can use the Stop action to hibernate an instance if the instance is enabled // for hibernation (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#enabling-hibernation) // and it meets the hibernation prerequisites (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites). -// For more information, see Hibernate Your Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) +// For more information, see Hibernate your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) // in the Amazon Elastic Compute Cloud User Guide. // // We don't charge usage for a stopped instance, or data transfer fees; however, @@ -36646,7 +38318,7 @@ func (c *EC2) StopInstancesRequest(input *StopInstancesInput) (req *request.Requ // You can't stop or hibernate instance store-backed instances. You can't use // the Stop action to hibernate Spot Instances, but you can specify that Amazon // EC2 should hibernate Spot Instances when they are interrupted. For more information, -// see Hibernating Interrupted Spot Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) +// see Hibernating interrupted Spot Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html#hibernate-spot-instances) // in the Amazon Elastic Compute Cloud User Guide. // // When you stop or hibernate an instance, we shut it down. You can restart @@ -36662,13 +38334,13 @@ func (c *EC2) StopInstancesRequest(input *StopInstancesInput) (req *request.Requ // an instance, the root device and any other devices attached during the instance // launch are automatically deleted. For more information about the differences // between rebooting, stopping, hibernating, and terminating instances, see -// Instance Lifecycle (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) +// Instance lifecycle (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) // in the Amazon Elastic Compute Cloud User Guide. // // When you stop an instance, we attempt to shut it down forcibly after a short // while. If your instance appears stuck in the stopping state after a period // of time, there may be an issue with the underlying host computer. For more -// information, see Troubleshooting Stopping Your Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) +// information, see Troubleshooting stopping your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesStopping.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -36838,11 +38510,11 @@ func (c *EC2) TerminateInstancesRequest(input *TerminateInstancesInput) (req *re // an instance, any attached EBS volumes with the DeleteOnTermination block // device mapping parameter set to true are automatically deleted. For more // information about the differences between stopping and terminating instances, -// see Instance Lifecycle (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) +// see Instance lifecycle (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html) // in the Amazon Elastic Compute Cloud User Guide. // -// For more information about troubleshooting, see Troubleshooting Terminating -// Your Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) +// For more information about troubleshooting, see Troubleshooting terminating +// your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesShuttingDown.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -37067,7 +38739,7 @@ func (c *EC2) UnmonitorInstancesRequest(input *UnmonitorInstancesInput) (req *re // UnmonitorInstances API operation for Amazon Elastic Compute Cloud. // // Disables detailed monitoring for a running instance. For more information, -// see Monitoring Your Instances and Volumes (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) +// see Monitoring your instances and volumes (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-cloudwatch.html) // in the Amazon Elastic Compute Cloud User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -37836,7 +39508,57 @@ func (s *ActiveInstance) SetSpotInstanceRequestId(v string) *ActiveInstance { return s } -// Describes an Elastic IP address. +// An entry for a prefix list. +type AddPrefixListEntry struct { + _ struct{} `type:"structure"` + + // The CIDR block. + // + // Cidr is a required field + Cidr *string `type:"string" required:"true"` + + // A description for the entry. + // + // Constraints: Up to 255 characters in length. + Description *string `type:"string"` +} + +// String returns the string representation +func (s AddPrefixListEntry) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s AddPrefixListEntry) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *AddPrefixListEntry) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "AddPrefixListEntry"} + if s.Cidr == nil { + invalidParams.Add(request.NewErrParamRequired("Cidr")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCidr sets the Cidr field's value. +func (s *AddPrefixListEntry) SetCidr(v string) *AddPrefixListEntry { + s.Cidr = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *AddPrefixListEntry) SetDescription(v string) *AddPrefixListEntry { + s.Description = &v + return s +} + +// Describes an Elastic IP address, or a carrier IP address. type Address struct { _ struct{} `type:"structure"` @@ -37847,6 +39569,11 @@ type Address struct { // VPC. AssociationId *string `locationName:"associationId" type:"string"` + // The carrier IP address associated. This option is only available for network + // interfaces which reside in a subnet in a Wavelength Zone (for example an + // EC2 instance). + CarrierIp *string `locationName:"carrierIp" type:"string"` + // The customer-owned IP address. CustomerOwnedIp *string `locationName:"customerOwnedIp" type:"string"` @@ -37860,7 +39587,8 @@ type Address struct { // The ID of the instance that the address is associated with (if any). InstanceId *string `locationName:"instanceId" type:"string"` - // The name of the location from which the IP address is advertised. + // The name of the unique set of Availability Zones, Local Zones, or Wavelength + // Zones from which AWS advertises IP addresses. NetworkBorderGroup *string `locationName:"networkBorderGroup" type:"string"` // The ID of the network interface. @@ -37904,6 +39632,12 @@ func (s *Address) SetAssociationId(v string) *Address { return s } +// SetCarrierIp sets the CarrierIp field's value. +func (s *Address) SetCarrierIp(v string) *Address { + s.CarrierIp = &v + return s +} + // SetCustomerOwnedIp sets the CustomerOwnedIp field's value. func (s *Address) SetCustomerOwnedIp(v string) *Address { s.CustomerOwnedIp = &v @@ -38056,9 +39790,11 @@ type AllocateAddressInput struct { // address from the address pool. CustomerOwnedIpv4Pool *string `type:"string"` - // Set to vpc to allocate the address for use with instances in a VPC. + // Indicates whether the Elastic IP address is for use with instances in a VPC + // or instances in EC2-Classic. // - // Default: The address is for use with instances in EC2-Classic. + // Default: If the Region supports EC2-Classic, the default is standard. Otherwise, + // the default is vpc. Domain *string `type:"string" enum:"DomainType"` // Checks whether you have the required permissions for the action, without @@ -38067,12 +39803,9 @@ type AllocateAddressInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // The location from which the IP address is advertised. Use this parameter - // to limit the address to this location. - // - // A network border group is a unique set of Availability Zones or Local Zones - // from where AWS advertises IP addresses and limits the addresses to the group. - // IP addresses cannot move between network border groups. + // A unique set of Availability Zones, Local Zones, or Wavelength Zones from + // which AWS advertises IP addresses. Use this parameter to limit the IP address + // to this location. IP addresses cannot move between network border groups. // // Use DescribeAvailabilityZones (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeAvailabilityZones.html) // to view the network border groups. @@ -38141,17 +39874,22 @@ type AllocateAddressOutput struct { // IP address for use with instances in a VPC. AllocationId *string `locationName:"allocationId" type:"string"` + // The carrier IP address. This option is only available for network interfaces + // which reside in a subnet in a Wavelength Zone (for example an EC2 instance). + CarrierIp *string `locationName:"carrierIp" type:"string"` + // The customer-owned IP address. CustomerOwnedIp *string `locationName:"customerOwnedIp" type:"string"` // The ID of the customer-owned address pool. CustomerOwnedIpv4Pool *string `locationName:"customerOwnedIpv4Pool" type:"string"` - // Indicates whether this Elastic IP address is for use with instances in EC2-Classic - // (standard) or instances in a VPC (vpc). + // Indicates whether the Elastic IP address is for use with instances in a VPC + // (vpc) or instances in EC2-Classic (standard). Domain *string `locationName:"domain" type:"string" enum:"DomainType"` - // The location from which the IP address is advertised. + // The set of Availability Zones, Local Zones, or Wavelength Zones from which + // AWS advertises IP addresses. NetworkBorderGroup *string `locationName:"networkBorderGroup" type:"string"` // The Elastic IP address. @@ -38177,6 +39915,12 @@ func (s *AllocateAddressOutput) SetAllocationId(v string) *AllocateAddressOutput return s } +// SetCarrierIp sets the CarrierIp field's value. +func (s *AllocateAddressOutput) SetCarrierIp(v string) *AllocateAddressOutput { + s.CarrierIp = &v + return s +} + // SetCustomerOwnedIp sets the CustomerOwnedIp field's value. func (s *AllocateAddressOutput) SetCustomerOwnedIp(v string) *AllocateAddressOutput { s.CustomerOwnedIp = &v @@ -39469,7 +41213,7 @@ type AssociateVpcCidrBlockInput struct { Ipv6CidrBlock *string `type:"string"` // The name of the location from which we advertise the IPV6 CIDR block. Use - // this parameter to limit the CiDR block to this location. + // this parameter to limit the CIDR block to this location. // // You must set AmazonProvidedIpv6CidrBlock to true to use this parameter. // @@ -40225,11 +41969,14 @@ func (s *AuthorizationRule) SetStatus(v *ClientVpnAuthorizationRuleStatus) *Auth type AuthorizeClientVpnIngressInput struct { _ struct{} `type:"structure"` - // The ID of the Active Directory group to grant access. + // The ID of the group to grant access to, for example, the Active Directory + // group or identity provider (IdP) group. Required if AuthorizeAllGroups is + // false or not specified. AccessGroupId *string `type:"string"` - // Indicates whether to grant access to all clients. Use true to grant all clients - // who successfully establish a VPN connection access to the network. + // Indicates whether to grant access to all clients. Specify true to grant all + // clients who successfully establish a VPN connection access to the network. + // Must be set to true if AccessGroupId is not specified. AuthorizeAllGroups *bool `type:"boolean"` // Unique, case-sensitive identifier that you provide to ensure the idempotency @@ -40637,38 +42384,52 @@ func (s AuthorizeSecurityGroupIngressOutput) GoString() string { return s.String() } -// Describes an Availability Zone or Local Zone. +// Describes Availability Zones, Local Zones, and Wavelength Zones. type AvailabilityZone struct { _ struct{} `type:"structure"` // For Availability Zones, this parameter has the same value as the Region name. // // For Local Zones, the name of the associated group, for example us-west-2-lax-1. + // + // For Wavelength Zones, the name of the associated group, for example us-east-1-wl1-bos-wlz-1. GroupName *string `locationName:"groupName" type:"string"` - // Any messages about the Availability Zone or Local Zone. + // Any messages about the Availability Zone, Local Zone, or Wavelength Zone. Messages []*AvailabilityZoneMessage `locationName:"messageSet" locationNameList:"item" type:"list"` - // The name of the location from which the address is advertised. + // The name of the network border group. NetworkBorderGroup *string `locationName:"networkBorderGroup" type:"string"` // For Availability Zones, this parameter always has the value of opt-in-not-required. // - // For Local Zones, this parameter is the opt in status. The possible values - // are opted-in, and not-opted-in. + // For Local Zones and Wavelength Zones, this parameter is the opt-in status. + // The possible values are opted-in, and not-opted-in. OptInStatus *string `locationName:"optInStatus" type:"string" enum:"AvailabilityZoneOptInStatus"` + // The ID of the zone that handles some of the Local Zone or Wavelength Zone + // control plane operations, such as API calls. + ParentZoneId *string `locationName:"parentZoneId" type:"string"` + + // The name of the zone that handles some of the Local Zone or Wavelength Zone + // control plane operations, such as API calls. + ParentZoneName *string `locationName:"parentZoneName" type:"string"` + // The name of the Region. RegionName *string `locationName:"regionName" type:"string"` - // The state of the Availability Zone or Local Zone. + // The state of the Availability Zone, Local Zone, or Wavelength Zone. State *string `locationName:"zoneState" type:"string" enum:"AvailabilityZoneState"` - // The ID of the Availability Zone or Local Zone. + // The ID of the Availability Zone, Local Zone, or Wavelength Zone. ZoneId *string `locationName:"zoneId" type:"string"` - // The name of the Availability Zone or Local Zone. + // The name of the Availability Zone, Local Zone, or Wavelength Zone. ZoneName *string `locationName:"zoneName" type:"string"` + + // The type of zone. The valid values are availability-zone, local-zone, and + // wavelength-zone. + ZoneType *string `locationName:"zoneType" type:"string"` } // String returns the string representation @@ -40705,6 +42466,18 @@ func (s *AvailabilityZone) SetOptInStatus(v string) *AvailabilityZone { return s } +// SetParentZoneId sets the ParentZoneId field's value. +func (s *AvailabilityZone) SetParentZoneId(v string) *AvailabilityZone { + s.ParentZoneId = &v + return s +} + +// SetParentZoneName sets the ParentZoneName field's value. +func (s *AvailabilityZone) SetParentZoneName(v string) *AvailabilityZone { + s.ParentZoneName = &v + return s +} + // SetRegionName sets the RegionName field's value. func (s *AvailabilityZone) SetRegionName(v string) *AvailabilityZone { s.RegionName = &v @@ -40729,11 +42502,18 @@ func (s *AvailabilityZone) SetZoneName(v string) *AvailabilityZone { return s } -// Describes a message about an Availability Zone or Local Zone. +// SetZoneType sets the ZoneType field's value. +func (s *AvailabilityZone) SetZoneType(v string) *AvailabilityZone { + s.ZoneType = &v + return s +} + +// Describes a message about an Availability Zone, Local Zone, or Wavelength +// Zone. type AvailabilityZoneMessage struct { _ struct{} `type:"structure"` - // The message about the Availability Zone or Local Zone. + // The message about the Availability Zone, Local Zone, or Wavelength Zone. Message *string `locationName:"message" type:"string"` } @@ -42116,6 +43896,39 @@ func (s *CapacityReservation) SetTotalInstanceCount(v int64) *CapacityReservatio return s } +// Describes a resource group to which a Capacity Reservation has been added. +type CapacityReservationGroup struct { + _ struct{} `type:"structure"` + + // The ARN of the resource group. + GroupArn *string `locationName:"groupArn" type:"string"` + + // The ID of the AWS account that owns the resource group. + OwnerId *string `locationName:"ownerId" type:"string"` +} + +// String returns the string representation +func (s CapacityReservationGroup) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CapacityReservationGroup) GoString() string { + return s.String() +} + +// SetGroupArn sets the GroupArn field's value. +func (s *CapacityReservationGroup) SetGroupArn(v string) *CapacityReservationGroup { + s.GroupArn = &v + return s +} + +// SetOwnerId sets the OwnerId field's value. +func (s *CapacityReservationGroup) SetOwnerId(v string) *CapacityReservationGroup { + s.OwnerId = &v + return s +} + // Describes the strategy for using unused Capacity Reservations for fulfilling // On-Demand capacity. // @@ -42214,7 +44027,7 @@ func (s *CapacityReservationOptionsRequest) SetUsageStrategy(v string) *Capacity // to run as an On-Demand Instance or to run in any open Capacity Reservation // that has matching attributes (instance type, platform, Availability Zone). // Use the CapacityReservationTarget parameter to explicitly target a specific -// Capacity Reservation. +// Capacity Reservation or a Capacity Reservation group. type CapacityReservationSpecification struct { _ struct{} `type:"structure"` @@ -42228,7 +44041,8 @@ type CapacityReservationSpecification struct { // one is available. The instance runs as an On-Demand Instance. CapacityReservationPreference *string `type:"string" enum:"CapacityReservationPreference"` - // Information about the target Capacity Reservation. + // Information about the target Capacity Reservation or Capacity Reservation + // group. CapacityReservationTarget *CapacityReservationTarget `type:"structure"` } @@ -42259,7 +44073,8 @@ func (s *CapacityReservationSpecification) SetCapacityReservationTarget(v *Capac // instance is configured to run in On-Demand capacity, or if it is configured // in run in any open Capacity Reservation that has matching attributes (instance // type, platform, Availability Zone). The action returns the capacityReservationTarget -// response element if the instance explicily targets a specific Capacity Reservation. +// response element if the instance explicily targets a specific Capacity Reservation +// or Capacity Reservation group. type CapacityReservationSpecificationResponse struct { _ struct{} `type:"structure"` @@ -42273,7 +44088,8 @@ type CapacityReservationSpecificationResponse struct { // one is available. The instance runs in On-Demand capacity. CapacityReservationPreference *string `locationName:"capacityReservationPreference" type:"string" enum:"CapacityReservationPreference"` - // Information about the targeted Capacity Reservation. + // Information about the targeted Capacity Reservation or Capacity Reservation + // group. CapacityReservationTarget *CapacityReservationTargetResponse `locationName:"capacityReservationTarget" type:"structure"` } @@ -42299,12 +44115,15 @@ func (s *CapacityReservationSpecificationResponse) SetCapacityReservationTarget( return s } -// Describes a target Capacity Reservation. +// Describes a target Capacity Reservation or Capacity Reservation group. type CapacityReservationTarget struct { _ struct{} `type:"structure"` - // The ID of the Capacity Reservation. + // The ID of the Capacity Reservation in which to run the instance. CapacityReservationId *string `type:"string"` + + // The ARN of the Capacity Reservation resource group in which to run the instance. + CapacityReservationResourceGroupArn *string `type:"string"` } // String returns the string representation @@ -42323,12 +44142,21 @@ func (s *CapacityReservationTarget) SetCapacityReservationId(v string) *Capacity return s } -// Describes a target Capacity Reservation. +// SetCapacityReservationResourceGroupArn sets the CapacityReservationResourceGroupArn field's value. +func (s *CapacityReservationTarget) SetCapacityReservationResourceGroupArn(v string) *CapacityReservationTarget { + s.CapacityReservationResourceGroupArn = &v + return s +} + +// Describes a target Capacity Reservation or Capacity Reservation group. type CapacityReservationTargetResponse struct { _ struct{} `type:"structure"` - // The ID of the Capacity Reservation. + // The ID of the targeted Capacity Reservation. CapacityReservationId *string `locationName:"capacityReservationId" type:"string"` + + // The ARN of the targeted Capacity Reservation group. + CapacityReservationResourceGroupArn *string `locationName:"capacityReservationResourceGroupArn" type:"string"` } // String returns the string representation @@ -42347,6 +44175,72 @@ func (s *CapacityReservationTargetResponse) SetCapacityReservationId(v string) * return s } +// SetCapacityReservationResourceGroupArn sets the CapacityReservationResourceGroupArn field's value. +func (s *CapacityReservationTargetResponse) SetCapacityReservationResourceGroupArn(v string) *CapacityReservationTargetResponse { + s.CapacityReservationResourceGroupArn = &v + return s +} + +// Describes a carrier gateway. +type CarrierGateway struct { + _ struct{} `type:"structure"` + + // The ID of the carrier gateway. + CarrierGatewayId *string `locationName:"carrierGatewayId" type:"string"` + + // The AWS account ID of the owner of the carrier gateway. + OwnerId *string `locationName:"ownerId" type:"string"` + + // The state of the carrier gateway. + State *string `locationName:"state" type:"string" enum:"CarrierGatewayState"` + + // The tags assigned to the carrier gateway. + Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` + + // The ID of the VPC associated with the carrier gateway. + VpcId *string `locationName:"vpcId" type:"string"` +} + +// String returns the string representation +func (s CarrierGateway) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CarrierGateway) GoString() string { + return s.String() +} + +// SetCarrierGatewayId sets the CarrierGatewayId field's value. +func (s *CarrierGateway) SetCarrierGatewayId(v string) *CarrierGateway { + s.CarrierGatewayId = &v + return s +} + +// SetOwnerId sets the OwnerId field's value. +func (s *CarrierGateway) SetOwnerId(v string) *CarrierGateway { + s.OwnerId = &v + return s +} + +// SetState sets the State field's value. +func (s *CarrierGateway) SetState(v string) *CarrierGateway { + s.State = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *CarrierGateway) SetTags(v []*Tag) *CarrierGateway { + s.Tags = v + return s +} + +// SetVpcId sets the VpcId field's value. +func (s *CarrierGateway) SetVpcId(v string) *CarrierGateway { + s.VpcId = &v + return s +} + // Information about the client certificate used for authentication. type CertificateAuthentication struct { _ struct{} `type:"structure"` @@ -42708,9 +44602,8 @@ func (s *ClientData) SetUploadStart(v time.Time) *ClientData { return s } -// Describes the authentication methods used by a Client VPN endpoint. Client -// VPN supports Active Directory and mutual authentication. For more information, -// see Authentication (https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/authentication-authrization.html#client-authentication) +// Describes the authentication methods used by a Client VPN endpoint. For more +// information, see Authentication (https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/authentication-authrization.html#client-authentication) // in the AWS Client VPN Administrator Guide. type ClientVpnAuthentication struct { _ struct{} `type:"structure"` @@ -42718,6 +44611,9 @@ type ClientVpnAuthentication struct { // Information about the Active Directory, if applicable. ActiveDirectory *DirectoryServiceAuthentication `locationName:"activeDirectory" type:"structure"` + // Information about the IAM SAML identity provider, if applicable. + FederatedAuthentication *FederatedAuthentication `locationName:"federatedAuthentication" type:"structure"` + // Information about the authentication certificates, if applicable. MutualAuthentication *CertificateAuthentication `locationName:"mutualAuthentication" type:"structure"` @@ -42741,6 +44637,12 @@ func (s *ClientVpnAuthentication) SetActiveDirectory(v *DirectoryServiceAuthenti return s } +// SetFederatedAuthentication sets the FederatedAuthentication field's value. +func (s *ClientVpnAuthentication) SetFederatedAuthentication(v *FederatedAuthentication) *ClientVpnAuthentication { + s.FederatedAuthentication = v + return s +} + // SetMutualAuthentication sets the MutualAuthentication field's value. func (s *ClientVpnAuthentication) SetMutualAuthentication(v *CertificateAuthentication) *ClientVpnAuthentication { s.MutualAuthentication = v @@ -42754,8 +44656,7 @@ func (s *ClientVpnAuthentication) SetType(v string) *ClientVpnAuthentication { } // Describes the authentication method to be used by a Client VPN endpoint. -// Client VPN supports Active Directory and mutual authentication. For more -// information, see Authentication (https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/authentication-authrization.html#client-authentication) +// For more information, see Authentication (https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/authentication-authrization.html#client-authentication) // in the AWS Client VPN Administrator Guide. type ClientVpnAuthenticationRequest struct { _ struct{} `type:"structure"` @@ -42764,13 +44665,15 @@ type ClientVpnAuthenticationRequest struct { // provide this information if Type is directory-service-authentication. ActiveDirectory *DirectoryServiceAuthenticationRequest `type:"structure"` + // Information about the IAM SAML identity provider to be used, if applicable. + // You must provide this information if Type is federated-authentication. + FederatedAuthentication *FederatedAuthenticationRequest `type:"structure"` + // Information about the authentication certificates to be used, if applicable. // You must provide this information if Type is certificate-authentication. MutualAuthentication *CertificateAuthenticationRequest `type:"structure"` - // The type of client authentication to be used. Specify certificate-authentication - // to use certificate-based authentication, or directory-service-authentication - // to use Active Directory authentication. + // The type of client authentication to be used. Type *string `type:"string" enum:"ClientVpnAuthenticationType"` } @@ -42790,6 +44693,12 @@ func (s *ClientVpnAuthenticationRequest) SetActiveDirectory(v *DirectoryServiceA return s } +// SetFederatedAuthentication sets the FederatedAuthentication field's value. +func (s *ClientVpnAuthenticationRequest) SetFederatedAuthentication(v *FederatedAuthenticationRequest) *ClientVpnAuthenticationRequest { + s.FederatedAuthentication = v + return s +} + // SetMutualAuthentication sets the MutualAuthentication field's value. func (s *ClientVpnAuthenticationRequest) SetMutualAuthentication(v *CertificateAuthenticationRequest) *ClientVpnAuthenticationRequest { s.MutualAuthentication = v @@ -43415,6 +45324,9 @@ type CoipPool struct { // The ID of the local gateway route table. LocalGatewayRouteTableId *string `locationName:"localGatewayRouteTableId" type:"string"` + // The ARN of the address pool. + PoolArn *string `locationName:"poolArn" min:"1" type:"string"` + // The address ranges of the address pool. PoolCidrs []*string `locationName:"poolCidrSet" locationNameList:"item" type:"list"` @@ -43441,6 +45353,12 @@ func (s *CoipPool) SetLocalGatewayRouteTableId(v string) *CoipPool { return s } +// SetPoolArn sets the PoolArn field's value. +func (s *CoipPool) SetPoolArn(v string) *CoipPool { + s.PoolArn = &v + return s +} + // SetPoolCidrs sets the PoolCidrs field's value. func (s *CoipPool) SetPoolCidrs(v []*string) *CoipPool { s.PoolCidrs = v @@ -43561,7 +45479,8 @@ func (s *ConfirmProductInstanceOutput) SetReturn(v bool) *ConfirmProductInstance type ConnectionLogOptions struct { _ struct{} `type:"structure"` - // The name of the CloudWatch Logs log group. + // The name of the CloudWatch Logs log group. Required if connection logging + // is enabled. CloudwatchLogGroup *string `type:"string"` // The name of the CloudWatch Logs log stream to which the connection data is @@ -44362,8 +46281,6 @@ type CreateCapacityReservationInput struct { // Unique, case-sensitive identifier that you provide to ensure the idempotency // of the request. For more information, see How to Ensure Idempotency (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). - // - // Constraint: Maximum 64 ASCII characters. ClientToken *string `type:"string"` // Checks whether you have the required permissions for the action, without @@ -44591,6 +46508,98 @@ func (s *CreateCapacityReservationOutput) SetCapacityReservation(v *CapacityRese return s } +type CreateCarrierGatewayInput struct { + _ struct{} `type:"structure"` + + // Unique, case-sensitive identifier that you provide to ensure the idempotency + // of the request. For more information, see How to Ensure Idempotency (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html). + ClientToken *string `type:"string" idempotencyToken:"true"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The tags to associate with the carrier gateway. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + + // The ID of the VPC to associate with the carrier gateway. + // + // VpcId is a required field + VpcId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s CreateCarrierGatewayInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateCarrierGatewayInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateCarrierGatewayInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateCarrierGatewayInput"} + if s.VpcId == nil { + invalidParams.Add(request.NewErrParamRequired("VpcId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetClientToken sets the ClientToken field's value. +func (s *CreateCarrierGatewayInput) SetClientToken(v string) *CreateCarrierGatewayInput { + s.ClientToken = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *CreateCarrierGatewayInput) SetDryRun(v bool) *CreateCarrierGatewayInput { + s.DryRun = &v + return s +} + +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateCarrierGatewayInput) SetTagSpecifications(v []*TagSpecification) *CreateCarrierGatewayInput { + s.TagSpecifications = v + return s +} + +// SetVpcId sets the VpcId field's value. +func (s *CreateCarrierGatewayInput) SetVpcId(v string) *CreateCarrierGatewayInput { + s.VpcId = &v + return s +} + +type CreateCarrierGatewayOutput struct { + _ struct{} `type:"structure"` + + // Information about the carrier gateway. + CarrierGateway *CarrierGateway `locationName:"carrierGateway" type:"structure"` +} + +// String returns the string representation +func (s CreateCarrierGatewayOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateCarrierGatewayOutput) GoString() string { + return s.String() +} + +// SetCarrierGateway sets the CarrierGateway field's value. +func (s *CreateCarrierGatewayOutput) SetCarrierGateway(v *CarrierGateway) *CreateCarrierGatewayOutput { + s.CarrierGateway = v + return s +} + type CreateClientVpnEndpointInput struct { _ struct{} `type:"structure"` @@ -44999,6 +47008,9 @@ type CreateCustomerGatewayInput struct { // The address must be static. PublicIp *string `locationName:"IpAddress" type:"string"` + // The tags to apply to the customer gateway. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The type of VPN connection that this customer gateway supports (ipsec.1). // // Type is a required field @@ -45061,6 +47073,12 @@ func (s *CreateCustomerGatewayInput) SetPublicIp(v string) *CreateCustomerGatewa return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateCustomerGatewayInput) SetTagSpecifications(v []*TagSpecification) *CreateCustomerGatewayInput { + s.TagSpecifications = v + return s +} + // SetType sets the Type field's value. func (s *CreateCustomerGatewayInput) SetType(v string) *CreateCustomerGatewayInput { s.Type = &v @@ -45226,6 +47244,9 @@ type CreateDhcpOptionsInput struct { // the required permissions, the error response is DryRunOperation. Otherwise, // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` + + // The tags to assign to the DHCP option. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } // String returns the string representation @@ -45263,6 +47284,12 @@ func (s *CreateDhcpOptionsInput) SetDryRun(v bool) *CreateDhcpOptionsInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateDhcpOptionsInput) SetTagSpecifications(v []*TagSpecification) *CreateDhcpOptionsInput { + s.TagSpecifications = v + return s +} + type CreateDhcpOptionsOutput struct { _ struct{} `type:"structure"` @@ -45299,6 +47326,9 @@ type CreateEgressOnlyInternetGatewayInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` + // The tags to assign to the egress-only internet gateway. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The ID of the VPC for which to create the egress-only internet gateway. // // VpcId is a required field @@ -45340,6 +47370,12 @@ func (s *CreateEgressOnlyInternetGatewayInput) SetDryRun(v bool) *CreateEgressOn return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateEgressOnlyInternetGatewayInput) SetTagSpecifications(v []*TagSpecification) *CreateEgressOnlyInternetGatewayInput { + s.TagSpecifications = v + return s +} + // SetVpcId sets the VpcId field's value. func (s *CreateEgressOnlyInternetGatewayInput) SetVpcId(v string) *CreateEgressOnlyInternetGatewayInput { s.VpcId = &v @@ -45783,8 +47819,6 @@ type CreateFlowLogsInput struct { // // Specify the fields using the ${field-id} format, separated by spaces. For // the AWS CLI, use single quotation marks (' ') to surround the parameter value. - // - // Only applicable to flow logs that are published to an Amazon S3 bucket. LogFormat *string `type:"string"` // The name of a new or existing CloudWatch Logs log group where Amazon EC2 @@ -46228,7 +48262,7 @@ type CreateInstanceExportTaskInput struct { _ struct{} `type:"structure"` // A description for the conversion task or the resource being exported. The - // maximum length is 255 bytes. + // maximum length is 255 characters. Description *string `locationName:"description" type:"string"` // The format and location for an instance export task. @@ -46239,6 +48273,9 @@ type CreateInstanceExportTaskInput struct { // InstanceId is a required field InstanceId *string `locationName:"instanceId" type:"string" required:"true"` + // The tags to apply to the instance export task during creation. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The target virtualization environment. TargetEnvironment *string `locationName:"targetEnvironment" type:"string" enum:"ExportEnvironment"` } @@ -46284,6 +48321,12 @@ func (s *CreateInstanceExportTaskInput) SetInstanceId(v string) *CreateInstanceE return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateInstanceExportTaskInput) SetTagSpecifications(v []*TagSpecification) *CreateInstanceExportTaskInput { + s.TagSpecifications = v + return s +} + // SetTargetEnvironment sets the TargetEnvironment field's value. func (s *CreateInstanceExportTaskInput) SetTargetEnvironment(v string) *CreateInstanceExportTaskInput { s.TargetEnvironment = &v @@ -46321,6 +48364,9 @@ type CreateInternetGatewayInput struct { // the required permissions, the error response is DryRunOperation. Otherwise, // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` + + // The tags to assign to the internet gateway. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } // String returns the string representation @@ -46339,6 +48385,12 @@ func (s *CreateInternetGatewayInput) SetDryRun(v bool) *CreateInternetGatewayInp return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateInternetGatewayInput) SetTagSpecifications(v []*TagSpecification) *CreateInternetGatewayInput { + s.TagSpecifications = v + return s +} + type CreateInternetGatewayOutput struct { _ struct{} `type:"structure"` @@ -46590,6 +48642,11 @@ type CreateLaunchTemplateOutput struct { // Information about the launch template. LaunchTemplate *LaunchTemplate `locationName:"launchTemplate" type:"structure"` + + // If the launch template contains parameters or parameter combinations that + // are not valid, an error code and an error message are returned for each issue + // that's found. + Warning *ValidationWarning `locationName:"warning" type:"structure"` } // String returns the string representation @@ -46608,6 +48665,12 @@ func (s *CreateLaunchTemplateOutput) SetLaunchTemplate(v *LaunchTemplate) *Creat return s } +// SetWarning sets the Warning field's value. +func (s *CreateLaunchTemplateOutput) SetWarning(v *ValidationWarning) *CreateLaunchTemplateOutput { + s.Warning = v + return s +} + type CreateLaunchTemplateVersionInput struct { _ struct{} `type:"structure"` @@ -46725,6 +48788,11 @@ type CreateLaunchTemplateVersionOutput struct { // Information about the launch template version. LaunchTemplateVersion *LaunchTemplateVersion `locationName:"launchTemplateVersion" type:"structure"` + + // If the new version of the launch template contains parameters or parameter + // combinations that are not valid, an error code and an error message are returned + // for each issue that's found. + Warning *ValidationWarning `locationName:"warning" type:"structure"` } // String returns the string representation @@ -46743,6 +48811,12 @@ func (s *CreateLaunchTemplateVersionOutput) SetLaunchTemplateVersion(v *LaunchTe return s } +// SetWarning sets the Warning field's value. +func (s *CreateLaunchTemplateVersionOutput) SetWarning(v *ValidationWarning) *CreateLaunchTemplateVersionOutput { + s.Warning = v + return s +} + type CreateLocalGatewayRouteInput struct { _ struct{} `type:"structure"` @@ -46859,6 +48933,9 @@ type CreateLocalGatewayRouteTableVpcAssociationInput struct { // LocalGatewayRouteTableId is a required field LocalGatewayRouteTableId *string `type:"string" required:"true"` + // The tags to assign to the local gateway route table VPC association. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The ID of the VPC. // // VpcId is a required field @@ -46903,6 +48980,12 @@ func (s *CreateLocalGatewayRouteTableVpcAssociationInput) SetLocalGatewayRouteTa return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateLocalGatewayRouteTableVpcAssociationInput) SetTagSpecifications(v []*TagSpecification) *CreateLocalGatewayRouteTableVpcAssociationInput { + s.TagSpecifications = v + return s +} + // SetVpcId sets the VpcId field's value. func (s *CreateLocalGatewayRouteTableVpcAssociationInput) SetVpcId(v string) *CreateLocalGatewayRouteTableVpcAssociationInput { s.VpcId = &v @@ -46932,6 +49015,151 @@ func (s *CreateLocalGatewayRouteTableVpcAssociationOutput) SetLocalGatewayRouteT return s } +type CreateManagedPrefixListInput struct { + _ struct{} `type:"structure"` + + // The IP address type. + // + // Valid Values: IPv4 | IPv6 + // + // AddressFamily is a required field + AddressFamily *string `type:"string" required:"true"` + + // Unique, case-sensitive identifier you provide to ensure the idempotency of + // the request. For more information, see Ensuring Idempotency (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). + // + // Constraints: Up to 255 UTF-8 characters in length. + ClientToken *string `type:"string" idempotencyToken:"true"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // One or more entries for the prefix list. + Entries []*AddPrefixListEntry `locationName:"Entry" type:"list"` + + // The maximum number of entries for the prefix list. + // + // MaxEntries is a required field + MaxEntries *int64 `type:"integer" required:"true"` + + // A name for the prefix list. + // + // Constraints: Up to 255 characters in length. The name cannot start with com.amazonaws. + // + // PrefixListName is a required field + PrefixListName *string `type:"string" required:"true"` + + // The tags to apply to the prefix list during creation. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` +} + +// String returns the string representation +func (s CreateManagedPrefixListInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateManagedPrefixListInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateManagedPrefixListInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateManagedPrefixListInput"} + if s.AddressFamily == nil { + invalidParams.Add(request.NewErrParamRequired("AddressFamily")) + } + if s.MaxEntries == nil { + invalidParams.Add(request.NewErrParamRequired("MaxEntries")) + } + if s.PrefixListName == nil { + invalidParams.Add(request.NewErrParamRequired("PrefixListName")) + } + if s.Entries != nil { + for i, v := range s.Entries { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Entries", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAddressFamily sets the AddressFamily field's value. +func (s *CreateManagedPrefixListInput) SetAddressFamily(v string) *CreateManagedPrefixListInput { + s.AddressFamily = &v + return s +} + +// SetClientToken sets the ClientToken field's value. +func (s *CreateManagedPrefixListInput) SetClientToken(v string) *CreateManagedPrefixListInput { + s.ClientToken = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *CreateManagedPrefixListInput) SetDryRun(v bool) *CreateManagedPrefixListInput { + s.DryRun = &v + return s +} + +// SetEntries sets the Entries field's value. +func (s *CreateManagedPrefixListInput) SetEntries(v []*AddPrefixListEntry) *CreateManagedPrefixListInput { + s.Entries = v + return s +} + +// SetMaxEntries sets the MaxEntries field's value. +func (s *CreateManagedPrefixListInput) SetMaxEntries(v int64) *CreateManagedPrefixListInput { + s.MaxEntries = &v + return s +} + +// SetPrefixListName sets the PrefixListName field's value. +func (s *CreateManagedPrefixListInput) SetPrefixListName(v string) *CreateManagedPrefixListInput { + s.PrefixListName = &v + return s +} + +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateManagedPrefixListInput) SetTagSpecifications(v []*TagSpecification) *CreateManagedPrefixListInput { + s.TagSpecifications = v + return s +} + +type CreateManagedPrefixListOutput struct { + _ struct{} `type:"structure"` + + // Information about the prefix list. + PrefixList *ManagedPrefixList `locationName:"prefixList" type:"structure"` +} + +// String returns the string representation +func (s CreateManagedPrefixListOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateManagedPrefixListOutput) GoString() string { + return s.String() +} + +// SetPrefixList sets the PrefixList field's value. +func (s *CreateManagedPrefixListOutput) SetPrefixList(v *ManagedPrefixList) *CreateManagedPrefixListOutput { + s.PrefixList = v + return s +} + type CreateNatGatewayInput struct { _ struct{} `type:"structure"` @@ -47056,6 +49284,8 @@ type CreateNetworkAclEntryInput struct { _ struct{} `type:"structure"` // The IPv4 network range to allow or deny, in CIDR notation (for example 172.16.0.0/24). + // We modify the specified CIDR block to its canonical form; for example, if + // you specify 100.68.0.18/18, we modify it to 100.68.0.0/18. CidrBlock *string `locationName:"cidrBlock" type:"string"` // Checks whether you have the required permissions for the action, without @@ -47230,6 +49460,9 @@ type CreateNetworkAclInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` + // The tags to assign to the network ACL. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The ID of the VPC. // // VpcId is a required field @@ -47265,6 +49498,12 @@ func (s *CreateNetworkAclInput) SetDryRun(v bool) *CreateNetworkAclInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateNetworkAclInput) SetTagSpecifications(v []*TagSpecification) *CreateNetworkAclInput { + s.TagSpecifications = v + return s +} + // SetVpcId sets the VpcId field's value. func (s *CreateNetworkAclInput) SetVpcId(v string) *CreateNetworkAclInput { s.VpcId = &v @@ -47351,6 +49590,9 @@ type CreateNetworkInterfaceInput struct { // // SubnetId is a required field SubnetId *string `locationName:"subnetId" type:"string" required:"true"` + + // The tags to apply to the new network interface. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } // String returns the string representation @@ -47436,6 +49678,12 @@ func (s *CreateNetworkInterfaceInput) SetSubnetId(v string) *CreateNetworkInterf return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateNetworkInterfaceInput) SetTagSpecifications(v []*TagSpecification) *CreateNetworkInterfaceInput { + s.TagSpecifications = v + return s +} + // Contains the output of CreateNetworkInterface. type CreateNetworkInterfaceOutput struct { _ struct{} `type:"structure"` @@ -47769,14 +50017,25 @@ func (s *CreateReservedInstancesListingOutput) SetReservedInstancesListings(v [] type CreateRouteInput struct { _ struct{} `type:"structure"` + // The ID of the carrier gateway. + // + // You can only use this option when the VPC contains a subnet which is associated + // with a Wavelength Zone. + CarrierGatewayId *string `type:"string"` + // The IPv4 CIDR address block used for the destination match. Routing decisions - // are based on the most specific match. + // are based on the most specific match. We modify the specified CIDR block + // to its canonical form; for example, if you specify 100.68.0.18/18, we modify + // it to 100.68.0.0/18. DestinationCidrBlock *string `locationName:"destinationCidrBlock" type:"string"` // The IPv6 CIDR block used for the destination match. Routing decisions are // based on the most specific match. DestinationIpv6CidrBlock *string `locationName:"destinationIpv6CidrBlock" type:"string"` + // The ID of a prefix list used for the destination match. + DestinationPrefixListId *string `type:"string"` + // Checks whether you have the required permissions for the action, without // actually making the request, and provides an error response. If you have // the required permissions, the error response is DryRunOperation. Otherwise, @@ -47838,6 +50097,12 @@ func (s *CreateRouteInput) Validate() error { return nil } +// SetCarrierGatewayId sets the CarrierGatewayId field's value. +func (s *CreateRouteInput) SetCarrierGatewayId(v string) *CreateRouteInput { + s.CarrierGatewayId = &v + return s +} + // SetDestinationCidrBlock sets the DestinationCidrBlock field's value. func (s *CreateRouteInput) SetDestinationCidrBlock(v string) *CreateRouteInput { s.DestinationCidrBlock = &v @@ -47850,6 +50115,12 @@ func (s *CreateRouteInput) SetDestinationIpv6CidrBlock(v string) *CreateRouteInp return s } +// SetDestinationPrefixListId sets the DestinationPrefixListId field's value. +func (s *CreateRouteInput) SetDestinationPrefixListId(v string) *CreateRouteInput { + s.DestinationPrefixListId = &v + return s +} + // SetDryRun sets the DryRun field's value. func (s *CreateRouteInput) SetDryRun(v bool) *CreateRouteInput { s.DryRun = &v @@ -47942,6 +50213,9 @@ type CreateRouteTableInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` + // The tags to assign to the route table. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The ID of the VPC. // // VpcId is a required field @@ -47977,6 +50251,12 @@ func (s *CreateRouteTableInput) SetDryRun(v bool) *CreateRouteTableInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateRouteTableInput) SetTagSpecifications(v []*TagSpecification) *CreateRouteTableInput { + s.TagSpecifications = v + return s +} + // SetVpcId sets the VpcId field's value. func (s *CreateRouteTableInput) SetVpcId(v string) *CreateRouteTableInput { s.VpcId = &v @@ -48037,6 +50317,9 @@ type CreateSecurityGroupInput struct { // GroupName is a required field GroupName *string `type:"string" required:"true"` + // The tags to assign to the security group. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // [EC2-VPC] The ID of the VPC. Required for EC2-VPC. VpcId *string `type:"string"` } @@ -48085,6 +50368,12 @@ func (s *CreateSecurityGroupInput) SetGroupName(v string) *CreateSecurityGroupIn return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateSecurityGroupInput) SetTagSpecifications(v []*TagSpecification) *CreateSecurityGroupInput { + s.TagSpecifications = v + return s +} + // SetVpcId sets the VpcId field's value. func (s *CreateSecurityGroupInput) SetVpcId(v string) *CreateSecurityGroupInput { s.VpcId = &v @@ -48096,6 +50385,9 @@ type CreateSecurityGroupOutput struct { // The ID of the security group. GroupId *string `locationName:"groupId" type:"string"` + + // The tags assigned to the security group. + Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` } // String returns the string representation @@ -48114,6 +50406,12 @@ func (s *CreateSecurityGroupOutput) SetGroupId(v string) *CreateSecurityGroupOut return s } +// SetTags sets the Tags field's value. +func (s *CreateSecurityGroupOutput) SetTags(v []*Tag) *CreateSecurityGroupOutput { + s.Tags = v + return s +} + type CreateSnapshotInput struct { _ struct{} `type:"structure"` @@ -48378,12 +50676,17 @@ type CreateSubnetInput struct { // for example us-west-2-lax-1a. For information about the Regions that support // Local Zones, see Available Regions (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html#concepts-available-regions) // in the Amazon Elastic Compute Cloud User Guide. + // + // To create a subnet in an Outpost, set this value to the Availability Zone + // for the Outpost and specify the Outpost ARN. AvailabilityZone *string `type:"string"` // The AZ ID or the Local Zone ID of the subnet. AvailabilityZoneId *string `type:"string"` // The IPv4 network range for the subnet, in CIDR notation. For example, 10.0.0.0/24. + // We modify the specified CIDR block to its canonical form; for example, if + // you specify 100.68.0.18/18, we modify it to 100.68.0.0/18. // // CidrBlock is a required field CidrBlock *string `type:"string" required:"true"` @@ -48398,9 +50701,13 @@ type CreateSubnetInput struct { // must use a /64 prefix length. Ipv6CidrBlock *string `type:"string"` - // The Amazon Resource Name (ARN) of the Outpost. + // The Amazon Resource Name (ARN) of the Outpost. If you specify an Outpost + // ARN, you must also specify the Availability Zone of the Outpost subnet. OutpostArn *string `type:"string"` + // The tags to assign to the subnet. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The ID of the VPC. // // VpcId is a required field @@ -48469,6 +50776,12 @@ func (s *CreateSubnetInput) SetOutpostArn(v string) *CreateSubnetInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateSubnetInput) SetTagSpecifications(v []*TagSpecification) *CreateSubnetInput { + s.TagSpecifications = v + return s +} + // SetVpcId sets the VpcId field's value. func (s *CreateSubnetInput) SetVpcId(v string) *CreateSubnetInput { s.VpcId = &v @@ -49445,6 +51758,111 @@ func (s *CreateTransitGatewayPeeringAttachmentOutput) SetTransitGatewayPeeringAt return s } +type CreateTransitGatewayPrefixListReferenceInput struct { + _ struct{} `type:"structure"` + + // Indicates whether to drop traffic that matches this route. + Blackhole *bool `type:"boolean"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The ID of the prefix list that is used for destination matches. + // + // PrefixListId is a required field + PrefixListId *string `type:"string" required:"true"` + + // The ID of the attachment to which traffic is routed. + TransitGatewayAttachmentId *string `type:"string"` + + // The ID of the transit gateway route table. + // + // TransitGatewayRouteTableId is a required field + TransitGatewayRouteTableId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s CreateTransitGatewayPrefixListReferenceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateTransitGatewayPrefixListReferenceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *CreateTransitGatewayPrefixListReferenceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "CreateTransitGatewayPrefixListReferenceInput"} + if s.PrefixListId == nil { + invalidParams.Add(request.NewErrParamRequired("PrefixListId")) + } + if s.TransitGatewayRouteTableId == nil { + invalidParams.Add(request.NewErrParamRequired("TransitGatewayRouteTableId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBlackhole sets the Blackhole field's value. +func (s *CreateTransitGatewayPrefixListReferenceInput) SetBlackhole(v bool) *CreateTransitGatewayPrefixListReferenceInput { + s.Blackhole = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *CreateTransitGatewayPrefixListReferenceInput) SetDryRun(v bool) *CreateTransitGatewayPrefixListReferenceInput { + s.DryRun = &v + return s +} + +// SetPrefixListId sets the PrefixListId field's value. +func (s *CreateTransitGatewayPrefixListReferenceInput) SetPrefixListId(v string) *CreateTransitGatewayPrefixListReferenceInput { + s.PrefixListId = &v + return s +} + +// SetTransitGatewayAttachmentId sets the TransitGatewayAttachmentId field's value. +func (s *CreateTransitGatewayPrefixListReferenceInput) SetTransitGatewayAttachmentId(v string) *CreateTransitGatewayPrefixListReferenceInput { + s.TransitGatewayAttachmentId = &v + return s +} + +// SetTransitGatewayRouteTableId sets the TransitGatewayRouteTableId field's value. +func (s *CreateTransitGatewayPrefixListReferenceInput) SetTransitGatewayRouteTableId(v string) *CreateTransitGatewayPrefixListReferenceInput { + s.TransitGatewayRouteTableId = &v + return s +} + +type CreateTransitGatewayPrefixListReferenceOutput struct { + _ struct{} `type:"structure"` + + // Information about the prefix list reference. + TransitGatewayPrefixListReference *TransitGatewayPrefixListReference `locationName:"transitGatewayPrefixListReference" type:"structure"` +} + +// String returns the string representation +func (s CreateTransitGatewayPrefixListReferenceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s CreateTransitGatewayPrefixListReferenceOutput) GoString() string { + return s.String() +} + +// SetTransitGatewayPrefixListReference sets the TransitGatewayPrefixListReference field's value. +func (s *CreateTransitGatewayPrefixListReferenceOutput) SetTransitGatewayPrefixListReference(v *TransitGatewayPrefixListReference) *CreateTransitGatewayPrefixListReferenceOutput { + s.TransitGatewayPrefixListReference = v + return s +} + type CreateTransitGatewayRouteInput struct { _ struct{} `type:"structure"` @@ -49805,22 +52223,22 @@ type CreateVolumeInput struct { // Specifies whether the volume should be encrypted. The effect of setting the // encryption state to true depends on the volume origin (new or from a snapshot), // starting encryption state, ownership, and whether encryption by default is - // enabled. For more information, see Encryption by Default (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-by-default) + // enabled. For more information, see Encryption by default (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#encryption-by-default) // in the Amazon Elastic Compute Cloud User Guide. // // Encrypted Amazon EBS volumes must be attached to instances that support Amazon - // EBS encryption. For more information, see Supported Instance Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances). + // EBS encryption. For more information, see Supported instance types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances). Encrypted *bool `locationName:"encrypted" type:"boolean"` - // The number of I/O operations per second (IOPS) to provision for the volume, - // with a maximum ratio of 50 IOPS/GiB. Range is 100 to 64,000 IOPS for volumes - // in most Regions. Maximum IOPS of 64,000 is guaranteed only on Nitro-based - // instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). + // The number of I/O operations per second (IOPS) to provision for an io1 or + // io2 volume, with a maximum ratio of 50 IOPS/GiB for io1, and 500 IOPS/GiB + // for io2. Range is 100 to 64,000 IOPS for volumes in most Regions. Maximum + // IOPS of 64,000 is guaranteed only on Nitro-based instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). // Other instance families guarantee performance up to 32,000 IOPS. For more - // information, see Amazon EBS Volume Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) + // information, see Amazon EBS volume types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) // in the Amazon Elastic Compute Cloud User Guide. // - // This parameter is valid only for Provisioned IOPS SSD (io1) volumes. + // This parameter is valid only for Provisioned IOPS SSD (io1 and io2) volumes. Iops *int64 `type:"integer"` // The identifier of the AWS Key Management Service (AWS KMS) customer master @@ -49856,9 +52274,9 @@ type CreateVolumeInput struct { // The size of the volume, in GiBs. You must specify either a snapshot ID or // a volume size. // - // Constraints: 1-16,384 for gp2, 4-16,384 for io1, 500-16,384 for st1, 500-16,384 - // for sc1, and 1-1,024 for standard. If you specify a snapshot, the volume - // size must be equal to or larger than the snapshot size. + // Constraints: 1-16,384 for gp2, 4-16,384 for io1 and io2, 500-16,384 for st1, + // 500-16,384 for sc1, and 1-1,024 for standard. If you specify a snapshot, + // the volume size must be equal to or larger than the snapshot size. // // Default: If you're creating the volume from a snapshot and don't specify // a volume size, the default is the snapshot size. @@ -49871,9 +52289,9 @@ type CreateVolumeInput struct { // The tags to apply to the volume during creation. TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` - // The volume type. This can be gp2 for General Purpose SSD, io1 for Provisioned - // IOPS SSD, st1 for Throughput Optimized HDD, sc1 for Cold HDD, or standard - // for Magnetic volumes. + // The volume type. This can be gp2 for General Purpose SSD, io1 or io2 for + // Provisioned IOPS SSD, st1 for Throughput Optimized HDD, sc1 for Cold HDD, + // or standard for Magnetic volumes. // // Default: gp2 VolumeType *string `type:"string" enum:"VolumeType"` @@ -50483,6 +52901,8 @@ type CreateVpcInput struct { AmazonProvidedIpv6CidrBlock *bool `locationName:"amazonProvidedIpv6CidrBlock" type:"boolean"` // The IPv4 network range for the VPC, in CIDR notation. For example, 10.0.0.0/16. + // We modify the specified CIDR block to its canonical form; for example, if + // you specify 100.68.0.18/18, we modify it to 100.68.0.0/18. // // CidrBlock is a required field CidrBlock *string `type:"string" required:"true"` @@ -50519,6 +52939,9 @@ type CreateVpcInput struct { // The ID of an IPv6 address pool from which to allocate the IPv6 CIDR block. Ipv6Pool *string `type:"string"` + + // The tags to assign to the VPC. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } // String returns the string representation @@ -50586,6 +53009,12 @@ func (s *CreateVpcInput) SetIpv6Pool(v string) *CreateVpcInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateVpcInput) SetTagSpecifications(v []*TagSpecification) *CreateVpcInput { + s.TagSpecifications = v + return s +} + type CreateVpcOutput struct { _ struct{} `type:"structure"` @@ -50633,6 +53062,9 @@ type CreateVpcPeeringConnectionInput struct { // You must specify this parameter in the request. PeerVpcId *string `locationName:"peerVpcId" type:"string"` + // The tags to assign to the peering connection. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The ID of the requester VPC. You must specify this parameter in the request. VpcId *string `locationName:"vpcId" type:"string"` } @@ -50671,6 +53103,12 @@ func (s *CreateVpcPeeringConnectionInput) SetPeerVpcId(v string) *CreateVpcPeeri return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateVpcPeeringConnectionInput) SetTagSpecifications(v []*TagSpecification) *CreateVpcPeeringConnectionInput { + s.TagSpecifications = v + return s +} + // SetVpcId sets the VpcId field's value. func (s *CreateVpcPeeringConnectionInput) SetVpcId(v string) *CreateVpcPeeringConnectionInput { s.VpcId = &v @@ -50718,6 +53156,9 @@ type CreateVpnConnectionInput struct { // The options for the VPN connection. Options *VpnConnectionOptionsSpecification `locationName:"options" type:"structure"` + // The tags to apply to the VPN connection. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The ID of the transit gateway. If you specify a transit gateway, you cannot // specify a virtual private gateway. TransitGatewayId *string `type:"string"` @@ -50776,6 +53217,12 @@ func (s *CreateVpnConnectionInput) SetOptions(v *VpnConnectionOptionsSpecificati return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateVpnConnectionInput) SetTagSpecifications(v []*TagSpecification) *CreateVpnConnectionInput { + s.TagSpecifications = v + return s +} + // SetTransitGatewayId sets the TransitGatewayId field's value. func (s *CreateVpnConnectionInput) SetTransitGatewayId(v string) *CreateVpnConnectionInput { s.TransitGatewayId = &v @@ -50905,6 +53352,9 @@ type CreateVpnGatewayInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` + // The tags to apply to the virtual private gateway. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The type of VPN connection this virtual private gateway supports. // // Type is a required field @@ -50952,6 +53402,12 @@ func (s *CreateVpnGatewayInput) SetDryRun(v bool) *CreateVpnGatewayInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *CreateVpnGatewayInput) SetTagSpecifications(v []*TagSpecification) *CreateVpnGatewayInput { + s.TagSpecifications = v + return s +} + // SetType sets the Type field's value. func (s *CreateVpnGatewayInput) SetType(v string) *CreateVpnGatewayInput { s.Type = &v @@ -50982,12 +53438,12 @@ func (s *CreateVpnGatewayOutput) SetVpnGateway(v *VpnGateway) *CreateVpnGatewayO return s } -// Describes the credit option for CPU usage of a T2 or T3 instance. +// Describes the credit option for CPU usage of a T2, T3, or T3a instance. type CreditSpecification struct { _ struct{} `type:"structure"` - // The credit option for CPU usage of a T2 or T3 instance. Valid values are - // standard and unlimited. + // The credit option for CPU usage of a T2, T3, or T3a instance. Valid values + // are standard and unlimited. CpuCredits *string `locationName:"cpuCredits" type:"string"` } @@ -51007,12 +53463,12 @@ func (s *CreditSpecification) SetCpuCredits(v string) *CreditSpecification { return s } -// The credit option for CPU usage of a T2 or T3 instance. +// The credit option for CPU usage of a T2, T3, or T3a instance. type CreditSpecificationRequest struct { _ struct{} `type:"structure"` - // The credit option for CPU usage of a T2 or T3 instance. Valid values are - // standard and unlimited. + // The credit option for CPU usage of a T2, T3, or T3a instance. Valid values + // are standard and unlimited. // // CpuCredits is a required field CpuCredits *string `type:"string" required:"true"` @@ -51136,6 +53592,79 @@ func (s *CustomerGateway) SetType(v string) *CustomerGateway { return s } +type DeleteCarrierGatewayInput struct { + _ struct{} `type:"structure"` + + // The ID of the carrier gateway. + // + // CarrierGatewayId is a required field + CarrierGatewayId *string `type:"string" required:"true"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` +} + +// String returns the string representation +func (s DeleteCarrierGatewayInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteCarrierGatewayInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteCarrierGatewayInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteCarrierGatewayInput"} + if s.CarrierGatewayId == nil { + invalidParams.Add(request.NewErrParamRequired("CarrierGatewayId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCarrierGatewayId sets the CarrierGatewayId field's value. +func (s *DeleteCarrierGatewayInput) SetCarrierGatewayId(v string) *DeleteCarrierGatewayInput { + s.CarrierGatewayId = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *DeleteCarrierGatewayInput) SetDryRun(v bool) *DeleteCarrierGatewayInput { + s.DryRun = &v + return s +} + +type DeleteCarrierGatewayOutput struct { + _ struct{} `type:"structure"` + + // Information about the carrier gateway. + CarrierGateway *CarrierGateway `locationName:"carrierGateway" type:"structure"` +} + +// String returns the string representation +func (s DeleteCarrierGatewayOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteCarrierGatewayOutput) GoString() string { + return s.String() +} + +// SetCarrierGateway sets the CarrierGateway field's value. +func (s *DeleteCarrierGatewayOutput) SetCarrierGateway(v *CarrierGateway) *DeleteCarrierGatewayOutput { + s.CarrierGateway = v + return s +} + type DeleteClientVpnEndpointInput struct { _ struct{} `type:"structure"` @@ -52422,6 +54951,79 @@ func (s *DeleteLocalGatewayRouteTableVpcAssociationOutput) SetLocalGatewayRouteT return s } +type DeleteManagedPrefixListInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The ID of the prefix list. + // + // PrefixListId is a required field + PrefixListId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteManagedPrefixListInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteManagedPrefixListInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteManagedPrefixListInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteManagedPrefixListInput"} + if s.PrefixListId == nil { + invalidParams.Add(request.NewErrParamRequired("PrefixListId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *DeleteManagedPrefixListInput) SetDryRun(v bool) *DeleteManagedPrefixListInput { + s.DryRun = &v + return s +} + +// SetPrefixListId sets the PrefixListId field's value. +func (s *DeleteManagedPrefixListInput) SetPrefixListId(v string) *DeleteManagedPrefixListInput { + s.PrefixListId = &v + return s +} + +type DeleteManagedPrefixListOutput struct { + _ struct{} `type:"structure"` + + // Information about the prefix list. + PrefixList *ManagedPrefixList `locationName:"prefixList" type:"structure"` +} + +// String returns the string representation +func (s DeleteManagedPrefixListOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteManagedPrefixListOutput) GoString() string { + return s.String() +} + +// SetPrefixList sets the PrefixList field's value. +func (s *DeleteManagedPrefixListOutput) SetPrefixList(v *ManagedPrefixList) *DeleteManagedPrefixListOutput { + s.PrefixList = v + return s +} + type DeleteNatGatewayInput struct { _ struct{} `type:"structure"` @@ -52995,6 +55597,9 @@ type DeleteRouteInput struct { // for the route exactly. DestinationIpv6CidrBlock *string `locationName:"destinationIpv6CidrBlock" type:"string"` + // The ID of the prefix list for the route. + DestinationPrefixListId *string `type:"string"` + // Checks whether you have the required permissions for the action, without // actually making the request, and provides an error response. If you have // the required permissions, the error response is DryRunOperation. Otherwise, @@ -53042,6 +55647,12 @@ func (s *DeleteRouteInput) SetDestinationIpv6CidrBlock(v string) *DeleteRouteInp return s } +// SetDestinationPrefixListId sets the DestinationPrefixListId field's value. +func (s *DeleteRouteInput) SetDestinationPrefixListId(v string) *DeleteRouteInput { + s.DestinationPrefixListId = &v + return s +} + // SetDryRun sets the DryRun field's value. func (s *DeleteRouteInput) SetDryRun(v bool) *DeleteRouteInput { s.DryRun = &v @@ -53954,6 +56565,93 @@ func (s *DeleteTransitGatewayPeeringAttachmentOutput) SetTransitGatewayPeeringAt return s } +type DeleteTransitGatewayPrefixListReferenceInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The ID of the prefix list. + // + // PrefixListId is a required field + PrefixListId *string `type:"string" required:"true"` + + // The ID of the route table. + // + // TransitGatewayRouteTableId is a required field + TransitGatewayRouteTableId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s DeleteTransitGatewayPrefixListReferenceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteTransitGatewayPrefixListReferenceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DeleteTransitGatewayPrefixListReferenceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DeleteTransitGatewayPrefixListReferenceInput"} + if s.PrefixListId == nil { + invalidParams.Add(request.NewErrParamRequired("PrefixListId")) + } + if s.TransitGatewayRouteTableId == nil { + invalidParams.Add(request.NewErrParamRequired("TransitGatewayRouteTableId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *DeleteTransitGatewayPrefixListReferenceInput) SetDryRun(v bool) *DeleteTransitGatewayPrefixListReferenceInput { + s.DryRun = &v + return s +} + +// SetPrefixListId sets the PrefixListId field's value. +func (s *DeleteTransitGatewayPrefixListReferenceInput) SetPrefixListId(v string) *DeleteTransitGatewayPrefixListReferenceInput { + s.PrefixListId = &v + return s +} + +// SetTransitGatewayRouteTableId sets the TransitGatewayRouteTableId field's value. +func (s *DeleteTransitGatewayPrefixListReferenceInput) SetTransitGatewayRouteTableId(v string) *DeleteTransitGatewayPrefixListReferenceInput { + s.TransitGatewayRouteTableId = &v + return s +} + +type DeleteTransitGatewayPrefixListReferenceOutput struct { + _ struct{} `type:"structure"` + + // Information about the deleted prefix list reference. + TransitGatewayPrefixListReference *TransitGatewayPrefixListReference `locationName:"transitGatewayPrefixListReference" type:"structure"` +} + +// String returns the string representation +func (s DeleteTransitGatewayPrefixListReferenceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DeleteTransitGatewayPrefixListReferenceOutput) GoString() string { + return s.String() +} + +// SetTransitGatewayPrefixListReference sets the TransitGatewayPrefixListReference field's value. +func (s *DeleteTransitGatewayPrefixListReferenceOutput) SetTransitGatewayPrefixListReference(v *TransitGatewayPrefixListReference) *DeleteTransitGatewayPrefixListReferenceOutput { + s.TransitGatewayPrefixListReference = v + return s +} + type DeleteTransitGatewayRouteInput struct { _ struct{} `type:"structure"` @@ -55274,7 +57972,8 @@ type DescribeAddressesInput struct { // * instance-id - The ID of the instance the address is associated with, // if any. // - // * network-border-group - The location from where the IP address is advertised. + // * network-border-group - A unique set of Availability Zones, Local Zones, + // or Wavelength Zones from where AWS advertises IP addresses. // // * network-interface-id - [EC2-VPC] The ID of the network interface that // the address is associated with, if any. @@ -55284,7 +57983,7 @@ type DescribeAddressesInput struct { // * private-ip-address - [EC2-VPC] The private IP address associated with // the Elastic IP address. // - // * public-ip - The Elastic IP address. + // * public-ip - The Elastic IP address, or the carrier IP address. // // * tag: - The key/value combination of a tag assigned to the resource. // Use the tag key in the filter name and the tag value as the filter value. @@ -55423,8 +58122,8 @@ func (s *DescribeAggregateIdFormatOutput) SetUseLongIdsAggregated(v bool) *Descr type DescribeAvailabilityZonesInput struct { _ struct{} `type:"structure"` - // Include all Availability Zones and Local Zones regardless of your opt in - // status. + // Include all Availability Zones, Local Zones, and Wavelength Zones regardless + // of your opt-in status. // // If you do not use this parameter, the results include only the zones for // the Regions where you have chosen the option to opt in. @@ -55440,29 +58139,41 @@ type DescribeAvailabilityZonesInput struct { // // * group-name - For Availability Zones, use the Region name. For Local // Zones, use the name of the group associated with the Local Zone (for example, - // us-west-2-lax-1). + // us-west-2-lax-1) For Wavelength Zones, use the name of the group associated + // with the Wavelength Zone (for example, us-east-1-wl1-bos-wlz-1). // - // * message - The Availability Zone or Local Zone message. + // * message - The Zone message. // - // * opt-in-status - The opt in status (opted-in, and not-opted-in | opt-in-not-required). + // * opt-in-status - The opt-in status (opted-in, and not-opted-in | opt-in-not-required). // - // * region-name - The name of the Region for the Availability Zone or Local - // Zone (for example, us-east-1). + // * parent-zoneID - The ID of the zone that handles some of the Local Zone + // and Wavelength Zone control plane operations, such as API calls. // - // * state - The state of the Availability Zone or Local Zone (available - // | information | impaired | unavailable). + // * parent-zoneName - The ID of the zone that handles some of the Local + // Zone and Wavelength Zone control plane operations, such as API calls. // - // * zone-id - The ID of the Availability Zone (for example, use1-az1) or - // the Local Zone (for example, use usw2-lax1-az1). + // * region-name - The name of the Region for the Zone (for example, us-east-1). // - // * zone-name - The name of the Availability Zone (for example, us-east-1a) - // or the Local Zone (for example, use us-west-2-lax-1a). + // * state - The state of the Availability Zone, the Local Zone, or the Wavelength + // Zone (available | information | impaired | unavailable). + // + // * zone-id - The ID of the Availability Zone (for example, use1-az1), the + // Local Zone (for example, usw2-lax1-az1), or the Wavelength Zone (for example, + // us-east-1-wl1-bos-wlz-1). + // + // * zone-type - The type of zone, for example, local-zone. + // + // * zone-name - The name of the Availability Zone (for example, us-east-1a), + // the Local Zone (for example, us-west-2-lax-1a), or the Wavelength Zone + // (for example, us-east-1-wl1-bos-wlz-1). + // + // * zone-type - The type of zone, for example, local-zone. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` - // The IDs of the Availability Zones and Local Zones. + // The IDs of the Availability Zones, Local Zones, and Wavelength Zones. ZoneIds []*string `locationName:"ZoneId" locationNameList:"ZoneId" type:"list"` - // The names of the Availability Zones and Local Zones. + // The names of the Availability Zones, Local Zones, and Wavelength Zones. ZoneNames []*string `locationName:"ZoneName" locationNameList:"ZoneName" type:"list"` } @@ -55509,7 +58220,7 @@ func (s *DescribeAvailabilityZonesInput) SetZoneNames(v []*string) *DescribeAvai type DescribeAvailabilityZonesOutput struct { _ struct{} `type:"structure"` - // Information about the Availability Zones and Local Zones. + // Information about the Availability Zones, Local Zones, and Wavelength Zones. AvailabilityZones []*AvailabilityZone `locationName:"availabilityZoneInfo" locationNameList:"item" type:"list"` } @@ -55784,10 +58495,11 @@ type DescribeCapacityReservationsInput struct { // The maximum number of results to return for the request in a single page. // The remaining results can be seen by sending another request with the returned - // nextToken value. + // nextToken value. This value can be between 5 and 500. If maxResults is given + // a larger value than 500, you receive an error. MaxResults *int64 `min:"1" type:"integer"` - // The token to retrieve the next page of results. + // The token to use to retrieve the next page of results. NextToken *string `type:"string"` } @@ -55877,6 +58589,134 @@ func (s *DescribeCapacityReservationsOutput) SetNextToken(v string) *DescribeCap return s } +type DescribeCarrierGatewaysInput struct { + _ struct{} `type:"structure"` + + // One or more carrier gateway IDs. + CarrierGatewayIds []*string `locationName:"CarrierGatewayId" type:"list"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // One or more filters. + // + // * carrier-gateway-id - The ID of the carrier gateway. + // + // * state - The state of the carrier gateway (pending | failed | available + // | deleting | deleted). + // + // * owner-id - The AWS account ID of the owner of the carrier gateway. + // + // * tag: - The key/value combination of a tag assigned to the resource. + // Use the tag key in the filter name and the tag value as the filter value. + // For example, to find all resources that have a tag with the key Owner + // and the value TeamA, specify tag:Owner for the filter name and TeamA for + // the filter value. + // + // * tag-key - The key of a tag assigned to the resource. Use this filter + // to find all resources assigned a tag with a specific key, regardless of + // the tag value. + // + // * vpc-id - The ID of the VPC associated with the carrier gateway. + Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` + + // The maximum number of results to return with a single call. To retrieve the + // remaining results, make another call with the returned nextToken value. + MaxResults *int64 `min:"5" type:"integer"` + + // The token for the next page of results. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s DescribeCarrierGatewaysInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeCarrierGatewaysInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeCarrierGatewaysInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeCarrierGatewaysInput"} + if s.MaxResults != nil && *s.MaxResults < 5 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 5)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCarrierGatewayIds sets the CarrierGatewayIds field's value. +func (s *DescribeCarrierGatewaysInput) SetCarrierGatewayIds(v []*string) *DescribeCarrierGatewaysInput { + s.CarrierGatewayIds = v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *DescribeCarrierGatewaysInput) SetDryRun(v bool) *DescribeCarrierGatewaysInput { + s.DryRun = &v + return s +} + +// SetFilters sets the Filters field's value. +func (s *DescribeCarrierGatewaysInput) SetFilters(v []*Filter) *DescribeCarrierGatewaysInput { + s.Filters = v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeCarrierGatewaysInput) SetMaxResults(v int64) *DescribeCarrierGatewaysInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeCarrierGatewaysInput) SetNextToken(v string) *DescribeCarrierGatewaysInput { + s.NextToken = &v + return s +} + +type DescribeCarrierGatewaysOutput struct { + _ struct{} `type:"structure"` + + // Information about the carrier gateway. + CarrierGateways []*CarrierGateway `locationName:"carrierGatewaySet" locationNameList:"item" type:"list"` + + // The token to use to retrieve the next page of results. This value is null + // when there are no more results to return. + NextToken *string `locationName:"nextToken" type:"string"` +} + +// String returns the string representation +func (s DescribeCarrierGatewaysOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeCarrierGatewaysOutput) GoString() string { + return s.String() +} + +// SetCarrierGateways sets the CarrierGateways field's value. +func (s *DescribeCarrierGatewaysOutput) SetCarrierGateways(v []*CarrierGateway) *DescribeCarrierGatewaysOutput { + s.CarrierGateways = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeCarrierGatewaysOutput) SetNextToken(v string) *DescribeCarrierGatewaysOutput { + s.NextToken = &v + return s +} + type DescribeClassicLinkInstancesInput struct { _ struct{} `type:"structure"` @@ -57450,10 +60290,11 @@ type DescribeFastSnapshotRestoreSuccessItem struct { // The time at which fast snapshot restores entered the optimizing state. OptimizingTime *time.Time `locationName:"optimizingTime" type:"timestamp"` - // The alias of the snapshot owner. + // The AWS owner alias that enabled fast snapshot restores on the snapshot. + // This is intended for future use. OwnerAlias *string `locationName:"ownerAlias" type:"string"` - // The ID of the AWS account that owns the snapshot. + // The ID of the AWS account that enabled fast snapshot restores on the snapshot. OwnerId *string `locationName:"ownerId" type:"string"` // The ID of the snapshot. @@ -57561,7 +60402,8 @@ type DescribeFastSnapshotRestoresInput struct { // // * availability-zone: The Availability Zone of the snapshot. // - // * owner-id: The ID of the AWS account that owns the snapshot. + // * owner-id: The ID of the AWS account that enabled fast snapshot restore + // on the snapshot. // // * snapshot-id: The ID of the snapshot. // @@ -59267,7 +62109,7 @@ type DescribeImagesInput struct { // in GiB. // // * block-device-mapping.volume-type - The volume type of the EBS volume - // (gp2 | io1 | st1 | sc1 | standard). + // (gp2 | io1 | io2 | st1 | sc1 | standard). // // * block-device-mapping.encrypted - A Boolean that indicates whether the // EBS volume is encrypted. @@ -59291,11 +62133,13 @@ type DescribeImagesInput struct { // // * name - The name of the AMI (provided during image creation). // - // * owner-alias - String value from an Amazon-maintained list (amazon | - // aws-marketplace | microsoft) of snapshot owners. Not to be confused with - // the user-configured AWS account alias, which is set from the IAM console. + // * owner-alias - The owner alias, from an Amazon-maintained list (amazon + // | aws-marketplace). This is not the user-configured AWS account alias + // set using the IAM console. We recommend that you use the related parameter + // instead of this filter. // - // * owner-id - The AWS account ID of the image owner. + // * owner-id - The AWS account ID of the owner. We recommend that you use + // the related parameter instead of this filter. // // * platform - The platform. To only list Windows-based AMIs, use windows. // @@ -59337,10 +62181,10 @@ type DescribeImagesInput struct { // Default: Describes all images available to you. ImageIds []*string `locationName:"ImageId" locationNameList:"ImageId" type:"list"` - // Filters the images by the owner. Specify an AWS account ID, self (owner is - // the sender of the request), or an AWS owner alias (valid values are amazon - // | aws-marketplace | microsoft). Omitting this option returns all images for - // which you have launch permissions, regardless of ownership. + // Scopes the results to images with the specified owners. You can specify a + // combination of AWS account IDs, self, amazon, and aws-marketplace. If you + // omit this parameter, the results include all images for which you have launch + // permissions, regardless of ownership. Owners []*string `locationName:"Owner" locationNameList:"Owner" type:"list"` } @@ -60281,12 +63125,33 @@ type DescribeInstanceTypesInput struct { // * current-generation - Indicates whether this instance type is the latest // generation instance type of an instance family. (true | false) // + // * ebs-info.ebs-optimized-info.baseline-bandwidth-in-mbps - The baseline + // bandwidth performance for an EBS-optimized instance type, in Mbps. + // + // * ebs-info.ebs-optimized-info.baseline-throughput-in-mbps - The baseline + // throughput performance for an EBS-optimized instance type, in MBps. + // + // * ebs-info.ebs-optimized-info.baseline-iops - The baseline input/output + // storage operations per second for an EBS-optimized instance type. + // + // * ebs-info.ebs-optimized-info.maximum-bandwidth-in-mbps - The maximum + // bandwidth performance for an EBS-optimized instance type, in Mbps. + // + // * ebs-info.ebs-optimized-info.maximum-throughput-in-mbps - The maximum + // throughput performance for an EBS-optimized instance type, in MBps. + // + // * ebs-info.ebs-optimized-info.maximum-iops - The maximum input/output + // storage operations per second for an EBS-optimized instance type. + // // * ebs-info.ebs-optimized-support - Indicates whether the instance type // is EBS-optimized. (supported | unsupported | default) // // * ebs-info.encryption-support - Indicates whether EBS encryption is supported. // (supported | unsupported) // + // * ebs-info.nvme-support - Indicates whether non-volatile memory express + // (NVMe) is supported or required. (required | supported | unsupported) + // // * free-tier-eligible - Indicates whether the instance type is eligible // to use in the free tier. (true | false) // @@ -60314,6 +63179,9 @@ type DescribeInstanceTypesInput struct { // * network-info.ena-support - Indicates whether Elastic Network Adapter // (ENA) is supported or required. (required | supported | unsupported) // + // * network-info.efa-supported - Indicates whether the instance type supports + // Elastic Fabric Adapter (EFA). (true | false) + // // * network-info.ipv4-addresses-per-interface - The maximum number of private // IPv4 addresses per network interface. // @@ -61160,12 +64028,16 @@ type DescribeLaunchTemplateVersionsInput struct { // * ram-disk-id - The RAM disk ID. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` - // The ID of the launch template. You must specify either the launch template - // ID or launch template name in the request. + // The ID of the launch template. To describe one or more versions of a specified + // launch template, you must specify either the launch template ID or the launch + // template name in the request. To describe all the latest or default launch + // template versions in your account, you must omit this parameter. LaunchTemplateId *string `type:"string"` - // The name of the launch template. You must specify either the launch template - // ID or launch template name in the request. + // The name of the launch template. To describe one or more versions of a specified + // launch template, you must specify either the launch template ID or the launch + // template name in the request. To describe all the latest or default launch + // template versions in your account, you must omit this parameter. LaunchTemplateName *string `min:"3" type:"string"` // The maximum number of results to return in a single call. To retrieve the @@ -61182,7 +64054,18 @@ type DescribeLaunchTemplateVersionsInput struct { // The token to request the next page of results. NextToken *string `type:"string"` - // One or more versions of the launch template. + // One or more versions of the launch template. Valid values depend on whether + // you are describing a specified launch template (by ID or name) or all launch + // templates in your account. + // + // To describe one or more versions of a specified launch template, valid values + // are $Latest, $Default, and numbers. + // + // To describe all launch templates in your account that are defined as the + // latest version, the valid value is $Latest. To describe all launch templates + // in your account that are defined as the default version, the valid value + // is $Default. You can specify $Latest and $Default in the same call. You cannot + // specify numbers. Versions []*string `locationName:"LaunchTemplateVersion" locationNameList:"item" type:"list"` } @@ -61439,6 +64322,18 @@ type DescribeLocalGatewayRouteTableVirtualInterfaceGroupAssociationsInput struct DryRun *bool `type:"boolean"` // One or more filters. + // + // * local-gateway-id - The ID of a local gateway. + // + // * local-gateway-route-table-id - The ID of the local gateway route table. + // + // * local-gateway-route-table-virtual-interface-group-association-id - The + // ID of the association. + // + // * local-gateway-route-table-virtual-interface-group-id - The ID of the + // virtual interface group. + // + // * state - The state of the association. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` // The IDs of the associations. @@ -61548,6 +64443,16 @@ type DescribeLocalGatewayRouteTableVpcAssociationsInput struct { DryRun *bool `type:"boolean"` // One or more filters. + // + // * local-gateway-id - The ID of a local gateway. + // + // * local-gateway-route-table-id - The ID of the local gateway route table. + // + // * local-gateway-route-table-vpc-association-id - The ID of the association. + // + // * state - The state of the association. + // + // * vpc-id - The ID of the VPC. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` // The IDs of the associations. @@ -61657,6 +64562,14 @@ type DescribeLocalGatewayRouteTablesInput struct { DryRun *bool `type:"boolean"` // One or more filters. + // + // * local-gateway-id - The ID of a local gateway. + // + // * local-gateway-route-table-id - The ID of a local gateway route table. + // + // * outpost-arn - The Amazon Resource Name (ARN) of the Outpost. + // + // * state - The state of the local gateway route table. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` // The IDs of the local gateway route tables. @@ -61766,6 +64679,13 @@ type DescribeLocalGatewayVirtualInterfaceGroupsInput struct { DryRun *bool `type:"boolean"` // One or more filters. + // + // * local-gateway-id - The ID of a local gateway. + // + // * local-gateway-virtual-interface-id - The ID of the virtual interface. + // + // * local-gateway-virtual-interface-group-id - The ID of the virtual interface + // group. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` // The IDs of the virtual interface groups. @@ -61986,7 +64906,21 @@ type DescribeLocalGatewaysInput struct { // One or more filters. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` - // The IDs of the local gateways. + // One or more filters. + // + // * local-gateway-id - The ID of a local gateway. + // + // * local-gateway-route-table-id - The ID of the local gateway route table. + // + // * local-gateway-route-table-virtual-interface-group-association-id - The + // ID of the association. + // + // * local-gateway-route-table-virtual-interface-group-id - The ID of the + // virtual interface group. + // + // * outpost-arn - The Amazon Resource Name (ARN) of the Outpost. + // + // * state - The state of the association. LocalGatewayIds []*string `locationName:"LocalGatewayId" locationNameList:"item" type:"list"` // The maximum number of results to return with a single call. To retrieve the @@ -62083,6 +65017,121 @@ func (s *DescribeLocalGatewaysOutput) SetNextToken(v string) *DescribeLocalGatew return s } +type DescribeManagedPrefixListsInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // One or more filters. + // + // * owner-id - The ID of the prefix list owner. + // + // * prefix-list-id - The ID of the prefix list. + // + // * prefix-list-name - The name of the prefix list. + Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` + + // The maximum number of results to return with a single call. To retrieve the + // remaining results, make another call with the returned nextToken value. + MaxResults *int64 `min:"1" type:"integer"` + + // The token for the next page of results. + NextToken *string `type:"string"` + + // One or more prefix list IDs. + PrefixListIds []*string `locationName:"PrefixListId" locationNameList:"item" type:"list"` +} + +// String returns the string representation +func (s DescribeManagedPrefixListsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeManagedPrefixListsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *DescribeManagedPrefixListsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "DescribeManagedPrefixListsInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *DescribeManagedPrefixListsInput) SetDryRun(v bool) *DescribeManagedPrefixListsInput { + s.DryRun = &v + return s +} + +// SetFilters sets the Filters field's value. +func (s *DescribeManagedPrefixListsInput) SetFilters(v []*Filter) *DescribeManagedPrefixListsInput { + s.Filters = v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *DescribeManagedPrefixListsInput) SetMaxResults(v int64) *DescribeManagedPrefixListsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeManagedPrefixListsInput) SetNextToken(v string) *DescribeManagedPrefixListsInput { + s.NextToken = &v + return s +} + +// SetPrefixListIds sets the PrefixListIds field's value. +func (s *DescribeManagedPrefixListsInput) SetPrefixListIds(v []*string) *DescribeManagedPrefixListsInput { + s.PrefixListIds = v + return s +} + +type DescribeManagedPrefixListsOutput struct { + _ struct{} `type:"structure"` + + // The token to use to retrieve the next page of results. This value is null + // when there are no more results to return. + NextToken *string `locationName:"nextToken" type:"string"` + + // Information about the prefix lists. + PrefixLists []*ManagedPrefixList `locationName:"prefixListSet" locationNameList:"item" type:"list"` +} + +// String returns the string representation +func (s DescribeManagedPrefixListsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s DescribeManagedPrefixListsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *DescribeManagedPrefixListsOutput) SetNextToken(v string) *DescribeManagedPrefixListsOutput { + s.NextToken = &v + return s +} + +// SetPrefixLists sets the PrefixLists field's value. +func (s *DescribeManagedPrefixListsOutput) SetPrefixLists(v []*ManagedPrefixList) *DescribeManagedPrefixListsOutput { + s.PrefixLists = v + return s +} + type DescribeMovingAddressesInput struct { _ struct{} `type:"structure"` @@ -62773,9 +65822,6 @@ type DescribeNetworkInterfacesInput struct { // * attachment.instance-owner-id - The owner ID of the instance to which // the network interface is attached. // - // * attachment.nat-gateway-id - The ID of the NAT gateway to which the network - // interface is attached. - // // * attachment.status - The status of the attachment (attaching | attached // | detaching | detached). // @@ -64065,8 +67111,6 @@ type DescribeRouteTablesInput struct { // to find all resources assigned a tag with a specific key, regardless of // the tag value. // - // * transit-gateway-id - The ID of a transit gateway. - // // * vpc-id - The ID of the VPC for the route table. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` @@ -64555,8 +67599,8 @@ type DescribeSecurityGroupsInput struct { // * egress.ip-permission.ipv6-cidr - An IPv6 CIDR block for an outbound // security group rule. // - // * egress.ip-permission.prefix-list-id - The ID (prefix) of the AWS service - // to which a security group rule allows outbound access. + // * egress.ip-permission.prefix-list-id - The ID of a prefix list to which + // a security group rule allows outbound access. // // * egress.ip-permission.protocol - The IP protocol for an outbound security // group rule (tcp | udp | icmp or a protocol number). @@ -64586,8 +67630,8 @@ type DescribeSecurityGroupsInput struct { // * ip-permission.ipv6-cidr - An IPv6 CIDR block for an inbound security // group rule. // - // * ip-permission.prefix-list-id - The ID (prefix) of the AWS service from - // which a security group rule allows inbound access. + // * ip-permission.prefix-list-id - The ID of a prefix list from which a + // security group rule allows inbound access. // // * ip-permission.protocol - The IP protocol for an inbound security group // rule (tcp | udp | icmp or a protocol number). @@ -64850,12 +67894,12 @@ type DescribeSnapshotsInput struct { // // * encrypted - Indicates whether the snapshot is encrypted (true | false) // - // * owner-alias - Value from an Amazon-maintained list (amazon | self | - // all | aws-marketplace | microsoft) of snapshot owners. Not to be confused - // with the user-configured AWS account alias, which is set from the IAM - // console. + // * owner-alias - The owner alias, from an Amazon-maintained list (amazon). + // This is not the user-configured AWS account alias set using the IAM console. + // We recommend that you use the related parameter instead of this filter. // - // * owner-id - The ID of the AWS account that owns the snapshot. + // * owner-id - The AWS account ID of the owner. We recommend that you use + // the related parameter instead of this filter. // // * progress - The progress of the snapshot, as a percentage (for example, // 80%). @@ -64899,7 +67943,8 @@ type DescribeSnapshotsInput struct { // to return. NextToken *string `type:"string"` - // Describes the snapshots owned by these owners. + // Scopes the results to snapshots with the specified owners. You can specify + // a combination of AWS account IDs, self, and amazon. OwnerIds []*string `locationName:"Owner" locationNameList:"Owner" type:"list"` // The IDs of the AWS accounts that can create volumes from the snapshot. @@ -65455,8 +68500,8 @@ type DescribeSpotInstanceRequestsInput struct { // in GiB. // // * launch.block-device-mapping.volume-type - The type of EBS volume: gp2 - // for General Purpose SSD, io1 for Provisioned IOPS SSD, st1 for Throughput - // Optimized HDD, sc1for Cold HDD, or standard for Magnetic. + // for General Purpose SSD, io1 or io2 for Provisioned IOPS SSD, st1 for + // Throughput Optimized HDD, sc1for Cold HDD, or standard for Magnetic. // // * launch.group-id - The ID of the security group for the instance. // @@ -65510,7 +68555,7 @@ type DescribeSpotInstanceRequestsInput struct { // * state - The state of the Spot Instance request (open | active | closed // | cancelled | failed). Spot request status information can help you track // your Amazon EC2 Spot Instance requests. For more information, see Spot - // Request Status (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html) + // request status (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html) // in the Amazon EC2 User Guide for Linux Instances. // // * status-code - The short code describing the most recent evaluation of @@ -66530,11 +69575,12 @@ type DescribeTransitGatewayAttachmentsInput struct { // // * resource-owner-id - The ID of the AWS account that owns the resource. // - // * resource-type - The resource type (vpc | vpn). + // * resource-type - The resource type. Valid values are vpc | vpn | direct-connect-gateway + // | peering. // - // * state - The state of the attachment (available | deleted | deleting - // | failed | modifying | pendingAcceptance | pending | rollingBack | rejected - // | rejecting). + // * state - The state of the attachment. Valid values are available | deleted + // | deleting | failed | failing | initiatingRequest | modifying | pendingAcceptance + // | pending | rollingBack | rejected | rejecting. // // * transit-gateway-attachment-id - The ID of the attachment. // @@ -66776,9 +69822,9 @@ type DescribeTransitGatewayPeeringAttachmentsInput struct { // * remote-owner-id - The ID of the AWS account in the remote Region that // owns the transit gateway. // - // * state - The state of the peering attachment (available | deleted | deleting - // | failed | modifying | pendingAcceptance | pending | rollingBack | rejected - // | rejecting). + // * state - The state of the peering attachment. Valid values are available + // | deleted | deleting | failed | failing | initiatingRequest | modifying + // | pendingAcceptance | pending | rollingBack | rejected | rejecting). // // * transit-gateway-id - The ID of the transit gateway. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` @@ -66897,9 +69943,8 @@ type DescribeTransitGatewayRouteTablesInput struct { // * default-propagation-route-table - Indicates whether this is the default // propagation route table for the transit gateway (true | false). // - // * state - The state of the attachment (available | deleted | deleting - // | failed | modifying | pendingAcceptance | pending | rollingBack | rejected - // | rejecting). + // * state - The state of the route table (available | deleting | deleted + // | pending). // // * transit-gateway-id - The ID of the transit gateway. // @@ -67015,9 +70060,9 @@ type DescribeTransitGatewayVpcAttachmentsInput struct { // One or more filters. The possible values are: // - // * state - The state of the attachment (available | deleted | deleting - // | failed | modifying | pendingAcceptance | pending | rollingBack | rejected - // | rejecting). + // * state - The state of the attachment. Valid values are available | deleted + // | deleting | failed | failing | initiatingRequest | modifying | pendingAcceptance + // | pending | rollingBack | rejected | rejecting. // // * transit-gateway-attachment-id - The ID of the attachment. // @@ -67162,9 +70207,8 @@ type DescribeTransitGatewaysInput struct { // // * owner-id - The ID of the AWS account that owns the transit gateway. // - // * state - The state of the attachment (available | deleted | deleting - // | failed | modifying | pendingAcceptance | pending | rollingBack | rejected - // | rejecting). + // * state - The state of the transit gateway (available | deleted | deleting + // | modifying | pending). // // * transit-gateway-id - The ID of the transit gateway. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` @@ -67548,7 +70592,7 @@ type DescribeVolumesInput struct { // // * snapshot-id - The snapshot from which the volume was created. // - // * status - The status of the volume (creating | available | in-use | deleting + // * status - The state of the volume (creating | available | in-use | deleting // | deleted | error). // // * tag: - The key/value combination of a tag assigned to the resource. @@ -67564,7 +70608,7 @@ type DescribeVolumesInput struct { // * volume-id - The volume ID. // // * volume-type - The Amazon EBS volume type. This can be gp2 for General - // Purpose SSD, io1 for Provisioned IOPS SSD, st1 for Throughput Optimized + // Purpose SSD, io1 or io2 for Provisioned IOPS SSD, st1 for Throughput Optimized // HDD, sc1 for Cold HDD, or standard for Magnetic volumes. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` @@ -67638,9 +70682,34 @@ type DescribeVolumesModificationsInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The filters. Supported filters: volume-id | modification-state | target-size - // | target-iops | target-volume-type | original-size | original-iops | original-volume-type - // | start-time | originalMultiAttachEnabled | targetMultiAttachEnabled. + // The filters. + // + // * modification-state - The current modification state (modifying | optimizing + // | completed | failed). + // + // * original-iops - The original IOPS rate of the volume. + // + // * original-size - The original size of the volume, in GiB. + // + // * original-volume-type - The original volume type of the volume (standard + // | io1 | io2 | gp2 | sc1 | st1). + // + // * originalMultiAttachEnabled - Indicates whether Multi-Attach support + // was enabled (true | false). + // + // * start-time - The modification start time. + // + // * target-iops - The target IOPS rate of the volume. + // + // * target-size - The target size of the volume, in GiB. + // + // * target-volume-type - The target volume type of the volume (standard + // | io1 | io2 | gp2 | sc1 | st1). + // + // * targetMultiAttachEnabled - Indicates whether Multi-Attach support is + // to be enabled (true | false). + // + // * volume-id - The ID of the volume. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` // The maximum number of results (up to a limit of 500) to be returned in a @@ -67650,7 +70719,7 @@ type DescribeVolumesModificationsInput struct { // The nextToken value returned by a previous paginated request. NextToken *string `type:"string"` - // The IDs of the volumes for which in-progress modifications will be described. + // The IDs of the volumes. VolumeIds []*string `locationName:"VolumeId" locationNameList:"VolumeId" type:"list"` } @@ -69961,10 +73030,11 @@ type DisableFastSnapshotRestoreSuccessItem struct { // The time at which fast snapshot restores entered the optimizing state. OptimizingTime *time.Time `locationName:"optimizingTime" type:"timestamp"` - // The alias of the snapshot owner. + // The AWS owner alias that enabled fast snapshot restores on the snapshot. + // This is intended for future use. OwnerAlias *string `locationName:"ownerAlias" type:"string"` - // The ID of the AWS account that owns the snapshot. + // The ID of the AWS account that enabled fast snapshot restores on the snapshot. OwnerId *string `locationName:"ownerId" type:"string"` // The ID of the snapshot. @@ -70661,7 +73731,7 @@ type DisassociateRouteTableInput struct { _ struct{} `type:"structure"` // The association ID representing the current association between the route - // table and subnet. + // table and subnet or gateway. // // AssociationId is a required field AssociationId *string `locationName:"associationId" type:"string" required:"true"` @@ -71377,7 +74447,7 @@ type EbsBlockDevice struct { _ struct{} `type:"structure"` // Indicates whether the EBS volume is deleted on instance termination. For - // more information, see Preserving Amazon EBS Volumes on Instance Termination + // more information, see Preserving Amazon EBS volumes on instance termination // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html#preserving-volumes-on-termination) // in the Amazon Elastic Compute Cloud User Guide. DeleteOnTermination *bool `locationName:"deleteOnTermination" type:"boolean"` @@ -71392,27 +74462,28 @@ type EbsBlockDevice struct { // In no case can you remove encryption from an encrypted volume. // // Encrypted volumes can only be attached to instances that support Amazon EBS - // encryption. For more information, see Supported Instance Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances). + // encryption. For more information, see Supported instance types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html#EBSEncryption_supported_instances). // // This parameter is not returned by . Encrypted *bool `locationName:"encrypted" type:"boolean"` // The number of I/O operations per second (IOPS) that the volume supports. - // For io1 volumes, this represents the number of IOPS that are provisioned + // For io1 and io2 volumes, this represents the number of IOPS that are provisioned // for the volume. For gp2 volumes, this represents the baseline performance // of the volume and the rate at which the volume accumulates I/O credits for - // bursting. For more information, see Amazon EBS Volume Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) + // bursting. For more information, see Amazon EBS volume types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) // in the Amazon Elastic Compute Cloud User Guide. // - // Constraints: Range is 100-16,000 IOPS for gp2 volumes and 100 to 64,000IOPS - // for io1 volumes in most Regions. Maximum io1 IOPS of 64,000 is guaranteed - // only on Nitro-based instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). + // Constraints: Range is 100-16,000 IOPS for gp2 volumes and 100 to 64,000 IOPS + // for io1 and io2 volumes in most Regions. Maximum io1 and io2 IOPS of 64,000 + // is guaranteed only on Nitro-based instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). // Other instance families guarantee performance up to 32,000 IOPS. For more // information, see Amazon EBS Volume Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) // in the Amazon Elastic Compute Cloud User Guide. // - // Condition: This parameter is required for requests to create io1 volumes; - // it is not used in requests to create gp2, st1, sc1, or standard volumes. + // Condition: This parameter is required for requests to create io1 and io2 + // volumes; it is not used in requests to create gp2, st1, sc1, or standard + // volumes. Iops *int64 `locationName:"iops" type:"integer"` // Identifier (key ID, key alias, ID ARN, or alias ARN) for a customer managed @@ -71433,15 +74504,15 @@ type EbsBlockDevice struct { // a volume size, the default is the snapshot size. // // Constraints: 1-16384 for General Purpose SSD (gp2), 4-16384 for Provisioned - // IOPS SSD (io1), 500-16384 for Throughput Optimized HDD (st1), 500-16384 for - // Cold HDD (sc1), and 1-1024 for Magnetic (standard) volumes. If you specify + // IOPS SSD (io1 and io2), 500-16384 for Throughput Optimized HDD (st1), 500-16384 + // for Cold HDD (sc1), and 1-1024 for Magnetic (standard) volumes. If you specify // a snapshot, the volume size must be equal to or larger than the snapshot // size. VolumeSize *int64 `locationName:"volumeSize" type:"integer"` - // The volume type. If you set the type to io1, you must also specify the Iops - // parameter. If you set the type to gp2, st1, sc1, or standard, you must omit - // the Iops parameter. + // The volume type. If you set the type to io1 or io2, you must also specify + // the Iops parameter. If you set the type to gp2, st1, sc1, or standard, you + // must omit the Iops parameter. // // Default: gp2 VolumeType *string `locationName:"volumeType" type:"string" enum:"VolumeType"` @@ -71503,6 +74574,9 @@ func (s *EbsBlockDevice) SetVolumeType(v string) *EbsBlockDevice { type EbsInfo struct { _ struct{} `type:"structure"` + // Describes the optimized EBS performance for the instance type. + EbsOptimizedInfo *EbsOptimizedInfo `locationName:"ebsOptimizedInfo" type:"structure"` + // Indicates that the instance type is Amazon EBS-optimized. For more information, // see Amazon EBS-Optimized Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html) // in Amazon EC2 User Guide for Linux Instances. @@ -71510,6 +74584,9 @@ type EbsInfo struct { // Indicates whether Amazon EBS encryption is supported. EncryptionSupport *string `locationName:"encryptionSupport" type:"string" enum:"EbsEncryptionSupport"` + + // Indicates whether non-volatile memory express (NVMe) is supported. + NvmeSupport *string `locationName:"nvmeSupport" type:"string" enum:"EbsNvmeSupport"` } // String returns the string representation @@ -71522,6 +74599,12 @@ func (s EbsInfo) GoString() string { return s.String() } +// SetEbsOptimizedInfo sets the EbsOptimizedInfo field's value. +func (s *EbsInfo) SetEbsOptimizedInfo(v *EbsOptimizedInfo) *EbsInfo { + s.EbsOptimizedInfo = v + return s +} + // SetEbsOptimizedSupport sets the EbsOptimizedSupport field's value. func (s *EbsInfo) SetEbsOptimizedSupport(v string) *EbsInfo { s.EbsOptimizedSupport = &v @@ -71534,6 +74617,12 @@ func (s *EbsInfo) SetEncryptionSupport(v string) *EbsInfo { return s } +// SetNvmeSupport sets the NvmeSupport field's value. +func (s *EbsInfo) SetNvmeSupport(v string) *EbsInfo { + s.NvmeSupport = &v + return s +} + // Describes a parameter used to set up an EBS volume in a block device mapping. type EbsInstanceBlockDevice struct { _ struct{} `type:"structure"` @@ -71619,6 +74708,81 @@ func (s *EbsInstanceBlockDeviceSpecification) SetVolumeId(v string) *EbsInstance return s } +// Describes the optimized EBS performance for supported instance types. +type EbsOptimizedInfo struct { + _ struct{} `type:"structure"` + + // The baseline bandwidth performance for an EBS-optimized instance type, in + // Mbps. + BaselineBandwidthInMbps *int64 `locationName:"baselineBandwidthInMbps" type:"integer"` + + // The baseline input/output storage operations per seconds for an EBS-optimized + // instance type. + BaselineIops *int64 `locationName:"baselineIops" type:"integer"` + + // The baseline throughput performance for an EBS-optimized instance type, in + // MBps. + BaselineThroughputInMBps *float64 `locationName:"baselineThroughputInMBps" type:"double"` + + // The maximum bandwidth performance for an EBS-optimized instance type, in + // Mbps. + MaximumBandwidthInMbps *int64 `locationName:"maximumBandwidthInMbps" type:"integer"` + + // The maximum input/output storage operations per second for an EBS-optimized + // instance type. + MaximumIops *int64 `locationName:"maximumIops" type:"integer"` + + // The maximum throughput performance for an EBS-optimized instance type, in + // MBps. + MaximumThroughputInMBps *float64 `locationName:"maximumThroughputInMBps" type:"double"` +} + +// String returns the string representation +func (s EbsOptimizedInfo) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s EbsOptimizedInfo) GoString() string { + return s.String() +} + +// SetBaselineBandwidthInMbps sets the BaselineBandwidthInMbps field's value. +func (s *EbsOptimizedInfo) SetBaselineBandwidthInMbps(v int64) *EbsOptimizedInfo { + s.BaselineBandwidthInMbps = &v + return s +} + +// SetBaselineIops sets the BaselineIops field's value. +func (s *EbsOptimizedInfo) SetBaselineIops(v int64) *EbsOptimizedInfo { + s.BaselineIops = &v + return s +} + +// SetBaselineThroughputInMBps sets the BaselineThroughputInMBps field's value. +func (s *EbsOptimizedInfo) SetBaselineThroughputInMBps(v float64) *EbsOptimizedInfo { + s.BaselineThroughputInMBps = &v + return s +} + +// SetMaximumBandwidthInMbps sets the MaximumBandwidthInMbps field's value. +func (s *EbsOptimizedInfo) SetMaximumBandwidthInMbps(v int64) *EbsOptimizedInfo { + s.MaximumBandwidthInMbps = &v + return s +} + +// SetMaximumIops sets the MaximumIops field's value. +func (s *EbsOptimizedInfo) SetMaximumIops(v int64) *EbsOptimizedInfo { + s.MaximumIops = &v + return s +} + +// SetMaximumThroughputInMBps sets the MaximumThroughputInMBps field's value. +func (s *EbsOptimizedInfo) SetMaximumThroughputInMBps(v float64) *EbsOptimizedInfo { + s.MaximumThroughputInMBps = &v + return s +} + // Describes an egress-only internet gateway. type EgressOnlyInternetGateway struct { _ struct{} `type:"structure"` @@ -71891,7 +75055,7 @@ type ElasticInferenceAccelerator struct { Count *int64 `min:"1" type:"integer"` // The type of elastic inference accelerator. The possible values are eia1.medium, - // eia1.large, and eia1.xlarge. + // eia1.large, eia1.xlarge, eia2.medium, eia2.large, and eia2.xlarge. // // Type is a required field Type *string `type:"string" required:"true"` @@ -72159,10 +75323,11 @@ type EnableFastSnapshotRestoreSuccessItem struct { // The time at which fast snapshot restores entered the optimizing state. OptimizingTime *time.Time `locationName:"optimizingTime" type:"timestamp"` - // The alias of the snapshot owner. + // The AWS owner alias that enabled fast snapshot restores on the snapshot. + // This is intended for future use. OwnerAlias *string `locationName:"ownerAlias" type:"string"` - // The ID of the AWS account that owns the snapshot. + // The ID of the AWS account that enabled fast snapshot restores on the snapshot. OwnerId *string `locationName:"ownerId" type:"string"` // The ID of the snapshot. @@ -72974,7 +76139,7 @@ type ExportImageInput struct { // Token to enable idempotency for export image requests. ClientToken *string `type:"string" idempotencyToken:"true"` - // A description of the image being exported. The maximum length is 255 bytes. + // A description of the image being exported. The maximum length is 255 characters. Description *string `type:"string"` // The disk image format. @@ -72994,15 +76159,18 @@ type ExportImageInput struct { ImageId *string `type:"string" required:"true"` // The name of the role that grants VM Import/Export permission to export images - // to your S3 bucket. If this parameter is not specified, the default role is - // named 'vmimport'. + // to your Amazon S3 bucket. If this parameter is not specified, the default + // role is named 'vmimport'. RoleName *string `type:"string"` - // Information about the destination S3 bucket. The bucket must exist and grant - // WRITE and READ_ACP permissions to the AWS account vm-import-export@amazon.com. + // Information about the destination Amazon S3 bucket. The bucket must exist + // and grant WRITE and READ_ACP permissions to the AWS account vm-import-export@amazon.com. // // S3ExportLocation is a required field S3ExportLocation *ExportTaskS3LocationRequest `type:"structure" required:"true"` + + // The tags to apply to the image being exported. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } // String returns the string representation @@ -73081,6 +76249,12 @@ func (s *ExportImageInput) SetS3ExportLocation(v *ExportTaskS3LocationRequest) * return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *ExportImageInput) SetTagSpecifications(v []*TagSpecification) *ExportImageInput { + s.TagSpecifications = v + return s +} + type ExportImageOutput struct { _ struct{} `type:"structure"` @@ -73100,10 +76274,10 @@ type ExportImageOutput struct { Progress *string `locationName:"progress" type:"string"` // The name of the role that grants VM Import/Export permission to export images - // to your S3 bucket. + // to your Amazon S3 bucket. RoleName *string `locationName:"roleName" type:"string"` - // Information about the destination S3 bucket. + // Information about the destination Amazon S3 bucket. S3ExportLocation *ExportTaskS3Location `locationName:"s3ExportLocation" type:"structure"` // The status of the export image task. The possible values are active, completed, @@ -73112,6 +76286,9 @@ type ExportImageOutput struct { // The status message for the export image task. StatusMessage *string `locationName:"statusMessage" type:"string"` + + // Any tags assigned to the image being exported. + Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` } // String returns the string representation @@ -73178,6 +76355,12 @@ func (s *ExportImageOutput) SetStatusMessage(v string) *ExportImageOutput { return s } +// SetTags sets the Tags field's value. +func (s *ExportImageOutput) SetTags(v []*Tag) *ExportImageOutput { + s.Tags = v + return s +} + // Describes an export image task. type ExportImageTask struct { _ struct{} `type:"structure"` @@ -73194,7 +76377,7 @@ type ExportImageTask struct { // The percent complete of the export image task. Progress *string `locationName:"progress" type:"string"` - // Information about the destination S3 bucket. + // Information about the destination Amazon S3 bucket. S3ExportLocation *ExportTaskS3Location `locationName:"s3ExportLocation" type:"structure"` // The status of the export image task. The possible values are active, completed, @@ -73203,6 +76386,9 @@ type ExportImageTask struct { // The status message for the export image task. StatusMessage *string `locationName:"statusMessage" type:"string"` + + // Any tags assigned to the image being exported. + Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` } // String returns the string representation @@ -73257,6 +76443,12 @@ func (s *ExportImageTask) SetStatusMessage(v string) *ExportImageTask { return s } +// SetTags sets the Tags field's value. +func (s *ExportImageTask) SetTags(v []*Tag) *ExportImageTask { + s.Tags = v + return s +} + // Describes an instance export task. type ExportTask struct { _ struct{} `type:"structure"` @@ -73339,7 +76531,7 @@ func (s *ExportTask) SetTags(v []*Tag) *ExportTask { type ExportTaskS3Location struct { _ struct{} `type:"structure"` - // The destination S3 bucket. + // The destination Amazon S3 bucket. S3Bucket *string `locationName:"s3Bucket" type:"string"` // The prefix (logical hierarchy) in the bucket. @@ -73372,7 +76564,7 @@ func (s *ExportTaskS3Location) SetS3Prefix(v string) *ExportTaskS3Location { type ExportTaskS3LocationRequest struct { _ struct{} `type:"structure"` - // The destination S3 bucket. + // The destination Amazon S3 bucket. // // S3Bucket is a required field S3Bucket *string `type:"string" required:"true"` @@ -73427,8 +76619,8 @@ type ExportToS3Task struct { // The format for the exported image. DiskImageFormat *string `locationName:"diskImageFormat" type:"string" enum:"DiskImageFormat"` - // The S3 bucket for the destination image. The destination bucket must exist - // and grant WRITE and READ_ACP permissions to the AWS account vm-import-export@amazon.com. + // The Amazon S3 bucket for the destination image. The destination bucket must + // exist and grant WRITE and READ_ACP permissions to the AWS account vm-import-export@amazon.com. S3Bucket *string `locationName:"s3Bucket" type:"string"` // The encryption key for your S3 bucket. @@ -73480,12 +76672,12 @@ type ExportToS3TaskSpecification struct { // The format for the exported image. DiskImageFormat *string `locationName:"diskImageFormat" type:"string" enum:"DiskImageFormat"` - // The S3 bucket for the destination image. The destination bucket must exist - // and grant WRITE and READ_ACP permissions to the AWS account vm-import-export@amazon.com. + // The Amazon S3 bucket for the destination image. The destination bucket must + // exist and grant WRITE and READ_ACP permissions to the AWS account vm-import-export@amazon.com. S3Bucket *string `locationName:"s3Bucket" type:"string"` - // The image is written to a single object in the S3 bucket at the S3 key s3prefix - // + exportTaskId + '.' + diskImageFormat. + // The image is written to a single object in the Amazon S3 bucket at the S3 + // key s3prefix + exportTaskId + '.' + diskImageFormat. S3Prefix *string `locationName:"s3Prefix" type:"string"` } @@ -73552,13 +76744,11 @@ type ExportTransitGatewayRoutesInput struct { // routes in your route table and you specify supernet-of-match as 10.0.1.0/30, // then the result returns 10.0.1.0/29. // - // * state - The state of the attachment (available | deleted | deleting - // | failed | modifying | pendingAcceptance | pending | rollingBack | rejected - // | rejecting). + // * state - The state of the route (active | blackhole). // // * transit-gateway-route-destination-cidr-block - The CIDR range. // - // * type - The type of route (active | blackhole). + // * type - The type of route (propagated | static). Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` // The name of the S3 bucket. @@ -73678,6 +76868,54 @@ func (s *FailedQueuedPurchaseDeletion) SetReservedInstancesId(v string) *FailedQ return s } +// Describes the IAM SAML identity provider used for federated authentication. +type FederatedAuthentication struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the IAM SAML identity provider. + SamlProviderArn *string `locationName:"samlProviderArn" type:"string"` +} + +// String returns the string representation +func (s FederatedAuthentication) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s FederatedAuthentication) GoString() string { + return s.String() +} + +// SetSamlProviderArn sets the SamlProviderArn field's value. +func (s *FederatedAuthentication) SetSamlProviderArn(v string) *FederatedAuthentication { + s.SamlProviderArn = &v + return s +} + +// The IAM SAML identity provider used for federated authentication. +type FederatedAuthenticationRequest struct { + _ struct{} `type:"structure"` + + // The Amazon Resource Name (ARN) of the IAM SAML identity provider. + SAMLProviderArn *string `type:"string"` +} + +// String returns the string representation +func (s FederatedAuthenticationRequest) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s FederatedAuthenticationRequest) GoString() string { + return s.String() +} + +// SetSAMLProviderArn sets the SAMLProviderArn field's value. +func (s *FederatedAuthenticationRequest) SetSAMLProviderArn(v string) *FederatedAuthenticationRequest { + s.SAMLProviderArn = &v + return s +} + // A filter name and value pair that is used to return a more specific list // of results from a describe operation. Filters can be used to match a set // of resources by specific criteria, such as tags, attributes, or IDs. The @@ -74209,19 +77447,30 @@ func (s *FleetLaunchTemplateOverridesRequest) SetWeightedCapacity(v float64) *Fl return s } -// Describes a launch template. +// Describes the Amazon EC2 launch template and the launch template version +// that can be used by a Spot Fleet request to configure Amazon EC2 instances. +// For information about launch templates, see Launching an instance from a +// launch template (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html) +// in the Amazon EC2 User Guide for Linux Instances. type FleetLaunchTemplateSpecification struct { _ struct{} `type:"structure"` - // The ID of the launch template. You must specify either a template ID or a - // template name. + // The ID of the launch template. If you specify the template ID, you can't + // specify the template name. LaunchTemplateId *string `locationName:"launchTemplateId" type:"string"` - // The name of the launch template. You must specify either a template name - // or a template ID. + // The name of the launch template. If you specify the template name, you can't + // specify the template ID. LaunchTemplateName *string `locationName:"launchTemplateName" min:"3" type:"string"` - // The version number of the launch template. You must specify a version number. + // The launch template version number, $Latest, or $Default. You must specify + // a value, otherwise the request fails. + // + // If the value is $Latest, Amazon EC2 uses the latest version of the launch + // template. + // + // If the value is $Default, Amazon EC2 uses the default version of the launch + // template. Version *string `locationName:"version" type:"string"` } @@ -74266,19 +77515,30 @@ func (s *FleetLaunchTemplateSpecification) SetVersion(v string) *FleetLaunchTemp return s } -// The launch template to use. You must specify either the launch template ID -// or launch template name in the request. +// Describes the Amazon EC2 launch template and the launch template version +// that can be used by an EC2 Fleet to configure Amazon EC2 instances. For information +// about launch templates, see Launching an instance from a launch template +// (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html) +// in the Amazon Elastic Compute Cloud User Guide. type FleetLaunchTemplateSpecificationRequest struct { _ struct{} `type:"structure"` - // The ID of the launch template. + // The ID of the launch template. If you specify the template ID, you can't + // specify the template name. LaunchTemplateId *string `type:"string"` - // The name of the launch template. + // The name of the launch template. If you specify the template name, you can't + // specify the template ID. LaunchTemplateName *string `min:"3" type:"string"` - // The version number of the launch template. Note: This is a required parameter - // and will be updated soon. + // The launch template version number, $Latest, or $Default. You must specify + // a value, otherwise the request fails. + // + // If the value is $Latest, Amazon EC2 uses the latest version of the launch + // template. + // + // If the value is $Default, Amazon EC2 uses the default version of the launch + // template. Version *string `type:"string"` } @@ -74963,12 +78223,13 @@ type GetCapacityReservationUsageInput struct { // The maximum number of results to return for the request in a single page. // The remaining results can be seen by sending another request with the returned - // nextToken value. + // nextToken value. This value can be between 5 and 500. If maxResults is given + // a larger value than 500, you receive an error. // // Valid range: Minimum value of 1. Maximum value of 1000. MaxResults *int64 `min:"1" type:"integer"` - // The token to retrieve the next page of results. + // The token to use to retrieve the next page of results. NextToken *string `type:"string"` } @@ -75615,6 +78876,114 @@ func (s *GetEbsEncryptionByDefaultOutput) SetEbsEncryptionByDefault(v bool) *Get return s } +type GetGroupsForCapacityReservationInput struct { + _ struct{} `type:"structure"` + + // The ID of the Capacity Reservation. + // + // CapacityReservationId is a required field + CapacityReservationId *string `type:"string" required:"true"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The maximum number of results to return for the request in a single page. + // The remaining results can be seen by sending another request with the returned + // nextToken value. This value can be between 5 and 500. If maxResults is given + // a larger value than 500, you receive an error. + MaxResults *int64 `min:"1" type:"integer"` + + // The token to use to retrieve the next page of results. + NextToken *string `type:"string"` +} + +// String returns the string representation +func (s GetGroupsForCapacityReservationInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetGroupsForCapacityReservationInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetGroupsForCapacityReservationInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetGroupsForCapacityReservationInput"} + if s.CapacityReservationId == nil { + invalidParams.Add(request.NewErrParamRequired("CapacityReservationId")) + } + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCapacityReservationId sets the CapacityReservationId field's value. +func (s *GetGroupsForCapacityReservationInput) SetCapacityReservationId(v string) *GetGroupsForCapacityReservationInput { + s.CapacityReservationId = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *GetGroupsForCapacityReservationInput) SetDryRun(v bool) *GetGroupsForCapacityReservationInput { + s.DryRun = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetGroupsForCapacityReservationInput) SetMaxResults(v int64) *GetGroupsForCapacityReservationInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetGroupsForCapacityReservationInput) SetNextToken(v string) *GetGroupsForCapacityReservationInput { + s.NextToken = &v + return s +} + +type GetGroupsForCapacityReservationOutput struct { + _ struct{} `type:"structure"` + + // Information about the resource groups to which the Capacity Reservation has + // been added. + CapacityReservationGroups []*CapacityReservationGroup `locationName:"capacityReservationGroupSet" locationNameList:"item" type:"list"` + + // The token to use to retrieve the next page of results. This value is null + // when there are no more results to return. + NextToken *string `locationName:"nextToken" type:"string"` +} + +// String returns the string representation +func (s GetGroupsForCapacityReservationOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetGroupsForCapacityReservationOutput) GoString() string { + return s.String() +} + +// SetCapacityReservationGroups sets the CapacityReservationGroups field's value. +func (s *GetGroupsForCapacityReservationOutput) SetCapacityReservationGroups(v []*CapacityReservationGroup) *GetGroupsForCapacityReservationOutput { + s.CapacityReservationGroups = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetGroupsForCapacityReservationOutput) SetNextToken(v string) *GetGroupsForCapacityReservationOutput { + s.NextToken = &v + return s +} + type GetHostReservationPurchasePreviewInput struct { _ struct{} `type:"structure"` @@ -75792,6 +79161,226 @@ func (s *GetLaunchTemplateDataOutput) SetLaunchTemplateData(v *ResponseLaunchTem return s } +type GetManagedPrefixListAssociationsInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The maximum number of results to return with a single call. To retrieve the + // remaining results, make another call with the returned nextToken value. + MaxResults *int64 `min:"5" type:"integer"` + + // The token for the next page of results. + NextToken *string `type:"string"` + + // The ID of the prefix list. + // + // PrefixListId is a required field + PrefixListId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s GetManagedPrefixListAssociationsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetManagedPrefixListAssociationsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetManagedPrefixListAssociationsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetManagedPrefixListAssociationsInput"} + if s.MaxResults != nil && *s.MaxResults < 5 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 5)) + } + if s.PrefixListId == nil { + invalidParams.Add(request.NewErrParamRequired("PrefixListId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *GetManagedPrefixListAssociationsInput) SetDryRun(v bool) *GetManagedPrefixListAssociationsInput { + s.DryRun = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetManagedPrefixListAssociationsInput) SetMaxResults(v int64) *GetManagedPrefixListAssociationsInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetManagedPrefixListAssociationsInput) SetNextToken(v string) *GetManagedPrefixListAssociationsInput { + s.NextToken = &v + return s +} + +// SetPrefixListId sets the PrefixListId field's value. +func (s *GetManagedPrefixListAssociationsInput) SetPrefixListId(v string) *GetManagedPrefixListAssociationsInput { + s.PrefixListId = &v + return s +} + +type GetManagedPrefixListAssociationsOutput struct { + _ struct{} `type:"structure"` + + // The token to use to retrieve the next page of results. This value is null + // when there are no more results to return. + NextToken *string `locationName:"nextToken" type:"string"` + + // Information about the associations. + PrefixListAssociations []*PrefixListAssociation `locationName:"prefixListAssociationSet" locationNameList:"item" type:"list"` +} + +// String returns the string representation +func (s GetManagedPrefixListAssociationsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetManagedPrefixListAssociationsOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *GetManagedPrefixListAssociationsOutput) SetNextToken(v string) *GetManagedPrefixListAssociationsOutput { + s.NextToken = &v + return s +} + +// SetPrefixListAssociations sets the PrefixListAssociations field's value. +func (s *GetManagedPrefixListAssociationsOutput) SetPrefixListAssociations(v []*PrefixListAssociation) *GetManagedPrefixListAssociationsOutput { + s.PrefixListAssociations = v + return s +} + +type GetManagedPrefixListEntriesInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The maximum number of results to return with a single call. To retrieve the + // remaining results, make another call with the returned nextToken value. + MaxResults *int64 `min:"1" type:"integer"` + + // The token for the next page of results. + NextToken *string `type:"string"` + + // The ID of the prefix list. + // + // PrefixListId is a required field + PrefixListId *string `type:"string" required:"true"` + + // The version of the prefix list for which to return the entries. The default + // is the current version. + TargetVersion *int64 `type:"long"` +} + +// String returns the string representation +func (s GetManagedPrefixListEntriesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetManagedPrefixListEntriesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetManagedPrefixListEntriesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetManagedPrefixListEntriesInput"} + if s.MaxResults != nil && *s.MaxResults < 1 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1)) + } + if s.PrefixListId == nil { + invalidParams.Add(request.NewErrParamRequired("PrefixListId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *GetManagedPrefixListEntriesInput) SetDryRun(v bool) *GetManagedPrefixListEntriesInput { + s.DryRun = &v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetManagedPrefixListEntriesInput) SetMaxResults(v int64) *GetManagedPrefixListEntriesInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetManagedPrefixListEntriesInput) SetNextToken(v string) *GetManagedPrefixListEntriesInput { + s.NextToken = &v + return s +} + +// SetPrefixListId sets the PrefixListId field's value. +func (s *GetManagedPrefixListEntriesInput) SetPrefixListId(v string) *GetManagedPrefixListEntriesInput { + s.PrefixListId = &v + return s +} + +// SetTargetVersion sets the TargetVersion field's value. +func (s *GetManagedPrefixListEntriesInput) SetTargetVersion(v int64) *GetManagedPrefixListEntriesInput { + s.TargetVersion = &v + return s +} + +type GetManagedPrefixListEntriesOutput struct { + _ struct{} `type:"structure"` + + // Information about the prefix list entries. + Entries []*PrefixListEntry `locationName:"entrySet" locationNameList:"item" type:"list"` + + // The token to use to retrieve the next page of results. This value is null + // when there are no more results to return. + NextToken *string `locationName:"nextToken" type:"string"` +} + +// String returns the string representation +func (s GetManagedPrefixListEntriesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetManagedPrefixListEntriesOutput) GoString() string { + return s.String() +} + +// SetEntries sets the Entries field's value. +func (s *GetManagedPrefixListEntriesOutput) SetEntries(v []*PrefixListEntry) *GetManagedPrefixListEntriesOutput { + s.Entries = v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetManagedPrefixListEntriesOutput) SetNextToken(v string) *GetManagedPrefixListEntriesOutput { + s.NextToken = &v + return s +} + type GetPasswordDataInput struct { _ struct{} `type:"structure"` @@ -76288,6 +79877,137 @@ func (s *GetTransitGatewayMulticastDomainAssociationsOutput) SetNextToken(v stri return s } +type GetTransitGatewayPrefixListReferencesInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // One or more filters. The possible values are: + // + // * attachment.resource-id - The ID of the resource for the attachment. + // + // * attachment.resource-type - The type of resource for the attachment. + // Valid values are vpc | vpn | direct-connect-gateway | peering. + // + // * attachment.transit-gateway-attachment-id - The ID of the attachment. + // + // * is-blackhole - Whether traffic matching the route is blocked (true | + // false). + // + // * prefix-list-id - The ID of the prefix list. + // + // * prefix-list-owner-id - The ID of the owner of the prefix list. + // + // * state - The state of the prefix list reference (pending | available + // | modifying | deleting). + Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` + + // The maximum number of results to return with a single call. To retrieve the + // remaining results, make another call with the returned nextToken value. + MaxResults *int64 `min:"5" type:"integer"` + + // The token for the next page of results. + NextToken *string `type:"string"` + + // The ID of the transit gateway route table. + // + // TransitGatewayRouteTableId is a required field + TransitGatewayRouteTableId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s GetTransitGatewayPrefixListReferencesInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetTransitGatewayPrefixListReferencesInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *GetTransitGatewayPrefixListReferencesInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "GetTransitGatewayPrefixListReferencesInput"} + if s.MaxResults != nil && *s.MaxResults < 5 { + invalidParams.Add(request.NewErrParamMinValue("MaxResults", 5)) + } + if s.TransitGatewayRouteTableId == nil { + invalidParams.Add(request.NewErrParamRequired("TransitGatewayRouteTableId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *GetTransitGatewayPrefixListReferencesInput) SetDryRun(v bool) *GetTransitGatewayPrefixListReferencesInput { + s.DryRun = &v + return s +} + +// SetFilters sets the Filters field's value. +func (s *GetTransitGatewayPrefixListReferencesInput) SetFilters(v []*Filter) *GetTransitGatewayPrefixListReferencesInput { + s.Filters = v + return s +} + +// SetMaxResults sets the MaxResults field's value. +func (s *GetTransitGatewayPrefixListReferencesInput) SetMaxResults(v int64) *GetTransitGatewayPrefixListReferencesInput { + s.MaxResults = &v + return s +} + +// SetNextToken sets the NextToken field's value. +func (s *GetTransitGatewayPrefixListReferencesInput) SetNextToken(v string) *GetTransitGatewayPrefixListReferencesInput { + s.NextToken = &v + return s +} + +// SetTransitGatewayRouteTableId sets the TransitGatewayRouteTableId field's value. +func (s *GetTransitGatewayPrefixListReferencesInput) SetTransitGatewayRouteTableId(v string) *GetTransitGatewayPrefixListReferencesInput { + s.TransitGatewayRouteTableId = &v + return s +} + +type GetTransitGatewayPrefixListReferencesOutput struct { + _ struct{} `type:"structure"` + + // The token to use to retrieve the next page of results. This value is null + // when there are no more results to return. + NextToken *string `locationName:"nextToken" type:"string"` + + // Information about the prefix list references. + TransitGatewayPrefixListReferences []*TransitGatewayPrefixListReference `locationName:"transitGatewayPrefixListReferenceSet" locationNameList:"item" type:"list"` +} + +// String returns the string representation +func (s GetTransitGatewayPrefixListReferencesOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s GetTransitGatewayPrefixListReferencesOutput) GoString() string { + return s.String() +} + +// SetNextToken sets the NextToken field's value. +func (s *GetTransitGatewayPrefixListReferencesOutput) SetNextToken(v string) *GetTransitGatewayPrefixListReferencesOutput { + s.NextToken = &v + return s +} + +// SetTransitGatewayPrefixListReferences sets the TransitGatewayPrefixListReferences field's value. +func (s *GetTransitGatewayPrefixListReferencesOutput) SetTransitGatewayPrefixListReferences(v []*TransitGatewayPrefixListReference) *GetTransitGatewayPrefixListReferencesOutput { + s.TransitGatewayPrefixListReferences = v + return s +} + type GetTransitGatewayRouteTableAssociationsInput struct { _ struct{} `type:"structure"` @@ -76301,7 +80021,8 @@ type GetTransitGatewayRouteTableAssociationsInput struct { // // * resource-id - The ID of the resource. // - // * resource-type - The resource type (vpc | vpn). + // * resource-type - The resource type. Valid values are vpc | vpn | direct-connect-gateway + // | peering. // // * transit-gateway-attachment-id - The ID of the attachment. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` @@ -76421,7 +80142,8 @@ type GetTransitGatewayRouteTablePropagationsInput struct { // // * resource-id - The ID of the resource. // - // * resource-type - The resource type (vpc | vpn). + // * resource-type - The resource type. Valid values are vpc | vpn | direct-connect-gateway + // | peering. // // * transit-gateway-attachment-id - The ID of the attachment. Filters []*Filter `locationName:"Filter" locationNameList:"Filter" type:"list"` @@ -76671,7 +80393,7 @@ func (s *GroupIdentifier) SetGroupName(v string) *GroupIdentifier { // Indicates whether your instance is configured for hibernation. This parameter // is valid only if the instance meets the hibernation prerequisites (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites). -// For more information, see Hibernate Your Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) +// For more information, see Hibernate your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) // in the Amazon Elastic Compute Cloud User Guide. type HibernationOptions struct { _ struct{} `type:"structure"` @@ -76699,7 +80421,7 @@ func (s *HibernationOptions) SetConfigured(v bool) *HibernationOptions { // Indicates whether your instance is configured for hibernation. This parameter // is valid only if the instance meets the hibernation prerequisites (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html#hibernating-prerequisites). -// For more information, see Hibernate Your Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) +// For more information, see Hibernate your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) // in the Amazon Elastic Compute Cloud User Guide. type HibernationOptionsRequest struct { _ struct{} `type:"structure"` @@ -77849,7 +81571,7 @@ type ImageDiskContainer struct { // The format of the disk image being imported. // - // Valid values: VHD | VMDK | OVA + // Valid values: OVA | VHD | VHDX |VMDK Format *string `type:"string"` // The ID of the EBS snapshot to be used for importing the snapshot. @@ -78091,6 +81813,9 @@ type ImportImageInput struct { // The name of the role to use when not using the default role, 'vmimport'. RoleName *string `type:"string"` + + // The tags to apply to the image being imported. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } // String returns the string representation @@ -78181,6 +81906,12 @@ func (s *ImportImageInput) SetRoleName(v string) *ImportImageInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *ImportImageInput) SetTagSpecifications(v []*TagSpecification) *ImportImageInput { + s.TagSpecifications = v + return s +} + // The request information of license configurations. type ImportImageLicenseConfigurationRequest struct { _ struct{} `type:"structure"` @@ -78238,7 +81969,7 @@ type ImportImageOutput struct { // A description of the import task. Description *string `locationName:"description" type:"string"` - // Indicates whether the AMI is encypted. + // Indicates whether the AMI is encrypted. Encrypted *bool `locationName:"encrypted" type:"boolean"` // The target hypervisor of the import task. @@ -78274,6 +82005,9 @@ type ImportImageOutput struct { // A detailed status message of the import task. StatusMessage *string `locationName:"statusMessage" type:"string"` + + // Any tags assigned to the image being imported. + Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` } // String returns the string representation @@ -78370,6 +82104,12 @@ func (s *ImportImageOutput) SetStatusMessage(v string) *ImportImageOutput { return s } +// SetTags sets the Tags field's value. +func (s *ImportImageOutput) SetTags(v []*Tag) *ImportImageOutput { + s.Tags = v + return s +} + // Describes an import image task. type ImportImageTask struct { _ struct{} `type:"structure"` @@ -79070,6 +82810,9 @@ type ImportSnapshotInput struct { // The name of the role to use when not using the default role, 'vmimport'. RoleName *string `type:"string"` + + // The tags to apply to the snapshot being imported. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } // String returns the string representation @@ -79130,6 +82873,12 @@ func (s *ImportSnapshotInput) SetRoleName(v string) *ImportSnapshotInput { return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *ImportSnapshotInput) SetTagSpecifications(v []*TagSpecification) *ImportSnapshotInput { + s.TagSpecifications = v + return s +} + type ImportSnapshotOutput struct { _ struct{} `type:"structure"` @@ -79141,6 +82890,9 @@ type ImportSnapshotOutput struct { // Information about the import snapshot task. SnapshotTaskDetail *SnapshotTaskDetail `locationName:"snapshotTaskDetail" type:"structure"` + + // Any tags assigned to the snapshot being imported. + Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` } // String returns the string representation @@ -79171,6 +82923,12 @@ func (s *ImportSnapshotOutput) SetSnapshotTaskDetail(v *SnapshotTaskDetail) *Imp return s } +// SetTags sets the Tags field's value. +func (s *ImportSnapshotOutput) SetTags(v []*Tag) *ImportSnapshotOutput { + s.Tags = v + return s +} + // Describes an import snapshot task. type ImportSnapshotTask struct { _ struct{} `type:"structure"` @@ -79584,7 +83342,11 @@ type Instance struct { // name is only available if you've enabled DNS hostnames for your VPC. PublicDnsName *string `locationName:"dnsName" type:"string"` - // The public IPv4 address assigned to the instance, if applicable. + // The public IPv4 address, or the Carrier IP address assigned to the instance, + // if applicable. + // + // A Carrier IP address only applies to an instance launched in a subnet associated + // with a Wavelength Zone. PublicIpAddress *string `locationName:"ipAddress" type:"string"` // The RAM disk associated with this instance, if applicable. @@ -80649,6 +84411,9 @@ func (s *InstanceNetworkInterface) SetVpcId(v string) *InstanceNetworkInterface type InstanceNetworkInterfaceAssociation struct { _ struct{} `type:"structure"` + // The carrier IP address associated with the network interface. + CarrierIp *string `locationName:"carrierIp" type:"string"` + // The ID of the owner of the Elastic IP address. IpOwnerId *string `locationName:"ipOwnerId" type:"string"` @@ -80669,6 +84434,12 @@ func (s InstanceNetworkInterfaceAssociation) GoString() string { return s.String() } +// SetCarrierIp sets the CarrierIp field's value. +func (s *InstanceNetworkInterfaceAssociation) SetCarrierIp(v string) *InstanceNetworkInterfaceAssociation { + s.CarrierIp = &v + return s +} + // SetIpOwnerId sets the IpOwnerId field's value. func (s *InstanceNetworkInterfaceAssociation) SetIpOwnerId(v string) *InstanceNetworkInterfaceAssociation { s.IpOwnerId = &v @@ -80751,6 +84522,13 @@ func (s *InstanceNetworkInterfaceAttachment) SetStatus(v string) *InstanceNetwor type InstanceNetworkInterfaceSpecification struct { _ struct{} `type:"structure"` + // Indicates whether to assign a carrier IP address to the network interface. + // + // You can only assign a carrier IP address to a network interface that is in + // a subnet in a Wavelength Zone. For more information about carrier IP addresses, + // see Carrier IP addresses in the AWS Wavelength Developer Guide. + AssociateCarrierIpAddress *bool `type:"boolean"` + // Indicates whether to assign a public IPv4 address to an instance you launch // in a VPC. The public IP address can only be assigned to a network interface // for eth0, and can only be assigned to a new network interface, not an existing @@ -80841,6 +84619,12 @@ func (s InstanceNetworkInterfaceSpecification) GoString() string { return s.String() } +// SetAssociateCarrierIpAddress sets the AssociateCarrierIpAddress field's value. +func (s *InstanceNetworkInterfaceSpecification) SetAssociateCarrierIpAddress(v bool) *InstanceNetworkInterfaceSpecification { + s.AssociateCarrierIpAddress = &v + return s +} + // SetAssociatePublicIpAddress sets the AssociatePublicIpAddress field's value. func (s *InstanceNetworkInterfaceSpecification) SetAssociatePublicIpAddress(v bool) *InstanceNetworkInterfaceSpecification { s.AssociatePublicIpAddress = &v @@ -81471,6 +85255,9 @@ type InstanceTypeInfo struct { // Indicates whether the instance type is offered for spot or On-Demand. SupportedUsageClasses []*string `locationName:"supportedUsageClasses" locationNameList:"item" type:"list"` + // The supported virtualization types. + SupportedVirtualizationTypes []*string `locationName:"supportedVirtualizationTypes" locationNameList:"item" type:"list"` + // Describes the vCPU configurations for the instance type. VCpuInfo *VCpuInfo `locationName:"vCpuInfo" type:"structure"` } @@ -81611,6 +85398,12 @@ func (s *InstanceTypeInfo) SetSupportedUsageClasses(v []*string) *InstanceTypeIn return s } +// SetSupportedVirtualizationTypes sets the SupportedVirtualizationTypes field's value. +func (s *InstanceTypeInfo) SetSupportedVirtualizationTypes(v []*string) *InstanceTypeInfo { + s.SupportedVirtualizationTypes = v + return s +} + // SetVCpuInfo sets the VCpuInfo field's value. func (s *InstanceTypeInfo) SetVCpuInfo(v *VCpuInfo) *InstanceTypeInfo { s.VCpuInfo = v @@ -81807,9 +85600,7 @@ type IpPermission struct { // [VPC only] The IPv6 ranges. Ipv6Ranges []*Ipv6Range `locationName:"ipv6Ranges" locationNameList:"item" type:"list"` - // [VPC only] The prefix list IDs for an AWS service. With outbound rules, this - // is the AWS service to access through a VPC endpoint from instances associated - // with the security group. + // [VPC only] The prefix list IDs. PrefixListIds []*PrefixListId `locationName:"prefixListIds" locationNameList:"item" type:"list"` // The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. @@ -82596,7 +86387,7 @@ func (s *LaunchTemplateBlockDeviceMappingRequest) SetVirtualName(v string) *Laun // to configure the instance to run in On-Demand capacity or to run in any open // Capacity Reservation that has matching attributes (instance type, platform, // Availability Zone). Use the CapacityReservationTarget parameter to explicitly -// target a specific Capacity Reservation. +// target a specific Capacity Reservation or a Capacity Reservation group. type LaunchTemplateCapacityReservationSpecificationRequest struct { _ struct{} `type:"structure"` @@ -82610,7 +86401,8 @@ type LaunchTemplateCapacityReservationSpecificationRequest struct { // one is available. The instance runs in On-Demand capacity. CapacityReservationPreference *string `type:"string" enum:"CapacityReservationPreference"` - // Information about the target Capacity Reservation. + // Information about the target Capacity Reservation or Capacity Reservation + // group. CapacityReservationTarget *CapacityReservationTarget `type:"structure"` } @@ -82650,7 +86442,8 @@ type LaunchTemplateCapacityReservationSpecificationResponse struct { // one is available. The instance runs in On-Demand capacity. CapacityReservationPreference *string `locationName:"capacityReservationPreference" type:"string" enum:"CapacityReservationPreference"` - // Information about the target Capacity Reservation. + // Information about the target Capacity Reservation or Capacity Reservation + // group. CapacityReservationTarget *CapacityReservationTargetResponse `locationName:"capacityReservationTarget" type:"structure"` } @@ -82883,16 +86676,15 @@ type LaunchTemplateEbsBlockDeviceRequest struct { // a volume from a snapshot, you can't specify an encryption value. Encrypted *bool `type:"boolean"` - // The number of I/O operations per second (IOPS) that the volume supports. - // For io1, this represents the number of IOPS that are provisioned for the - // volume. For gp2, this represents the baseline performance of the volume and - // the rate at which the volume accumulates I/O credits for bursting. For more - // information about General Purpose SSD baseline performance, I/O credits, - // and bursting, see Amazon EBS Volume Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) + // The number of I/O operations per second (IOPS) to provision for an io1 or + // io2 volume, with a maximum ratio of 50 IOPS/GiB for io1, and 500 IOPS/GiB + // for io2. Range is 100 to 64,000 IOPS for volumes in most Regions. Maximum + // IOPS of 64,000 is guaranteed only on Nitro-based instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). + // Other instance families guarantee performance up to 32,000 IOPS. For more + // information, see Amazon EBS Volume Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) // in the Amazon Elastic Compute Cloud User Guide. // - // Condition: This parameter is required for requests to create io1 volumes; - // it is not used in requests to create gp2, st1, sc1, or standard volumes. + // This parameter is valid only for Provisioned IOPS SSD (io1 and io2) volumes. Iops *int64 `type:"integer"` // The ARN of the symmetric AWS Key Management Service (AWS KMS) CMK used for @@ -83386,6 +87178,15 @@ func (s *LaunchTemplateInstanceMetadataOptionsRequest) SetHttpTokens(v string) * type LaunchTemplateInstanceNetworkInterfaceSpecification struct { _ struct{} `type:"structure"` + // Indicates whether to associate a Carrier IP address with eth0 for a new network + // interface. + // + // Use this option when you launch an instance in a Wavelength Zone and want + // to associate a Carrier IP address with the network interface. For more information + // about Carrier IP addresses, see Carrier IP addresses (https://docs.aws.amazon.com/wavelength/latest/developerguide/how-wavelengths-work.html#provider-owned-ip) + // in the AWS Wavelength Developer Guide. + AssociateCarrierIpAddress *bool `locationName:"associateCarrierIpAddress" type:"boolean"` + // Indicates whether to associate a public IPv4 address with eth0 for a new // network interface. AssociatePublicIpAddress *bool `locationName:"associatePublicIpAddress" type:"boolean"` @@ -83437,6 +87238,12 @@ func (s LaunchTemplateInstanceNetworkInterfaceSpecification) GoString() string { return s.String() } +// SetAssociateCarrierIpAddress sets the AssociateCarrierIpAddress field's value. +func (s *LaunchTemplateInstanceNetworkInterfaceSpecification) SetAssociateCarrierIpAddress(v bool) *LaunchTemplateInstanceNetworkInterfaceSpecification { + s.AssociateCarrierIpAddress = &v + return s +} + // SetAssociatePublicIpAddress sets the AssociatePublicIpAddress field's value. func (s *LaunchTemplateInstanceNetworkInterfaceSpecification) SetAssociatePublicIpAddress(v bool) *LaunchTemplateInstanceNetworkInterfaceSpecification { s.AssociatePublicIpAddress = &v @@ -83519,6 +87326,14 @@ func (s *LaunchTemplateInstanceNetworkInterfaceSpecification) SetSubnetId(v stri type LaunchTemplateInstanceNetworkInterfaceSpecificationRequest struct { _ struct{} `type:"structure"` + // Associates a Carrier IP address with eth0 for a new network interface. + // + // Use this option when you launch an instance in a Wavelength Zone and want + // to associate a Carrier IP address with the network interface. For more information + // about Carrier IP addresses, see Carrier IP addresses (https://docs.aws.amazon.com/wavelength/latest/developerguide/how-wavelengths-work.html#provider-owned-ip) + // in the AWS Wavelength Developer Guide. + AssociateCarrierIpAddress *bool `type:"boolean"` + // Associates a public IPv4 address with eth0 for a new network interface. AssociatePublicIpAddress *bool `type:"boolean"` @@ -83578,6 +87393,12 @@ func (s LaunchTemplateInstanceNetworkInterfaceSpecificationRequest) GoString() s return s.String() } +// SetAssociateCarrierIpAddress sets the AssociateCarrierIpAddress field's value. +func (s *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest) SetAssociateCarrierIpAddress(v bool) *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest { + s.AssociateCarrierIpAddress = &v + return s +} + // SetAssociatePublicIpAddress sets the AssociatePublicIpAddress field's value. func (s *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest) SetAssociatePublicIpAddress(v bool) *LaunchTemplateInstanceNetworkInterfaceSpecificationRequest { s.AssociatePublicIpAddress = &v @@ -84998,6 +88819,111 @@ func (s *LocalGatewayVirtualInterfaceGroup) SetTags(v []*Tag) *LocalGatewayVirtu return s } +// Describes a managed prefix list. +type ManagedPrefixList struct { + _ struct{} `type:"structure"` + + // The IP address version. + AddressFamily *string `locationName:"addressFamily" type:"string"` + + // The maximum number of entries for the prefix list. + MaxEntries *int64 `locationName:"maxEntries" type:"integer"` + + // The ID of the owner of the prefix list. + OwnerId *string `locationName:"ownerId" type:"string"` + + // The Amazon Resource Name (ARN) for the prefix list. + PrefixListArn *string `locationName:"prefixListArn" min:"1" type:"string"` + + // The ID of the prefix list. + PrefixListId *string `locationName:"prefixListId" type:"string"` + + // The name of the prefix list. + PrefixListName *string `locationName:"prefixListName" type:"string"` + + // The state of the prefix list. + State *string `locationName:"state" type:"string" enum:"PrefixListState"` + + // The state message. + StateMessage *string `locationName:"stateMessage" type:"string"` + + // The tags for the prefix list. + Tags []*Tag `locationName:"tagSet" locationNameList:"item" type:"list"` + + // The version of the prefix list. + Version *int64 `locationName:"version" type:"long"` +} + +// String returns the string representation +func (s ManagedPrefixList) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ManagedPrefixList) GoString() string { + return s.String() +} + +// SetAddressFamily sets the AddressFamily field's value. +func (s *ManagedPrefixList) SetAddressFamily(v string) *ManagedPrefixList { + s.AddressFamily = &v + return s +} + +// SetMaxEntries sets the MaxEntries field's value. +func (s *ManagedPrefixList) SetMaxEntries(v int64) *ManagedPrefixList { + s.MaxEntries = &v + return s +} + +// SetOwnerId sets the OwnerId field's value. +func (s *ManagedPrefixList) SetOwnerId(v string) *ManagedPrefixList { + s.OwnerId = &v + return s +} + +// SetPrefixListArn sets the PrefixListArn field's value. +func (s *ManagedPrefixList) SetPrefixListArn(v string) *ManagedPrefixList { + s.PrefixListArn = &v + return s +} + +// SetPrefixListId sets the PrefixListId field's value. +func (s *ManagedPrefixList) SetPrefixListId(v string) *ManagedPrefixList { + s.PrefixListId = &v + return s +} + +// SetPrefixListName sets the PrefixListName field's value. +func (s *ManagedPrefixList) SetPrefixListName(v string) *ManagedPrefixList { + s.PrefixListName = &v + return s +} + +// SetState sets the State field's value. +func (s *ManagedPrefixList) SetState(v string) *ManagedPrefixList { + s.State = &v + return s +} + +// SetStateMessage sets the StateMessage field's value. +func (s *ManagedPrefixList) SetStateMessage(v string) *ManagedPrefixList { + s.StateMessage = &v + return s +} + +// SetTags sets the Tags field's value. +func (s *ManagedPrefixList) SetTags(v []*Tag) *ManagedPrefixList { + s.Tags = v + return s +} + +// SetVersion sets the Version field's value. +func (s *ManagedPrefixList) SetVersion(v int64) *ManagedPrefixList { + s.Version = &v + return s +} + // Describes the memory for the instance type. type MemoryInfo struct { _ struct{} `type:"structure"` @@ -85031,14 +88957,16 @@ type ModifyAvailabilityZoneGroupInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` - // The name of the Availability Zone Group. + // The name of the Availability Zone group, Local Zone group, or Wavelength + // Zone group. // // GroupName is a required field GroupName *string `type:"string" required:"true"` - // Indicates whether to enable or disable membership. The valid values are opted-in. - // You must contact AWS Support (https://console.aws.amazon.com/support/home#/case/create%3FissueType=customer-service%26serviceCode=general-info%26getting-started%26categoryCode=using-aws%26services) - // to disable an Availability Zone group. + // Indicates whether you are opted in to the Local Zone group or Wavelength + // Zone group. The only valid value is opted-in. You must contact AWS Support + // (https://console.aws.amazon.com/support/home#/case/create%3FissueType=customer-service%26serviceCode=general-info%26getting-started%26categoryCode=using-aws%26services) + // to opt out of a Local Zone group, or Wavelength Zone group. // // OptInStatus is a required field OptInStatus *string `type:"string" required:"true" enum:"ModifyAvailabilityZoneOptInStatus"` @@ -85594,6 +89522,9 @@ type ModifyFleetInput struct { // FleetId is a required field FleetId *string `type:"string" required:"true"` + // The launch template and overrides. + LaunchTemplateConfigs []*FleetLaunchTemplateConfigRequest `locationName:"LaunchTemplateConfig" locationNameList:"item" type:"list"` + // The size of the EC2 Fleet. // // TargetCapacitySpecification is a required field @@ -85619,6 +89550,16 @@ func (s *ModifyFleetInput) Validate() error { if s.TargetCapacitySpecification == nil { invalidParams.Add(request.NewErrParamRequired("TargetCapacitySpecification")) } + if s.LaunchTemplateConfigs != nil { + for i, v := range s.LaunchTemplateConfigs { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "LaunchTemplateConfigs", i), err.(request.ErrInvalidParams)) + } + } + } if s.TargetCapacitySpecification != nil { if err := s.TargetCapacitySpecification.Validate(); err != nil { invalidParams.AddNested("TargetCapacitySpecification", err.(request.ErrInvalidParams)) @@ -85649,6 +89590,12 @@ func (s *ModifyFleetInput) SetFleetId(v string) *ModifyFleetInput { return s } +// SetLaunchTemplateConfigs sets the LaunchTemplateConfigs field's value. +func (s *ModifyFleetInput) SetLaunchTemplateConfigs(v []*FleetLaunchTemplateConfigRequest) *ModifyFleetInput { + s.LaunchTemplateConfigs = v + return s +} + // SetTargetCapacitySpecification sets the TargetCapacitySpecification field's value. func (s *ModifyFleetInput) SetTargetCapacitySpecification(v *TargetCapacitySpecificationRequest) *ModifyFleetInput { s.TargetCapacitySpecification = v @@ -86269,7 +90216,7 @@ type ModifyInstanceAttributeInput struct { // // To add instance store volumes to an Amazon EBS-backed instance, you must // add them when you launch the instance. For more information, see Updating - // the Block Device Mapping when Launching an Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html#Using_OverridingAMIBDM) + // the block device mapping when launching an instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html#Using_OverridingAMIBDM) // in the Amazon Elastic Compute Cloud User Guide. BlockDeviceMappings []*InstanceBlockDeviceMappingSpecification `locationName:"blockDeviceMapping" locationNameList:"item" type:"list"` @@ -86312,7 +90259,7 @@ type ModifyInstanceAttributeInput struct { InstanceInitiatedShutdownBehavior *AttributeValue `locationName:"instanceInitiatedShutdownBehavior" type:"structure"` // Changes the instance type to the specified value. For more information, see - // Instance Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html). + // Instance types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html). // If the instance type is not valid, the error returned is InvalidInstanceAttributeValue. InstanceType *AttributeValue `locationName:"instanceType" type:"structure"` @@ -87120,6 +91067,135 @@ func (s *ModifyLaunchTemplateOutput) SetLaunchTemplate(v *LaunchTemplate) *Modif return s } +type ModifyManagedPrefixListInput struct { + _ struct{} `type:"structure"` + + // One or more entries to add to the prefix list. + AddEntries []*AddPrefixListEntry `locationName:"AddEntry" type:"list"` + + // The current version of the prefix list. + CurrentVersion *int64 `type:"long"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The ID of the prefix list. + // + // PrefixListId is a required field + PrefixListId *string `type:"string" required:"true"` + + // A name for the prefix list. + PrefixListName *string `type:"string"` + + // One or more entries to remove from the prefix list. + RemoveEntries []*RemovePrefixListEntry `locationName:"RemoveEntry" type:"list"` +} + +// String returns the string representation +func (s ModifyManagedPrefixListInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ModifyManagedPrefixListInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ModifyManagedPrefixListInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ModifyManagedPrefixListInput"} + if s.PrefixListId == nil { + invalidParams.Add(request.NewErrParamRequired("PrefixListId")) + } + if s.AddEntries != nil { + for i, v := range s.AddEntries { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "AddEntries", i), err.(request.ErrInvalidParams)) + } + } + } + if s.RemoveEntries != nil { + for i, v := range s.RemoveEntries { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "RemoveEntries", i), err.(request.ErrInvalidParams)) + } + } + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetAddEntries sets the AddEntries field's value. +func (s *ModifyManagedPrefixListInput) SetAddEntries(v []*AddPrefixListEntry) *ModifyManagedPrefixListInput { + s.AddEntries = v + return s +} + +// SetCurrentVersion sets the CurrentVersion field's value. +func (s *ModifyManagedPrefixListInput) SetCurrentVersion(v int64) *ModifyManagedPrefixListInput { + s.CurrentVersion = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *ModifyManagedPrefixListInput) SetDryRun(v bool) *ModifyManagedPrefixListInput { + s.DryRun = &v + return s +} + +// SetPrefixListId sets the PrefixListId field's value. +func (s *ModifyManagedPrefixListInput) SetPrefixListId(v string) *ModifyManagedPrefixListInput { + s.PrefixListId = &v + return s +} + +// SetPrefixListName sets the PrefixListName field's value. +func (s *ModifyManagedPrefixListInput) SetPrefixListName(v string) *ModifyManagedPrefixListInput { + s.PrefixListName = &v + return s +} + +// SetRemoveEntries sets the RemoveEntries field's value. +func (s *ModifyManagedPrefixListInput) SetRemoveEntries(v []*RemovePrefixListEntry) *ModifyManagedPrefixListInput { + s.RemoveEntries = v + return s +} + +type ModifyManagedPrefixListOutput struct { + _ struct{} `type:"structure"` + + // Information about the prefix list. + PrefixList *ManagedPrefixList `locationName:"prefixList" type:"structure"` +} + +// String returns the string representation +func (s ModifyManagedPrefixListOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ModifyManagedPrefixListOutput) GoString() string { + return s.String() +} + +// SetPrefixList sets the PrefixList field's value. +func (s *ModifyManagedPrefixListOutput) SetPrefixList(v *ManagedPrefixList) *ModifyManagedPrefixListOutput { + s.PrefixList = v + return s +} + // Contains the parameters for ModifyNetworkInterfaceAttribute. type ModifyNetworkInterfaceAttributeInput struct { _ struct{} `type:"structure"` @@ -87435,6 +91511,12 @@ type ModifySpotFleetRequestInput struct { // the Spot Fleet. ExcessCapacityTerminationPolicy *string `locationName:"excessCapacityTerminationPolicy" type:"string" enum:"ExcessCapacityTerminationPolicy"` + // The launch template and overrides. You can only use this parameter if you + // specified a launch template (LaunchTemplateConfigs) in your Spot Fleet request. + // If you specified LaunchSpecifications in your Spot Fleet request, then omit + // this parameter. + LaunchTemplateConfigs []*LaunchTemplateConfig `locationName:"LaunchTemplateConfig" locationNameList:"item" type:"list"` + // The number of On-Demand Instances in the fleet. OnDemandTargetCapacity *int64 `type:"integer"` @@ -87463,6 +91545,16 @@ func (s *ModifySpotFleetRequestInput) Validate() error { if s.SpotFleetRequestId == nil { invalidParams.Add(request.NewErrParamRequired("SpotFleetRequestId")) } + if s.LaunchTemplateConfigs != nil { + for i, v := range s.LaunchTemplateConfigs { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "LaunchTemplateConfigs", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -87476,6 +91568,12 @@ func (s *ModifySpotFleetRequestInput) SetExcessCapacityTerminationPolicy(v strin return s } +// SetLaunchTemplateConfigs sets the LaunchTemplateConfigs field's value. +func (s *ModifySpotFleetRequestInput) SetLaunchTemplateConfigs(v []*LaunchTemplateConfig) *ModifySpotFleetRequestInput { + s.LaunchTemplateConfigs = v + return s +} + // SetOnDemandTargetCapacity sets the OnDemandTargetCapacity field's value. func (s *ModifySpotFleetRequestInput) SetOnDemandTargetCapacity(v int64) *ModifySpotFleetRequestInput { s.OnDemandTargetCapacity = &v @@ -87531,8 +91629,20 @@ type ModifySubnetAttributeInput struct { // or later of the Amazon EC2 API. AssignIpv6AddressOnCreation *AttributeBooleanValue `type:"structure"` - // Specify true to indicate that ENIs attached to instances created in the specified - // subnet should be assigned a public IPv4 address. + // The customer-owned IPv4 address pool associated with the subnet. + // + // You must set this value when you specify true for MapCustomerOwnedIpOnLaunch. + CustomerOwnedIpv4Pool *string `type:"string"` + + // Specify true to indicate that network interfaces attached to instances created + // in the specified subnet should be assigned a customer-owned IPv4 address. + // + // When this value is true, you must specify the customer-owned IP pool using + // CustomerOwnedIpv4Pool. + MapCustomerOwnedIpOnLaunch *AttributeBooleanValue `type:"structure"` + + // Specify true to indicate that network interfaces attached to instances created + // in the specified subnet should be assigned a public IPv4 address. MapPublicIpOnLaunch *AttributeBooleanValue `type:"structure"` // The ID of the subnet. @@ -87570,6 +91680,18 @@ func (s *ModifySubnetAttributeInput) SetAssignIpv6AddressOnCreation(v *Attribute return s } +// SetCustomerOwnedIpv4Pool sets the CustomerOwnedIpv4Pool field's value. +func (s *ModifySubnetAttributeInput) SetCustomerOwnedIpv4Pool(v string) *ModifySubnetAttributeInput { + s.CustomerOwnedIpv4Pool = &v + return s +} + +// SetMapCustomerOwnedIpOnLaunch sets the MapCustomerOwnedIpOnLaunch field's value. +func (s *ModifySubnetAttributeInput) SetMapCustomerOwnedIpOnLaunch(v *AttributeBooleanValue) *ModifySubnetAttributeInput { + s.MapCustomerOwnedIpOnLaunch = v + return s +} + // SetMapPublicIpOnLaunch sets the MapPublicIpOnLaunch field's value. func (s *ModifySubnetAttributeInput) SetMapPublicIpOnLaunch(v *AttributeBooleanValue) *ModifySubnetAttributeInput { s.MapPublicIpOnLaunch = v @@ -88003,6 +92125,282 @@ func (s *ModifyTrafficMirrorSessionOutput) SetTrafficMirrorSession(v *TrafficMir return s } +type ModifyTransitGatewayInput struct { + _ struct{} `type:"structure"` + + // The description for the transit gateway. + Description *string `type:"string"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The options to modify. + Options *ModifyTransitGatewayOptions `type:"structure"` + + // The ID of the transit gateway. + // + // TransitGatewayId is a required field + TransitGatewayId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s ModifyTransitGatewayInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ModifyTransitGatewayInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ModifyTransitGatewayInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ModifyTransitGatewayInput"} + if s.TransitGatewayId == nil { + invalidParams.Add(request.NewErrParamRequired("TransitGatewayId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDescription sets the Description field's value. +func (s *ModifyTransitGatewayInput) SetDescription(v string) *ModifyTransitGatewayInput { + s.Description = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *ModifyTransitGatewayInput) SetDryRun(v bool) *ModifyTransitGatewayInput { + s.DryRun = &v + return s +} + +// SetOptions sets the Options field's value. +func (s *ModifyTransitGatewayInput) SetOptions(v *ModifyTransitGatewayOptions) *ModifyTransitGatewayInput { + s.Options = v + return s +} + +// SetTransitGatewayId sets the TransitGatewayId field's value. +func (s *ModifyTransitGatewayInput) SetTransitGatewayId(v string) *ModifyTransitGatewayInput { + s.TransitGatewayId = &v + return s +} + +// The transit gateway options. +type ModifyTransitGatewayOptions struct { + _ struct{} `type:"structure"` + + // The ID of the default association route table. + AssociationDefaultRouteTableId *string `type:"string"` + + // Enable or disable automatic acceptance of attachment requests. + AutoAcceptSharedAttachments *string `type:"string" enum:"AutoAcceptSharedAttachmentsValue"` + + // Enable or disable automatic association with the default association route + // table. + DefaultRouteTableAssociation *string `type:"string" enum:"DefaultRouteTableAssociationValue"` + + // Enable or disable automatic propagation of routes to the default propagation + // route table. + DefaultRouteTablePropagation *string `type:"string" enum:"DefaultRouteTablePropagationValue"` + + // Enable or disable DNS support. + DnsSupport *string `type:"string" enum:"DnsSupportValue"` + + // The ID of the default propagation route table. + PropagationDefaultRouteTableId *string `type:"string"` + + // Enable or disable Equal Cost Multipath Protocol support. + VpnEcmpSupport *string `type:"string" enum:"VpnEcmpSupportValue"` +} + +// String returns the string representation +func (s ModifyTransitGatewayOptions) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ModifyTransitGatewayOptions) GoString() string { + return s.String() +} + +// SetAssociationDefaultRouteTableId sets the AssociationDefaultRouteTableId field's value. +func (s *ModifyTransitGatewayOptions) SetAssociationDefaultRouteTableId(v string) *ModifyTransitGatewayOptions { + s.AssociationDefaultRouteTableId = &v + return s +} + +// SetAutoAcceptSharedAttachments sets the AutoAcceptSharedAttachments field's value. +func (s *ModifyTransitGatewayOptions) SetAutoAcceptSharedAttachments(v string) *ModifyTransitGatewayOptions { + s.AutoAcceptSharedAttachments = &v + return s +} + +// SetDefaultRouteTableAssociation sets the DefaultRouteTableAssociation field's value. +func (s *ModifyTransitGatewayOptions) SetDefaultRouteTableAssociation(v string) *ModifyTransitGatewayOptions { + s.DefaultRouteTableAssociation = &v + return s +} + +// SetDefaultRouteTablePropagation sets the DefaultRouteTablePropagation field's value. +func (s *ModifyTransitGatewayOptions) SetDefaultRouteTablePropagation(v string) *ModifyTransitGatewayOptions { + s.DefaultRouteTablePropagation = &v + return s +} + +// SetDnsSupport sets the DnsSupport field's value. +func (s *ModifyTransitGatewayOptions) SetDnsSupport(v string) *ModifyTransitGatewayOptions { + s.DnsSupport = &v + return s +} + +// SetPropagationDefaultRouteTableId sets the PropagationDefaultRouteTableId field's value. +func (s *ModifyTransitGatewayOptions) SetPropagationDefaultRouteTableId(v string) *ModifyTransitGatewayOptions { + s.PropagationDefaultRouteTableId = &v + return s +} + +// SetVpnEcmpSupport sets the VpnEcmpSupport field's value. +func (s *ModifyTransitGatewayOptions) SetVpnEcmpSupport(v string) *ModifyTransitGatewayOptions { + s.VpnEcmpSupport = &v + return s +} + +type ModifyTransitGatewayOutput struct { + _ struct{} `type:"structure"` + + // Describes a transit gateway. + TransitGateway *TransitGateway `locationName:"transitGateway" type:"structure"` +} + +// String returns the string representation +func (s ModifyTransitGatewayOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ModifyTransitGatewayOutput) GoString() string { + return s.String() +} + +// SetTransitGateway sets the TransitGateway field's value. +func (s *ModifyTransitGatewayOutput) SetTransitGateway(v *TransitGateway) *ModifyTransitGatewayOutput { + s.TransitGateway = v + return s +} + +type ModifyTransitGatewayPrefixListReferenceInput struct { + _ struct{} `type:"structure"` + + // Indicates whether to drop traffic that matches this route. + Blackhole *bool `type:"boolean"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The ID of the prefix list. + // + // PrefixListId is a required field + PrefixListId *string `type:"string" required:"true"` + + // The ID of the attachment to which traffic is routed. + TransitGatewayAttachmentId *string `type:"string"` + + // The ID of the transit gateway route table. + // + // TransitGatewayRouteTableId is a required field + TransitGatewayRouteTableId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s ModifyTransitGatewayPrefixListReferenceInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ModifyTransitGatewayPrefixListReferenceInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ModifyTransitGatewayPrefixListReferenceInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ModifyTransitGatewayPrefixListReferenceInput"} + if s.PrefixListId == nil { + invalidParams.Add(request.NewErrParamRequired("PrefixListId")) + } + if s.TransitGatewayRouteTableId == nil { + invalidParams.Add(request.NewErrParamRequired("TransitGatewayRouteTableId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetBlackhole sets the Blackhole field's value. +func (s *ModifyTransitGatewayPrefixListReferenceInput) SetBlackhole(v bool) *ModifyTransitGatewayPrefixListReferenceInput { + s.Blackhole = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *ModifyTransitGatewayPrefixListReferenceInput) SetDryRun(v bool) *ModifyTransitGatewayPrefixListReferenceInput { + s.DryRun = &v + return s +} + +// SetPrefixListId sets the PrefixListId field's value. +func (s *ModifyTransitGatewayPrefixListReferenceInput) SetPrefixListId(v string) *ModifyTransitGatewayPrefixListReferenceInput { + s.PrefixListId = &v + return s +} + +// SetTransitGatewayAttachmentId sets the TransitGatewayAttachmentId field's value. +func (s *ModifyTransitGatewayPrefixListReferenceInput) SetTransitGatewayAttachmentId(v string) *ModifyTransitGatewayPrefixListReferenceInput { + s.TransitGatewayAttachmentId = &v + return s +} + +// SetTransitGatewayRouteTableId sets the TransitGatewayRouteTableId field's value. +func (s *ModifyTransitGatewayPrefixListReferenceInput) SetTransitGatewayRouteTableId(v string) *ModifyTransitGatewayPrefixListReferenceInput { + s.TransitGatewayRouteTableId = &v + return s +} + +type ModifyTransitGatewayPrefixListReferenceOutput struct { + _ struct{} `type:"structure"` + + // Information about the prefix list reference. + TransitGatewayPrefixListReference *TransitGatewayPrefixListReference `locationName:"transitGatewayPrefixListReference" type:"structure"` +} + +// String returns the string representation +func (s ModifyTransitGatewayPrefixListReferenceOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ModifyTransitGatewayPrefixListReferenceOutput) GoString() string { + return s.String() +} + +// SetTransitGatewayPrefixListReference sets the TransitGatewayPrefixListReference field's value. +func (s *ModifyTransitGatewayPrefixListReferenceOutput) SetTransitGatewayPrefixListReference(v *TransitGatewayPrefixListReference) *ModifyTransitGatewayPrefixListReferenceOutput { + s.TransitGatewayPrefixListReference = v + return s +} + type ModifyTransitGatewayVpcAttachmentInput struct { _ struct{} `type:"structure"` @@ -88223,8 +92621,8 @@ type ModifyVolumeInput struct { // The target IOPS rate of the volume. // - // This is only valid for Provisioned IOPS SSD (io1) volumes. For more information, - // see Provisioned IOPS SSD (io1) Volumes (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html#EBSVolumeTypes_piops). + // This is only valid for Provisioned IOPS SSD (io1 and io2) volumes. For moreinformation, + // see Provisioned IOPS SSD (io1 and io2) volumes (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html#EBSVolumeTypes_piops). // // Default: If no IOPS value is specified, the existing value is retained. Iops *int64 `type:"integer"` @@ -89136,6 +93534,123 @@ func (s *ModifyVpnConnectionInput) SetVpnGatewayId(v string) *ModifyVpnConnectio return s } +type ModifyVpnConnectionOptionsInput struct { + _ struct{} `type:"structure"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The IPv4 CIDR on the customer gateway (on-premises) side of the VPN connection. + // + // Default: 0.0.0.0/0 + LocalIpv4NetworkCidr *string `type:"string"` + + // The IPv6 CIDR on the customer gateway (on-premises) side of the VPN connection. + // + // Default: ::/0 + LocalIpv6NetworkCidr *string `type:"string"` + + // The IPv4 CIDR on the AWS side of the VPN connection. + // + // Default: 0.0.0.0/0 + RemoteIpv4NetworkCidr *string `type:"string"` + + // The IPv6 CIDR on the AWS side of the VPN connection. + // + // Default: ::/0 + RemoteIpv6NetworkCidr *string `type:"string"` + + // The ID of the Site-to-Site VPN VPN connection. + // + // VpnConnectionId is a required field + VpnConnectionId *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s ModifyVpnConnectionOptionsInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ModifyVpnConnectionOptionsInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ModifyVpnConnectionOptionsInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ModifyVpnConnectionOptionsInput"} + if s.VpnConnectionId == nil { + invalidParams.Add(request.NewErrParamRequired("VpnConnectionId")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetDryRun sets the DryRun field's value. +func (s *ModifyVpnConnectionOptionsInput) SetDryRun(v bool) *ModifyVpnConnectionOptionsInput { + s.DryRun = &v + return s +} + +// SetLocalIpv4NetworkCidr sets the LocalIpv4NetworkCidr field's value. +func (s *ModifyVpnConnectionOptionsInput) SetLocalIpv4NetworkCidr(v string) *ModifyVpnConnectionOptionsInput { + s.LocalIpv4NetworkCidr = &v + return s +} + +// SetLocalIpv6NetworkCidr sets the LocalIpv6NetworkCidr field's value. +func (s *ModifyVpnConnectionOptionsInput) SetLocalIpv6NetworkCidr(v string) *ModifyVpnConnectionOptionsInput { + s.LocalIpv6NetworkCidr = &v + return s +} + +// SetRemoteIpv4NetworkCidr sets the RemoteIpv4NetworkCidr field's value. +func (s *ModifyVpnConnectionOptionsInput) SetRemoteIpv4NetworkCidr(v string) *ModifyVpnConnectionOptionsInput { + s.RemoteIpv4NetworkCidr = &v + return s +} + +// SetRemoteIpv6NetworkCidr sets the RemoteIpv6NetworkCidr field's value. +func (s *ModifyVpnConnectionOptionsInput) SetRemoteIpv6NetworkCidr(v string) *ModifyVpnConnectionOptionsInput { + s.RemoteIpv6NetworkCidr = &v + return s +} + +// SetVpnConnectionId sets the VpnConnectionId field's value. +func (s *ModifyVpnConnectionOptionsInput) SetVpnConnectionId(v string) *ModifyVpnConnectionOptionsInput { + s.VpnConnectionId = &v + return s +} + +type ModifyVpnConnectionOptionsOutput struct { + _ struct{} `type:"structure"` + + // Describes a VPN connection. + VpnConnection *VpnConnection `locationName:"vpnConnection" type:"structure"` +} + +// String returns the string representation +func (s ModifyVpnConnectionOptionsOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ModifyVpnConnectionOptionsOutput) GoString() string { + return s.String() +} + +// SetVpnConnection sets the VpnConnection field's value. +func (s *ModifyVpnConnectionOptionsOutput) SetVpnConnection(v *VpnConnection) *ModifyVpnConnectionOptionsOutput { + s.VpnConnection = v + return s +} + type ModifyVpnConnectionOutput struct { _ struct{} `type:"structure"` @@ -89351,6 +93866,14 @@ func (s *ModifyVpnTunnelOptionsOutput) SetVpnConnection(v *VpnConnection) *Modif type ModifyVpnTunnelOptionsSpecification struct { _ struct{} `type:"structure"` + // The action to take after DPD timeout occurs. Specify restart to restart the + // IKE initiation. Specify clear to end the IKE session. + // + // Valid Values: clear | none | restart + // + // Default: clear + DPDTimeoutAction *string `type:"string"` + // The number of seconds after which a DPD timeout occurs. // // Constraints: A value between 0 and 30. @@ -89366,19 +93889,19 @@ type ModifyVpnTunnelOptionsSpecification struct { // One or more Diffie-Hellman group numbers that are permitted for the VPN tunnel // for phase 1 IKE negotiations. // - // Valid values: 2 | 14 | 15 | 16 | 17 | 18 | 22 | 23 | 24 + // Valid values: 2 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 Phase1DHGroupNumbers []*Phase1DHGroupNumbersRequestListValue `locationName:"Phase1DHGroupNumber" locationNameList:"item" type:"list"` // One or more encryption algorithms that are permitted for the VPN tunnel for // phase 1 IKE negotiations. // - // Valid values: AES128 | AES256 + // Valid values: AES128 | AES256 | AES128-GCM-16 | AES256-GCM-16 Phase1EncryptionAlgorithms []*Phase1EncryptionAlgorithmsRequestListValue `locationName:"Phase1EncryptionAlgorithm" locationNameList:"item" type:"list"` // One or more integrity algorithms that are permitted for the VPN tunnel for // phase 1 IKE negotiations. // - // Valid values: SHA1 | SHA2-256 + // Valid values: SHA1 | SHA2-256 | SHA2-384 | SHA2-512 Phase1IntegrityAlgorithms []*Phase1IntegrityAlgorithmsRequestListValue `locationName:"Phase1IntegrityAlgorithm" locationNameList:"item" type:"list"` // The lifetime for phase 1 of the IKE negotiation, in seconds. @@ -89391,19 +93914,19 @@ type ModifyVpnTunnelOptionsSpecification struct { // One or more Diffie-Hellman group numbers that are permitted for the VPN tunnel // for phase 2 IKE negotiations. // - // Valid values: 2 | 5 | 14 | 15 | 16 | 17 | 18 | 22 | 23 | 24 + // Valid values: 2 | 5 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 Phase2DHGroupNumbers []*Phase2DHGroupNumbersRequestListValue `locationName:"Phase2DHGroupNumber" locationNameList:"item" type:"list"` // One or more encryption algorithms that are permitted for the VPN tunnel for // phase 2 IKE negotiations. // - // Valid values: AES128 | AES256 + // Valid values: AES128 | AES256 | AES128-GCM-16 | AES256-GCM-16 Phase2EncryptionAlgorithms []*Phase2EncryptionAlgorithmsRequestListValue `locationName:"Phase2EncryptionAlgorithm" locationNameList:"item" type:"list"` // One or more integrity algorithms that are permitted for the VPN tunnel for // phase 2 IKE negotiations. // - // Valid values: SHA1 | SHA2-256 + // Valid values: SHA1 | SHA2-256 | SHA2-384 | SHA2-512 Phase2IntegrityAlgorithms []*Phase2IntegrityAlgorithmsRequestListValue `locationName:"Phase2IntegrityAlgorithm" locationNameList:"item" type:"list"` // The lifetime for phase 2 of the IKE negotiation, in seconds. @@ -89446,7 +93969,16 @@ type ModifyVpnTunnelOptionsSpecification struct { // Default: 1024 ReplayWindowSize *int64 `type:"integer"` - // The range of inside IP addresses for the tunnel. Any specified CIDR blocks + // The action to take when the establishing the tunnel for the VPN connection. + // By default, your customer gateway device must initiate the IKE negotiation + // and bring up the tunnel. Specify start for AWS to initiate the IKE negotiation. + // + // Valid Values: add | start + // + // Default: add + StartupAction *string `type:"string"` + + // The range of inside IPv4 addresses for the tunnel. Any specified CIDR blocks // must be unique across all VPN connections that use the same virtual private // gateway. // @@ -89467,6 +93999,12 @@ type ModifyVpnTunnelOptionsSpecification struct { // // * 169.254.169.252/30 TunnelInsideCidr *string `type:"string"` + + // The range of inside IPv6 addresses for the tunnel. Any specified CIDR blocks + // must be unique across all VPN connections that use the same transit gateway. + // + // Constraints: A size /126 CIDR block from the local fd00::/8 range. + TunnelInsideIpv6Cidr *string `type:"string"` } // String returns the string representation @@ -89479,6 +94017,12 @@ func (s ModifyVpnTunnelOptionsSpecification) GoString() string { return s.String() } +// SetDPDTimeoutAction sets the DPDTimeoutAction field's value. +func (s *ModifyVpnTunnelOptionsSpecification) SetDPDTimeoutAction(v string) *ModifyVpnTunnelOptionsSpecification { + s.DPDTimeoutAction = &v + return s +} + // SetDPDTimeoutSeconds sets the DPDTimeoutSeconds field's value. func (s *ModifyVpnTunnelOptionsSpecification) SetDPDTimeoutSeconds(v int64) *ModifyVpnTunnelOptionsSpecification { s.DPDTimeoutSeconds = &v @@ -89563,12 +94107,24 @@ func (s *ModifyVpnTunnelOptionsSpecification) SetReplayWindowSize(v int64) *Modi return s } +// SetStartupAction sets the StartupAction field's value. +func (s *ModifyVpnTunnelOptionsSpecification) SetStartupAction(v string) *ModifyVpnTunnelOptionsSpecification { + s.StartupAction = &v + return s +} + // SetTunnelInsideCidr sets the TunnelInsideCidr field's value. func (s *ModifyVpnTunnelOptionsSpecification) SetTunnelInsideCidr(v string) *ModifyVpnTunnelOptionsSpecification { s.TunnelInsideCidr = &v return s } +// SetTunnelInsideIpv6Cidr sets the TunnelInsideIpv6Cidr field's value. +func (s *ModifyVpnTunnelOptionsSpecification) SetTunnelInsideIpv6Cidr(v string) *ModifyVpnTunnelOptionsSpecification { + s.TunnelInsideIpv6Cidr = &v + return s +} + type MonitorInstancesInput struct { _ struct{} `type:"structure"` @@ -90202,6 +94758,9 @@ func (s *NetworkAclEntry) SetRuleNumber(v int64) *NetworkAclEntry { type NetworkInfo struct { _ struct{} `type:"structure"` + // Indicates whether Elastic Fabric Adapter (EFA) is supported. + EfaSupported *bool `locationName:"efaSupported" type:"boolean"` + // Indicates whether Elastic Network Adapter (ENA) is supported. EnaSupport *string `locationName:"enaSupport" type:"string" enum:"EnaSupport"` @@ -90231,6 +94790,12 @@ func (s NetworkInfo) GoString() string { return s.String() } +// SetEfaSupported sets the EfaSupported field's value. +func (s *NetworkInfo) SetEfaSupported(v bool) *NetworkInfo { + s.EfaSupported = &v + return s +} + // SetEnaSupport sets the EnaSupport field's value. func (s *NetworkInfo) SetEnaSupport(v string) *NetworkInfo { s.EnaSupport = &v @@ -90473,7 +95038,9 @@ func (s *NetworkInterface) SetVpcId(v string) *NetworkInterface { return s } -// Describes association information for an Elastic IP address (IPv4 only). +// Describes association information for an Elastic IP address (IPv4 only), +// or a Carrier IP address (for a network interface which resides in a subnet +// in a Wavelength Zone). type NetworkInterfaceAssociation struct { _ struct{} `type:"structure"` @@ -90483,13 +95050,23 @@ type NetworkInterfaceAssociation struct { // The association ID. AssociationId *string `locationName:"associationId" type:"string"` + // The carrier IP address associated with the network interface. + // + // This option is only available when the network interface is in a subnet which + // is associated with a Wavelength Zone. + CarrierIp *string `locationName:"carrierIp" type:"string"` + + // The customer-owned IP address associated with the network interface. + CustomerOwnedIp *string `locationName:"customerOwnedIp" type:"string"` + // The ID of the Elastic IP address owner. IpOwnerId *string `locationName:"ipOwnerId" type:"string"` // The public DNS name. PublicDnsName *string `locationName:"publicDnsName" type:"string"` - // The address of the Elastic IP address bound to the network interface. + // The address of the Elastic IP address or Carrier IP address bound to the + // network interface. PublicIp *string `locationName:"publicIp" type:"string"` } @@ -90515,6 +95092,18 @@ func (s *NetworkInterfaceAssociation) SetAssociationId(v string) *NetworkInterfa return s } +// SetCarrierIp sets the CarrierIp field's value. +func (s *NetworkInterfaceAssociation) SetCarrierIp(v string) *NetworkInterfaceAssociation { + s.CarrierIp = &v + return s +} + +// SetCustomerOwnedIp sets the CustomerOwnedIp field's value. +func (s *NetworkInterfaceAssociation) SetCustomerOwnedIp(v string) *NetworkInterfaceAssociation { + s.CustomerOwnedIp = &v + return s +} + // SetIpOwnerId sets the IpOwnerId field's value. func (s *NetworkInterfaceAssociation) SetIpOwnerId(v string) *NetworkInterfaceAssociation { s.IpOwnerId = &v @@ -91848,6 +96437,72 @@ func (s *PrefixList) SetPrefixListName(v string) *PrefixList { return s } +// Describes the resource with which a prefix list is associated. +type PrefixListAssociation struct { + _ struct{} `type:"structure"` + + // The ID of the resource. + ResourceId *string `locationName:"resourceId" type:"string"` + + // The owner of the resource. + ResourceOwner *string `locationName:"resourceOwner" type:"string"` +} + +// String returns the string representation +func (s PrefixListAssociation) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PrefixListAssociation) GoString() string { + return s.String() +} + +// SetResourceId sets the ResourceId field's value. +func (s *PrefixListAssociation) SetResourceId(v string) *PrefixListAssociation { + s.ResourceId = &v + return s +} + +// SetResourceOwner sets the ResourceOwner field's value. +func (s *PrefixListAssociation) SetResourceOwner(v string) *PrefixListAssociation { + s.ResourceOwner = &v + return s +} + +// Describes a prefix list entry. +type PrefixListEntry struct { + _ struct{} `type:"structure"` + + // The CIDR block. + Cidr *string `locationName:"cidr" type:"string"` + + // The description. + Description *string `locationName:"description" type:"string"` +} + +// String returns the string representation +func (s PrefixListEntry) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PrefixListEntry) GoString() string { + return s.String() +} + +// SetCidr sets the Cidr field's value. +func (s *PrefixListEntry) SetCidr(v string) *PrefixListEntry { + s.Cidr = &v + return s +} + +// SetDescription sets the Description field's value. +func (s *PrefixListEntry) SetDescription(v string) *PrefixListEntry { + s.Description = &v + return s +} + // Describes a prefix list ID. type PrefixListId struct { _ struct{} `type:"structure"` @@ -92264,6 +96919,9 @@ type ProvisionByoipCidrInput struct { // it is UnauthorizedOperation. DryRun *bool `type:"boolean"` + // The tags to apply to the address pool. + PoolTagSpecifications []*TagSpecification `locationName:"PoolTagSpecification" locationNameList:"item" type:"list"` + // (IPv6 only) Indicate whether the address range will be publicly advertised // to the internet. // @@ -92323,6 +96981,12 @@ func (s *ProvisionByoipCidrInput) SetDryRun(v bool) *ProvisionByoipCidrInput { return s } +// SetPoolTagSpecifications sets the PoolTagSpecifications field's value. +func (s *ProvisionByoipCidrInput) SetPoolTagSpecifications(v []*TagSpecification) *ProvisionByoipCidrInput { + s.PoolTagSpecifications = v + return s +} + // SetPubliclyAdvertisable sets the PubliclyAdvertisable field's value. func (s *ProvisionByoipCidrInput) SetPubliclyAdvertisable(v bool) *ProvisionByoipCidrInput { s.PubliclyAdvertisable = &v @@ -92431,6 +97095,11 @@ type PublicIpv4Pool struct { // A description of the address pool. Description *string `locationName:"description" type:"string"` + // The name of the location from which the address pool is advertised. A network + // border group is a unique set of Availability Zones or Local Zones from where + // AWS advertises public IP addresses. + NetworkBorderGroup *string `locationName:"networkBorderGroup" type:"string"` + // The address ranges. PoolAddressRanges []*PublicIpv4PoolRange `locationName:"poolAddressRangeSet" locationNameList:"item" type:"list"` @@ -92463,6 +97132,12 @@ func (s *PublicIpv4Pool) SetDescription(v string) *PublicIpv4Pool { return s } +// SetNetworkBorderGroup sets the NetworkBorderGroup field's value. +func (s *PublicIpv4Pool) SetNetworkBorderGroup(v string) *PublicIpv4Pool { + s.NetworkBorderGroup = &v + return s +} + // SetPoolAddressRanges sets the PoolAddressRanges field's value. func (s *PublicIpv4Pool) SetPoolAddressRanges(v []*PublicIpv4PoolRange) *PublicIpv4Pool { s.PoolAddressRanges = v @@ -92661,6 +97336,9 @@ type PurchaseHostReservationInput struct { // // OfferingId is a required field OfferingId *string `type:"string" required:"true"` + + // The tags to apply to the Dedicated Host Reservation during purchase. + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` } // String returns the string representation @@ -92719,6 +97397,12 @@ func (s *PurchaseHostReservationInput) SetOfferingId(v string) *PurchaseHostRese return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *PurchaseHostReservationInput) SetTagSpecifications(v []*TagSpecification) *PurchaseHostReservationInput { + s.TagSpecifications = v + return s +} + type PurchaseHostReservationOutput struct { _ struct{} `type:"structure"` @@ -93947,7 +98631,8 @@ type ReleaseAddressInput struct { // it is UnauthorizedOperation. DryRun *bool `locationName:"dryRun" type:"boolean"` - // The location that the IP address is released from. + // The set of Availability Zones, Local Zones, or Wavelength Zones from which + // AWS advertises IP addresses. // // If you provide an incorrect network border group, you will receive an InvalidAddress.NotFound // error. For more information, see Error Codes (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html). @@ -94080,6 +98765,45 @@ func (s *ReleaseHostsOutput) SetUnsuccessful(v []*UnsuccessfulItem) *ReleaseHost return s } +// An entry for a prefix list. +type RemovePrefixListEntry struct { + _ struct{} `type:"structure"` + + // The CIDR block. + // + // Cidr is a required field + Cidr *string `type:"string" required:"true"` +} + +// String returns the string representation +func (s RemovePrefixListEntry) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RemovePrefixListEntry) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *RemovePrefixListEntry) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RemovePrefixListEntry"} + if s.Cidr == nil { + invalidParams.Add(request.NewErrParamRequired("Cidr")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCidr sets the Cidr field's value. +func (s *RemovePrefixListEntry) SetCidr(v string) *RemovePrefixListEntry { + s.Cidr = &v + return s +} + type ReplaceIamInstanceProfileAssociationInput struct { _ struct{} `type:"structure"` @@ -94412,6 +99136,9 @@ func (s ReplaceNetworkAclEntryOutput) GoString() string { type ReplaceRouteInput struct { _ struct{} `type:"structure"` + // [IPv4 traffic only] The ID of a carrier gateway. + CarrierGatewayId *string `type:"string"` + // The IPv4 CIDR address block used for the destination match. The value that // you provide must match the CIDR of an existing route in the table. DestinationCidrBlock *string `locationName:"destinationCidrBlock" type:"string"` @@ -94420,6 +99147,9 @@ type ReplaceRouteInput struct { // you provide must match the CIDR of an existing route in the table. DestinationIpv6CidrBlock *string `locationName:"destinationIpv6CidrBlock" type:"string"` + // The ID of the prefix list for the route. + DestinationPrefixListId *string `type:"string"` + // Checks whether you have the required permissions for the action, without // actually making the request, and provides an error response. If you have // the required permissions, the error response is DryRunOperation. Otherwise, @@ -94482,6 +99212,12 @@ func (s *ReplaceRouteInput) Validate() error { return nil } +// SetCarrierGatewayId sets the CarrierGatewayId field's value. +func (s *ReplaceRouteInput) SetCarrierGatewayId(v string) *ReplaceRouteInput { + s.CarrierGatewayId = &v + return s +} + // SetDestinationCidrBlock sets the DestinationCidrBlock field's value. func (s *ReplaceRouteInput) SetDestinationCidrBlock(v string) *ReplaceRouteInput { s.DestinationCidrBlock = &v @@ -94494,6 +99230,12 @@ func (s *ReplaceRouteInput) SetDestinationIpv6CidrBlock(v string) *ReplaceRouteI return s } +// SetDestinationPrefixListId sets the DestinationPrefixListId field's value. +func (s *ReplaceRouteInput) SetDestinationPrefixListId(v string) *ReplaceRouteInput { + s.DestinationPrefixListId = &v + return s +} + // SetDryRun sets the DryRun field's value. func (s *ReplaceRouteInput) SetDryRun(v bool) *ReplaceRouteInput { s.DryRun = &v @@ -94934,8 +99676,8 @@ type RequestLaunchTemplateData struct { // in the Amazon Elastic Compute Cloud User Guide. CpuOptions *LaunchTemplateCpuOptionsRequest `type:"structure"` - // The credit option for CPU usage of the instance. Valid for T2 or T3 instances - // only. + // The credit option for CPU usage of the instance. Valid for T2, T3, or T3a + // instances only. CreditSpecification *CreditSpecificationRequest `type:"structure"` // If you set this parameter to true, you can't terminate the instance using @@ -95397,6 +100139,12 @@ type RequestSpotInstancesInput struct { // The default is the On-Demand price. SpotPrice *string `locationName:"spotPrice" type:"string"` + // The key-value pair for tagging the Spot Instance request on creation. The + // value for ResourceType must be spot-instances-request, otherwise the Spot + // Instance request fails. To tag the Spot Instance request after it has been + // created, see CreateTags (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html). + TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` + // The Spot Instance request type. // // Default: one-time @@ -95500,6 +100248,12 @@ func (s *RequestSpotInstancesInput) SetSpotPrice(v string) *RequestSpotInstances return s } +// SetTagSpecifications sets the TagSpecifications field's value. +func (s *RequestSpotInstancesInput) SetTagSpecifications(v []*TagSpecification) *RequestSpotInstancesInput { + s.TagSpecifications = v + return s +} + // SetType sets the Type field's value. func (s *RequestSpotInstancesInput) SetType(v string) *RequestSpotInstancesInput { s.Type = &v @@ -97387,6 +102141,107 @@ func (s *RestoreAddressToClassicOutput) SetStatus(v string) *RestoreAddressToCla return s } +type RestoreManagedPrefixListVersionInput struct { + _ struct{} `type:"structure"` + + // The current version number for the prefix list. + // + // CurrentVersion is a required field + CurrentVersion *int64 `type:"long" required:"true"` + + // Checks whether you have the required permissions for the action, without + // actually making the request, and provides an error response. If you have + // the required permissions, the error response is DryRunOperation. Otherwise, + // it is UnauthorizedOperation. + DryRun *bool `type:"boolean"` + + // The ID of the prefix list. + // + // PrefixListId is a required field + PrefixListId *string `type:"string" required:"true"` + + // The version to restore. + // + // PreviousVersion is a required field + PreviousVersion *int64 `type:"long" required:"true"` +} + +// String returns the string representation +func (s RestoreManagedPrefixListVersionInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RestoreManagedPrefixListVersionInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *RestoreManagedPrefixListVersionInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "RestoreManagedPrefixListVersionInput"} + if s.CurrentVersion == nil { + invalidParams.Add(request.NewErrParamRequired("CurrentVersion")) + } + if s.PrefixListId == nil { + invalidParams.Add(request.NewErrParamRequired("PrefixListId")) + } + if s.PreviousVersion == nil { + invalidParams.Add(request.NewErrParamRequired("PreviousVersion")) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetCurrentVersion sets the CurrentVersion field's value. +func (s *RestoreManagedPrefixListVersionInput) SetCurrentVersion(v int64) *RestoreManagedPrefixListVersionInput { + s.CurrentVersion = &v + return s +} + +// SetDryRun sets the DryRun field's value. +func (s *RestoreManagedPrefixListVersionInput) SetDryRun(v bool) *RestoreManagedPrefixListVersionInput { + s.DryRun = &v + return s +} + +// SetPrefixListId sets the PrefixListId field's value. +func (s *RestoreManagedPrefixListVersionInput) SetPrefixListId(v string) *RestoreManagedPrefixListVersionInput { + s.PrefixListId = &v + return s +} + +// SetPreviousVersion sets the PreviousVersion field's value. +func (s *RestoreManagedPrefixListVersionInput) SetPreviousVersion(v int64) *RestoreManagedPrefixListVersionInput { + s.PreviousVersion = &v + return s +} + +type RestoreManagedPrefixListVersionOutput struct { + _ struct{} `type:"structure"` + + // Information about the prefix list. + PrefixList *ManagedPrefixList `locationName:"prefixList" type:"structure"` +} + +// String returns the string representation +func (s RestoreManagedPrefixListVersionOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s RestoreManagedPrefixListVersionOutput) GoString() string { + return s.String() +} + +// SetPrefixList sets the PrefixList field's value. +func (s *RestoreManagedPrefixListVersionOutput) SetPrefixList(v *ManagedPrefixList) *RestoreManagedPrefixListVersionOutput { + s.PrefixList = v + return s +} + type RevokeClientVpnIngressInput struct { _ struct{} `type:"structure"` @@ -97767,6 +102622,9 @@ func (s RevokeSecurityGroupIngressOutput) GoString() string { type Route struct { _ struct{} `type:"structure"` + // The ID of the carrier gateway. + CarrierGatewayId *string `locationName:"carrierGatewayId" type:"string"` + // The IPv4 CIDR block used for the destination match. DestinationCidrBlock *string `locationName:"destinationCidrBlock" type:"string"` @@ -97829,6 +102687,12 @@ func (s Route) GoString() string { return s.String() } +// SetCarrierGatewayId sets the CarrierGatewayId field's value. +func (s *Route) SetCarrierGatewayId(v string) *Route { + s.CarrierGatewayId = &v + return s +} + // SetDestinationCidrBlock sets the DestinationCidrBlock field's value. func (s *Route) SetDestinationCidrBlock(v string) *Route { s.DestinationCidrBlock = &v @@ -98116,17 +102980,17 @@ type RunInstancesInput struct { // For more information, see Ensuring Idempotency (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html). // // Constraints: Maximum 64 ASCII characters - ClientToken *string `locationName:"clientToken" type:"string"` + ClientToken *string `locationName:"clientToken" type:"string" idempotencyToken:"true"` // The CPU options for the instance. For more information, see Optimizing CPU - // Options (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) + // options (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-optimize-cpu.html) // in the Amazon Elastic Compute Cloud User Guide. CpuOptions *CpuOptionsRequest `type:"structure"` // The credit option for CPU usage of the burstable performance instance. Valid // values are standard and unlimited. To change this attribute after launch, // use ModifyInstanceCreditSpecification (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifyInstanceCreditSpecification.html). - // For more information, see Burstable Performance Instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) + // For more information, see Burstable performance instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html) // in the Amazon Elastic Compute Cloud User Guide. // // Default: standard (T2 instances) or unlimited (T3/T3a instances) @@ -98165,10 +103029,12 @@ type RunInstancesInput struct { // An elastic inference accelerator to associate with the instance. Elastic // inference accelerators are a resource you can attach to your Amazon EC2 instances // to accelerate your Deep Learning (DL) inference workloads. + // + // You cannot specify accelerators from different generations in the same request. ElasticInferenceAccelerators []*ElasticInferenceAccelerator `locationName:"ElasticInferenceAccelerator" locationNameList:"item" type:"list"` // Indicates whether an instance is enabled for hibernation. For more information, - // see Hibernate Your Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) + // see Hibernate your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) // in the Amazon Elastic Compute Cloud User Guide. HibernationOptions *HibernationOptionsRequest `type:"structure"` @@ -98191,7 +103057,7 @@ type RunInstancesInput struct { // InstanceInterruptionBehavior is set to either hibernate or stop. InstanceMarketOptions *InstanceMarketOptionsRequest `type:"structure"` - // The instance type. For more information, see Instance Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) + // The instance type. For more information, see Instance types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html) // in the Amazon Elastic Compute Cloud User Guide. // // Default: m1.small @@ -98251,7 +103117,7 @@ type RunInstancesInput struct { MaxCount *int64 `type:"integer" required:"true"` // The metadata options for the instance. For more information, see Instance - // Metadata and User Data (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html). + // metadata and user data (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html). MetadataOptions *InstanceMetadataOptionsRequest `type:"structure"` // The minimum number of instances to launch. If you specify a minimum that @@ -98328,7 +103194,7 @@ type RunInstancesInput struct { TagSpecifications []*TagSpecification `locationName:"TagSpecification" locationNameList:"item" type:"list"` // The user data to make available to the instance. For more information, see - // Running Commands on Your Linux Instance at Launch (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) + // Running commands on your Linux instance at launch (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html) // (Linux) and Adding User Data (https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html#instancedata-add-user-data) // (Windows). If you are using a command line tool, base64-encoding is performed // for you, and you can load the text from a file. Otherwise, you must provide @@ -99319,19 +104185,15 @@ type ScheduledInstancesEbs struct { // only to instances that support them. Encrypted *bool `type:"boolean"` - // The number of I/O operations per second (IOPS) that the volume supports. - // For io1 volumes, this represents the number of IOPS that are provisioned - // for the volume. For gp2 volumes, this represents the baseline performance - // of the volume and the rate at which the volume accumulates I/O credits for - // bursting. For more information about gp2 baseline performance, I/O credits, - // and bursting, see Amazon EBS Volume Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) + // The number of I/O operations per second (IOPS) to provision for an io1 or + // io2 volume, with a maximum ratio of 50 IOPS/GiB for io1, and 500 IOPS/GiB + // for io2. Range is 100 to 64,000 IOPS for volumes in most Regions. Maximum + // IOPS of 64,000 is guaranteed only on Nitro-based instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). + // Other instance families guarantee performance up to 32,000 IOPS. For more + // information, see Amazon EBS Volume Types (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) // in the Amazon Elastic Compute Cloud User Guide. // - // Constraint: Range is 100-20000 IOPS for io1 volumes and 100-10000 IOPS for - // gp2 volumes. - // - // Condition: This parameter is required for requests to create io1volumes; - // it is not used in requests to create gp2, st1, sc1, or standard volumes. + // This parameter is valid only for Provisioned IOPS SSD (io1 and io2) volumes. Iops *int64 `type:"integer"` // The ID of the snapshot. @@ -99343,8 +104205,9 @@ type ScheduledInstancesEbs struct { // a volume size, the default is the snapshot size. VolumeSize *int64 `type:"integer"` - // The volume type. gp2 for General Purpose SSD, io1 for Provisioned IOPS SSD, - // Throughput Optimized HDD for st1, Cold HDD for sc1, or standard for Magnetic. + // The volume type. gp2 for General Purpose SSD, io1 or io2 for Provisioned + // IOPS SSD, Throughput Optimized HDD for st1, Cold HDD for sc1, or standard + // for Magnetic. // // Default: gp2 VolumeType *string `type:"string"` @@ -100103,7 +104966,10 @@ type SearchTransitGatewayRoutesInput struct { // // * attachment.resource-id - The resource id of the transit gateway attachment. // - // * attachment.resource-type - The attachment resource type (vpc | vpn). + // * attachment.resource-type - The attachment resource type. Valid values + // are vpc | vpn | direct-connect-gateway | peering. + // + // * prefix-list-id - The ID of the prefix list. // // * route-search.exact-match - The exact match of the specified filter. // @@ -100834,9 +105700,10 @@ type Snapshot struct { // key for the parent volume. KmsKeyId *string `locationName:"kmsKeyId" type:"string"` - // Value from an Amazon-maintained list (amazon | self | all | aws-marketplace - // | microsoft) of snapshot owners. Not to be confused with the user-configured - // AWS account alias, which is set from the IAM console. + // The AWS owner alias, as maintained by Amazon. The possible values are: amazon + // | self | all | aws-marketplace | microsoft. This AWS owner alias is not to + // be confused with the user-configured AWS account alias, which is set from + // the IAM console. OwnerAlias *string `locationName:"ownerAlias" type:"string"` // The AWS account ID of the EBS snapshot owner. @@ -100999,7 +105866,7 @@ type SnapshotDetail struct { // The URL used to access the disk image. Url *string `locationName:"url" type:"string"` - // The S3 bucket for the disk image. + // The Amazon S3 bucket for the disk image. UserBucket *UserBucketDetails `locationName:"userBucket" type:"structure"` } @@ -101089,7 +105956,7 @@ type SnapshotDiskContainer struct { // a https URL (https://..) or an Amazon S3 URL (s3://..). Url *string `type:"string"` - // The S3 bucket for the disk image. + // The Amazon S3 bucket for the disk image. UserBucket *UserBucket `type:"structure"` } @@ -101269,7 +106136,7 @@ type SnapshotTaskDetail struct { // The URL of the disk image from which the snapshot is created. Url *string `locationName:"url" type:"string"` - // The S3 bucket for the disk image. + // The Amazon S3 bucket for the disk image. UserBucket *UserBucketDetails `locationName:"userBucket" type:"structure"` } @@ -101749,7 +106616,7 @@ type SpotFleetRequestConfigData struct { // The Amazon Resource Name (ARN) of an AWS Identity and Access Management (IAM) // role that grants the Spot Fleet the permission to request, launch, terminate, - // and tag instances on your behalf. For more information, see Spot Fleet Prerequisites + // and tag instances on your behalf. For more information, see Spot Fleet prerequisites // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-fleet-requests.html#spot-fleet-prerequisites) // in the Amazon EC2 User Guide for Linux Instances. Spot Fleet can terminate // Spot Instances on your behalf when you cancel its Spot Fleet request using @@ -102141,7 +107008,7 @@ type SpotInstanceRequest struct { SpotPrice *string `locationName:"spotPrice" type:"string"` // The state of the Spot Instance request. Spot status information helps track - // your Spot Instance requests. For more information, see Spot Status (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html) + // your Spot Instance requests. For more information, see Spot status (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html) // in the Amazon EC2 User Guide for Linux Instances. State *string `locationName:"state" type:"string" enum:"SpotInstanceState"` @@ -102327,7 +107194,7 @@ func (s *SpotInstanceStateFault) SetMessage(v string) *SpotInstanceStateFault { type SpotInstanceStatus struct { _ struct{} `type:"structure"` - // The status code. For a list of status codes, see Spot Status Codes (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html#spot-instance-bid-status-understand) + // The status code. For a list of status codes, see Spot status codes (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-bid-status.html#spot-instance-bid-status-understand) // in the Amazon EC2 User Guide for Linux Instances. Code *string `locationName:"code" type:"string"` @@ -102751,8 +107618,7 @@ type StaleIpPermission struct { // The IP ranges. Not applicable for stale security group rules. IpRanges []*string `locationName:"ipRanges" locationNameList:"item" type:"list"` - // The prefix list IDs for an AWS service. Not applicable for stale security - // group rules. + // The prefix list IDs. Not applicable for stale security group rules. PrefixListIds []*string `locationName:"prefixListIds" locationNameList:"item" type:"list"` // The end of the port range for the TCP and UDP protocols, or an ICMP type @@ -103124,7 +107990,7 @@ type StopInstancesInput struct { // Hibernates the instance if the instance was enabled for hibernation at launch. // If the instance cannot hibernate successfully, a normal shutdown occurs. - // For more information, see Hibernate Your Instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) + // For more information, see Hibernate your instance (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html) // in the Amazon Elastic Compute Cloud User Guide. // // Default: false @@ -103284,12 +108150,20 @@ type Subnet struct { // The IPv4 CIDR block assigned to the subnet. CidrBlock *string `locationName:"cidrBlock" type:"string"` + // The customer-owned IPv4 address pool associated with the subnet. + CustomerOwnedIpv4Pool *string `locationName:"customerOwnedIpv4Pool" type:"string"` + // Indicates whether this is the default subnet for the Availability Zone. DefaultForAz *bool `locationName:"defaultForAz" type:"boolean"` // Information about the IPv6 CIDR blocks associated with the subnet. Ipv6CidrBlockAssociationSet []*SubnetIpv6CidrBlockAssociation `locationName:"ipv6CidrBlockAssociationSet" locationNameList:"item" type:"list"` + // Indicates whether a network interface created in this subnet (including a + // network interface created by RunInstances) receives a customer-owned IPv4 + // address. + MapCustomerOwnedIpOnLaunch *bool `locationName:"mapCustomerOwnedIpOnLaunch" type:"boolean"` + // Indicates whether instances launched in this subnet receive a public IPv4 // address. MapPublicIpOnLaunch *bool `locationName:"mapPublicIpOnLaunch" type:"boolean"` @@ -103356,6 +108230,12 @@ func (s *Subnet) SetCidrBlock(v string) *Subnet { return s } +// SetCustomerOwnedIpv4Pool sets the CustomerOwnedIpv4Pool field's value. +func (s *Subnet) SetCustomerOwnedIpv4Pool(v string) *Subnet { + s.CustomerOwnedIpv4Pool = &v + return s +} + // SetDefaultForAz sets the DefaultForAz field's value. func (s *Subnet) SetDefaultForAz(v bool) *Subnet { s.DefaultForAz = &v @@ -103368,6 +108248,12 @@ func (s *Subnet) SetIpv6CidrBlockAssociationSet(v []*SubnetIpv6CidrBlockAssociat return s } +// SetMapCustomerOwnedIpOnLaunch sets the MapCustomerOwnedIpOnLaunch field's value. +func (s *Subnet) SetMapCustomerOwnedIpOnLaunch(v bool) *Subnet { + s.MapCustomerOwnedIpOnLaunch = &v + return s +} + // SetMapPublicIpOnLaunch sets the MapPublicIpOnLaunch field's value. func (s *Subnet) SetMapPublicIpOnLaunch(v bool) *Subnet { s.MapPublicIpOnLaunch = &v @@ -103668,12 +108554,17 @@ type TagSpecification struct { _ struct{} `type:"structure"` // The type of resource to tag. Currently, the resource types that support tagging - // on creation are: capacity-reservation | client-vpn-endpoint | dedicated-host - // | fleet | fpga-image | instance | key-pair | launch-template | | natgateway - // | spot-fleet-request | placement-group | snapshot | traffic-mirror-filter - // | traffic-mirror-session | traffic-mirror-target | transit-gateway | transit-gateway-attachment - // | transit-gateway-route-table | vpc-endpoint (for interface VPC endpoints)| - // vpc-endpoint-service (for gateway VPC endpoints) | volume | vpc-flow-log. + // on creation are: capacity-reservation | client-vpn-endpoint | customer-gateway + // | dedicated-host | dhcp-options | export-image-task | export-instance-task + // | fleet | fpga-image | host-reservation | import-image-task | import-snapshot-task + // | instance | internet-gateway | ipv4pool-ec2 | ipv6pool-ec2 | key-pair | + // launch-template | placement-group | prefix-list | natgateway | network-acl + // | route-table | security-group | spot-fleet-request | spot-instances-request + // | snapshot | subnet | traffic-mirror-filter | traffic-mirror-session | traffic-mirror-target + // | transit-gateway | transit-gateway-attachment | transit-gateway-route-table + // | volume |vpc | vpc-peering-connection | vpc-endpoint (for interface and + // gateway endpoints) | vpc-endpoint-service (for AWS PrivateLink) | vpc-flow-log + // | vpn-connection | vpn-gateway. // // To tag a resource after it has been created, see CreateTags (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateTags.html). ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` @@ -104871,7 +109762,7 @@ type TransitGatewayAssociation struct { // The ID of the resource. ResourceId *string `locationName:"resourceId" type:"string"` - // The resource type. + // The resource type. Note that the tgw-peering resource type has been deprecated. ResourceType *string `locationName:"resourceType" type:"string" enum:"TransitGatewayAttachmentResourceType"` // The state of the association. @@ -104940,10 +109831,10 @@ type TransitGatewayAttachment struct { // The ID of the AWS account that owns the resource. ResourceOwnerId *string `locationName:"resourceOwnerId" type:"string"` - // The resource type. + // The resource type. Note that the tgw-peering resource type has been deprecated. ResourceType *string `locationName:"resourceType" type:"string" enum:"TransitGatewayAttachmentResourceType"` - // The attachment state. + // The attachment state. Note that the initiating state has been deprecated. State *string `locationName:"state" type:"string" enum:"TransitGatewayAttachmentState"` // The tags for the attachment. @@ -105653,7 +110544,8 @@ type TransitGatewayPeeringAttachment struct { // Information about the requester transit gateway. RequesterTgwInfo *PeeringTgwInfo `locationName:"requesterTgwInfo" type:"structure"` - // The state of the transit gateway peering attachment. + // The state of the transit gateway peering attachment. Note that the initiating + // state has been deprecated. State *string `locationName:"state" type:"string" enum:"TransitGatewayAttachmentState"` // The status of the transit gateway peering attachment. @@ -105718,6 +110610,117 @@ func (s *TransitGatewayPeeringAttachment) SetTransitGatewayAttachmentId(v string return s } +// Describes a transit gateway prefix list attachment. +type TransitGatewayPrefixListAttachment struct { + _ struct{} `type:"structure"` + + // The ID of the resource. + ResourceId *string `locationName:"resourceId" type:"string"` + + // The resource type. Note that the tgw-peering resource type has been deprecated. + ResourceType *string `locationName:"resourceType" type:"string" enum:"TransitGatewayAttachmentResourceType"` + + // The ID of the attachment. + TransitGatewayAttachmentId *string `locationName:"transitGatewayAttachmentId" type:"string"` +} + +// String returns the string representation +func (s TransitGatewayPrefixListAttachment) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TransitGatewayPrefixListAttachment) GoString() string { + return s.String() +} + +// SetResourceId sets the ResourceId field's value. +func (s *TransitGatewayPrefixListAttachment) SetResourceId(v string) *TransitGatewayPrefixListAttachment { + s.ResourceId = &v + return s +} + +// SetResourceType sets the ResourceType field's value. +func (s *TransitGatewayPrefixListAttachment) SetResourceType(v string) *TransitGatewayPrefixListAttachment { + s.ResourceType = &v + return s +} + +// SetTransitGatewayAttachmentId sets the TransitGatewayAttachmentId field's value. +func (s *TransitGatewayPrefixListAttachment) SetTransitGatewayAttachmentId(v string) *TransitGatewayPrefixListAttachment { + s.TransitGatewayAttachmentId = &v + return s +} + +// Describes a prefix list reference. +type TransitGatewayPrefixListReference struct { + _ struct{} `type:"structure"` + + // Indicates whether traffic that matches this route is dropped. + Blackhole *bool `locationName:"blackhole" type:"boolean"` + + // The ID of the prefix list. + PrefixListId *string `locationName:"prefixListId" type:"string"` + + // The ID of the prefix list owner. + PrefixListOwnerId *string `locationName:"prefixListOwnerId" type:"string"` + + // The state of the prefix list reference. + State *string `locationName:"state" type:"string" enum:"TransitGatewayPrefixListReferenceState"` + + // Information about the transit gateway attachment. + TransitGatewayAttachment *TransitGatewayPrefixListAttachment `locationName:"transitGatewayAttachment" type:"structure"` + + // The ID of the transit gateway route table. + TransitGatewayRouteTableId *string `locationName:"transitGatewayRouteTableId" type:"string"` +} + +// String returns the string representation +func (s TransitGatewayPrefixListReference) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TransitGatewayPrefixListReference) GoString() string { + return s.String() +} + +// SetBlackhole sets the Blackhole field's value. +func (s *TransitGatewayPrefixListReference) SetBlackhole(v bool) *TransitGatewayPrefixListReference { + s.Blackhole = &v + return s +} + +// SetPrefixListId sets the PrefixListId field's value. +func (s *TransitGatewayPrefixListReference) SetPrefixListId(v string) *TransitGatewayPrefixListReference { + s.PrefixListId = &v + return s +} + +// SetPrefixListOwnerId sets the PrefixListOwnerId field's value. +func (s *TransitGatewayPrefixListReference) SetPrefixListOwnerId(v string) *TransitGatewayPrefixListReference { + s.PrefixListOwnerId = &v + return s +} + +// SetState sets the State field's value. +func (s *TransitGatewayPrefixListReference) SetState(v string) *TransitGatewayPrefixListReference { + s.State = &v + return s +} + +// SetTransitGatewayAttachment sets the TransitGatewayAttachment field's value. +func (s *TransitGatewayPrefixListReference) SetTransitGatewayAttachment(v *TransitGatewayPrefixListAttachment) *TransitGatewayPrefixListReference { + s.TransitGatewayAttachment = v + return s +} + +// SetTransitGatewayRouteTableId sets the TransitGatewayRouteTableId field's value. +func (s *TransitGatewayPrefixListReference) SetTransitGatewayRouteTableId(v string) *TransitGatewayPrefixListReference { + s.TransitGatewayRouteTableId = &v + return s +} + // Describes route propagation. type TransitGatewayPropagation struct { _ struct{} `type:"structure"` @@ -105725,7 +110728,7 @@ type TransitGatewayPropagation struct { // The ID of the resource. ResourceId *string `locationName:"resourceId" type:"string"` - // The resource type. + // The resource type. Note that the tgw-peering resource type has been deprecated. ResourceType *string `locationName:"resourceType" type:"string" enum:"TransitGatewayAttachmentResourceType"` // The state. @@ -105784,28 +110787,28 @@ type TransitGatewayRequestOptions struct { // A private Autonomous System Number (ASN) for the Amazon side of a BGP session. // The range is 64512 to 65534 for 16-bit ASNs and 4200000000 to 4294967294 - // for 32-bit ASNs. + // for 32-bit ASNs. The default is 64512. AmazonSideAsn *int64 `type:"long"` - // Enable or disable automatic acceptance of attachment requests. The default - // is disable. + // Enable or disable automatic acceptance of attachment requests. Disabled by + // default. AutoAcceptSharedAttachments *string `type:"string" enum:"AutoAcceptSharedAttachmentsValue"` // Enable or disable automatic association with the default association route - // table. The default is enable. + // table. Enabled by default. DefaultRouteTableAssociation *string `type:"string" enum:"DefaultRouteTableAssociationValue"` // Enable or disable automatic propagation of routes to the default propagation - // route table. The default is enable. + // route table. Enabled by default. DefaultRouteTablePropagation *string `type:"string" enum:"DefaultRouteTablePropagationValue"` - // Enable or disable DNS support. + // Enable or disable DNS support. Enabled by default. DnsSupport *string `type:"string" enum:"DnsSupportValue"` // Indicates whether multicast is enabled on the transit gateway MulticastSupport *string `type:"string" enum:"MulticastSupportValue"` - // Enable or disable Equal Cost Multipath Protocol support. + // Enable or disable Equal Cost Multipath Protocol support. Enabled by default. VpnEcmpSupport *string `type:"string" enum:"VpnEcmpSupportValue"` } @@ -105868,6 +110871,9 @@ type TransitGatewayRoute struct { // The CIDR block used for destination matches. DestinationCidrBlock *string `locationName:"destinationCidrBlock" type:"string"` + // The ID of the prefix list used for destination matches. + PrefixListId *string `locationName:"prefixListId" type:"string"` + // The state of the route. State *string `locationName:"state" type:"string" enum:"TransitGatewayRouteState"` @@ -105894,6 +110900,12 @@ func (s *TransitGatewayRoute) SetDestinationCidrBlock(v string) *TransitGatewayR return s } +// SetPrefixListId sets the PrefixListId field's value. +func (s *TransitGatewayRoute) SetPrefixListId(v string) *TransitGatewayRoute { + s.PrefixListId = &v + return s +} + // SetState sets the State field's value. func (s *TransitGatewayRoute) SetState(v string) *TransitGatewayRoute { s.State = &v @@ -105919,7 +110931,7 @@ type TransitGatewayRouteAttachment struct { // The ID of the resource. ResourceId *string `locationName:"resourceId" type:"string"` - // The resource type. + // The resource type. Note that the tgw-peering resource type has been deprecated. ResourceType *string `locationName:"resourceType" type:"string" enum:"TransitGatewayAttachmentResourceType"` // The ID of the attachment. @@ -106041,7 +111053,7 @@ type TransitGatewayRouteTableAssociation struct { // The ID of the resource. ResourceId *string `locationName:"resourceId" type:"string"` - // The resource type. + // The resource type. Note that the tgw-peering resource type has been deprecated. ResourceType *string `locationName:"resourceType" type:"string" enum:"TransitGatewayAttachmentResourceType"` // The state of the association. @@ -106092,7 +111104,7 @@ type TransitGatewayRouteTablePropagation struct { // The ID of the resource. ResourceId *string `locationName:"resourceId" type:"string"` - // The type of resource. + // The type of resource. Note that the tgw-peering resource type has been deprecated. ResourceType *string `locationName:"resourceType" type:"string" enum:"TransitGatewayAttachmentResourceType"` // The state of the resource. @@ -106146,7 +111158,8 @@ type TransitGatewayVpcAttachment struct { // The VPC attachment options. Options *TransitGatewayVpcAttachmentOptions `locationName:"options" type:"structure"` - // The state of the VPC attachment. + // The state of the VPC attachment. Note that the initiating state has been + // deprecated. State *string `locationName:"state" type:"string" enum:"TransitGatewayAttachmentState"` // The IDs of the subnets. @@ -106269,6 +111282,9 @@ func (s *TransitGatewayVpcAttachmentOptions) SetIpv6Support(v string) *TransitGa type TunnelOption struct { _ struct{} `type:"structure"` + // The action to take after a DPD timeout occurs. + DpdTimeoutAction *string `locationName:"dpdTimeoutAction" type:"string"` + // The number of seconds after which a DPD timeout occurs. DpdTimeoutSeconds *int64 `locationName:"dpdTimeoutSeconds" type:"integer"` @@ -106319,8 +111335,14 @@ type TunnelOption struct { // The number of packets in an IKE replay window. ReplayWindowSize *int64 `locationName:"replayWindowSize" type:"integer"` - // The range of inside IP addresses for the tunnel. + // The action to take when the establishing the VPN tunnels for a VPN connection. + StartupAction *string `locationName:"startupAction" type:"string"` + + // The range of inside IPv4 addresses for the tunnel. TunnelInsideCidr *string `locationName:"tunnelInsideCidr" type:"string"` + + // The range of inside IPv6 addresses for the tunnel. + TunnelInsideIpv6Cidr *string `locationName:"tunnelInsideIpv6Cidr" type:"string"` } // String returns the string representation @@ -106333,6 +111355,12 @@ func (s TunnelOption) GoString() string { return s.String() } +// SetDpdTimeoutAction sets the DpdTimeoutAction field's value. +func (s *TunnelOption) SetDpdTimeoutAction(v string) *TunnelOption { + s.DpdTimeoutAction = &v + return s +} + // SetDpdTimeoutSeconds sets the DpdTimeoutSeconds field's value. func (s *TunnelOption) SetDpdTimeoutSeconds(v int64) *TunnelOption { s.DpdTimeoutSeconds = &v @@ -106423,12 +111451,24 @@ func (s *TunnelOption) SetReplayWindowSize(v int64) *TunnelOption { return s } +// SetStartupAction sets the StartupAction field's value. +func (s *TunnelOption) SetStartupAction(v string) *TunnelOption { + s.StartupAction = &v + return s +} + // SetTunnelInsideCidr sets the TunnelInsideCidr field's value. func (s *TunnelOption) SetTunnelInsideCidr(v string) *TunnelOption { s.TunnelInsideCidr = &v return s } +// SetTunnelInsideIpv6Cidr sets the TunnelInsideIpv6Cidr field's value. +func (s *TunnelOption) SetTunnelInsideIpv6Cidr(v string) *TunnelOption { + s.TunnelInsideIpv6Cidr = &v + return s +} + type UnassignIpv6AddressesInput struct { _ struct{} `type:"structure"` @@ -106978,11 +112018,11 @@ func (s *UpdateSecurityGroupRuleDescriptionsIngressOutput) SetReturn(v bool) *Up return s } -// Describes the S3 bucket for the disk image. +// Describes the Amazon S3 bucket for the disk image. type UserBucket struct { _ struct{} `type:"structure"` - // The name of the S3 bucket where the disk image is located. + // The name of the Amazon S3 bucket where the disk image is located. S3Bucket *string `type:"string"` // The file name of the disk image. @@ -107011,11 +112051,11 @@ func (s *UserBucket) SetS3Key(v string) *UserBucket { return s } -// Describes the S3 bucket for the disk image. +// Describes the Amazon S3 bucket for the disk image. type UserBucketDetails struct { _ struct{} `type:"structure"` - // The S3 bucket from which the disk image was created. + // The Amazon S3 bucket from which the disk image was created. S3Bucket *string `locationName:"s3Bucket" type:"string"` // The file name of the disk image. @@ -107226,6 +112266,70 @@ func (s *VCpuInfo) SetValidThreadsPerCore(v []*int64) *VCpuInfo { return s } +// The error code and error message that is returned for a parameter or parameter +// combination that is not valid when a new launch template or new version of +// a launch template is created. +type ValidationError struct { + _ struct{} `type:"structure"` + + // The error code that indicates why the parameter or parameter combination + // is not valid. For more information about error codes, see Error Codes (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html.html). + Code *string `locationName:"code" type:"string"` + + // The error message that describes why the parameter or parameter combination + // is not valid. For more information about error messages, see Error Codes + // (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/errors-overview.html.html). + Message *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s ValidationError) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ValidationError) GoString() string { + return s.String() +} + +// SetCode sets the Code field's value. +func (s *ValidationError) SetCode(v string) *ValidationError { + s.Code = &v + return s +} + +// SetMessage sets the Message field's value. +func (s *ValidationError) SetMessage(v string) *ValidationError { + s.Message = &v + return s +} + +// The error codes and error messages that are returned for the parameters or +// parameter combinations that are not valid when a new launch template or new +// version of a launch template is created. +type ValidationWarning struct { + _ struct{} `type:"structure"` + + // The error codes and error messages. + Errors []*ValidationError `locationName:"errorSet" locationNameList:"item" type:"list"` +} + +// String returns the string representation +func (s ValidationWarning) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ValidationWarning) GoString() string { + return s.String() +} + +// SetErrors sets the Errors field's value. +func (s *ValidationWarning) SetErrors(v []*ValidationError) *ValidationWarning { + s.Errors = v + return s +} + // Describes telemetry for a VPN tunnel. type VgwTelemetry struct { _ struct{} `type:"structure"` @@ -107319,17 +112423,18 @@ type Volume struct { // For Provisioned IOPS SSD volumes, this represents the number of IOPS that // are provisioned for the volume. For General Purpose SSD volumes, this represents // the baseline performance of the volume and the rate at which the volume accumulates - // I/O credits for bursting. For more information, see Amazon EBS Volume Types + // I/O credits for bursting. For more information, see Amazon EBS volume types // (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html) // in the Amazon Elastic Compute Cloud User Guide. // - // Constraints: Range is 100-16,000 IOPS for gp2 volumes and 100 to 64,000IOPS - // for io1 volumes, in most Regions. The maximum IOPS for io1 of 64,000 is guaranteed - // only on Nitro-based instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). + // Constraints: Range is 100-16,000 IOPS for gp2 volumes and 100 to 64,000 IOPS + // for io1 and io2 volumes, in most Regions. The maximum IOPS for io1 and io2 + // of 64,000 is guaranteed only on Nitro-based instances (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances). // Other instance families guarantee performance up to 32,000 IOPS. // - // Condition: This parameter is required for requests to create io1 volumes; - // it is not used in requests to create gp2, st1, sc1, or standard volumes. + // Condition: This parameter is required for requests to create io1 and io2 + // volumes; it is not used in requests to create gp2, st1, sc1, or standard + // volumes. Iops *int64 `locationName:"iops" type:"integer"` // The Amazon Resource Name (ARN) of the AWS Key Management Service (AWS KMS) @@ -107358,9 +112463,9 @@ type Volume struct { // The ID of the volume. VolumeId *string `locationName:"volumeId" type:"string"` - // The volume type. This can be gp2 for General Purpose SSD, io1 for Provisioned - // IOPS SSD, st1 for Throughput Optimized HDD, sc1 for Cold HDD, or standard - // for Magnetic volumes. + // The volume type. This can be gp2 for General Purpose SSD, io1 or io2 for + // Provisioned IOPS SSD, st1 for Throughput Optimized HDD, sc1 for Cold HDD, + // or standard for Magnetic volumes. VolumeType *string `locationName:"volumeType" type:"string" enum:"VolumeType"` } @@ -107588,7 +112693,7 @@ type VolumeModification struct { // The original IOPS rate of the volume. OriginalIops *int64 `locationName:"originalIops" type:"integer"` - // The original size of the volume. + // The original size of the volume, in GiB. OriginalSize *int64 `locationName:"originalSize" type:"integer"` // The original EBS volume type of the volume. @@ -108005,8 +113110,7 @@ type Vpc struct { // Information about the IPv4 CIDR blocks associated with the VPC. CidrBlockAssociationSet []*VpcCidrBlockAssociation `locationName:"cidrBlockAssociationSet" locationNameList:"item" type:"list"` - // The ID of the set of DHCP options you've associated with the VPC (or default - // if the default options are associated with the VPC). + // The ID of the set of DHCP options you've associated with the VPC. DhcpOptionsId *string `locationName:"dhcpOptionsId" type:"string"` // The allowed tenancy of instances launched into the VPC. @@ -108515,7 +113619,8 @@ type VpcIpv6CidrBlockAssociation struct { // The ID of the IPv6 address pool from which the IPv6 CIDR block is allocated. Ipv6Pool *string `locationName:"ipv6Pool" type:"string"` - // The name of the location from which we advertise the IPV6 CIDR block. + // The name of the unique set of Availability Zones, Local Zones, or Wavelength + // Zones from which AWS advertises IP addresses, for example, us-east-1-wl1-bos-wlz-1. NetworkBorderGroup *string `locationName:"networkBorderGroup" type:"string"` } @@ -108921,10 +114026,25 @@ type VpnConnectionOptions struct { // Indicates whether acceleration is enabled for the VPN connection. EnableAcceleration *bool `locationName:"enableAcceleration" type:"boolean"` + // The IPv4 CIDR on the customer gateway (on-premises) side of the VPN connection. + LocalIpv4NetworkCidr *string `locationName:"localIpv4NetworkCidr" type:"string"` + + // The IPv6 CIDR on the customer gateway (on-premises) side of the VPN connection. + LocalIpv6NetworkCidr *string `locationName:"localIpv6NetworkCidr" type:"string"` + + // The IPv4 CIDR on the AWS side of the VPN connection. + RemoteIpv4NetworkCidr *string `locationName:"remoteIpv4NetworkCidr" type:"string"` + + // The IPv6 CIDR on the AWS side of the VPN connection. + RemoteIpv6NetworkCidr *string `locationName:"remoteIpv6NetworkCidr" type:"string"` + // Indicates whether the VPN connection uses static routes only. Static routes // must be used for devices that don't support BGP. StaticRoutesOnly *bool `locationName:"staticRoutesOnly" type:"boolean"` + // Indicates whether the VPN tunnels process IPv4 or IPv6 traffic. + TunnelInsideIpVersion *string `locationName:"tunnelInsideIpVersion" type:"string" enum:"TunnelInsideIpVersion"` + // Indicates the VPN tunnel options. TunnelOptions []*TunnelOption `locationName:"tunnelOptionSet" locationNameList:"item" type:"list"` } @@ -108945,12 +114065,42 @@ func (s *VpnConnectionOptions) SetEnableAcceleration(v bool) *VpnConnectionOptio return s } +// SetLocalIpv4NetworkCidr sets the LocalIpv4NetworkCidr field's value. +func (s *VpnConnectionOptions) SetLocalIpv4NetworkCidr(v string) *VpnConnectionOptions { + s.LocalIpv4NetworkCidr = &v + return s +} + +// SetLocalIpv6NetworkCidr sets the LocalIpv6NetworkCidr field's value. +func (s *VpnConnectionOptions) SetLocalIpv6NetworkCidr(v string) *VpnConnectionOptions { + s.LocalIpv6NetworkCidr = &v + return s +} + +// SetRemoteIpv4NetworkCidr sets the RemoteIpv4NetworkCidr field's value. +func (s *VpnConnectionOptions) SetRemoteIpv4NetworkCidr(v string) *VpnConnectionOptions { + s.RemoteIpv4NetworkCidr = &v + return s +} + +// SetRemoteIpv6NetworkCidr sets the RemoteIpv6NetworkCidr field's value. +func (s *VpnConnectionOptions) SetRemoteIpv6NetworkCidr(v string) *VpnConnectionOptions { + s.RemoteIpv6NetworkCidr = &v + return s +} + // SetStaticRoutesOnly sets the StaticRoutesOnly field's value. func (s *VpnConnectionOptions) SetStaticRoutesOnly(v bool) *VpnConnectionOptions { s.StaticRoutesOnly = &v return s } +// SetTunnelInsideIpVersion sets the TunnelInsideIpVersion field's value. +func (s *VpnConnectionOptions) SetTunnelInsideIpVersion(v string) *VpnConnectionOptions { + s.TunnelInsideIpVersion = &v + return s +} + // SetTunnelOptions sets the TunnelOptions field's value. func (s *VpnConnectionOptions) SetTunnelOptions(v []*TunnelOption) *VpnConnectionOptions { s.TunnelOptions = v @@ -108966,6 +114116,26 @@ type VpnConnectionOptionsSpecification struct { // Default: false EnableAcceleration *bool `type:"boolean"` + // The IPv4 CIDR on the customer gateway (on-premises) side of the VPN connection. + // + // Default: 0.0.0.0/0 + LocalIpv4NetworkCidr *string `type:"string"` + + // The IPv6 CIDR on the customer gateway (on-premises) side of the VPN connection. + // + // Default: ::/0 + LocalIpv6NetworkCidr *string `type:"string"` + + // The IPv4 CIDR on the AWS side of the VPN connection. + // + // Default: 0.0.0.0/0 + RemoteIpv4NetworkCidr *string `type:"string"` + + // The IPv6 CIDR on the AWS side of the VPN connection. + // + // Default: ::/0 + RemoteIpv6NetworkCidr *string `type:"string"` + // Indicate whether the VPN connection uses static routes only. If you are creating // a VPN connection for a device that does not support BGP, you must specify // true. Use CreateVpnConnectionRoute to create a static route. @@ -108973,6 +114143,11 @@ type VpnConnectionOptionsSpecification struct { // Default: false StaticRoutesOnly *bool `locationName:"staticRoutesOnly" type:"boolean"` + // Indicate whether the VPN tunnels process IPv4 or IPv6 traffic. + // + // Default: ipv4 + TunnelInsideIpVersion *string `type:"string" enum:"TunnelInsideIpVersion"` + // The tunnel options for the VPN connection. TunnelOptions []*VpnTunnelOptionsSpecification `type:"list"` } @@ -108993,12 +114168,42 @@ func (s *VpnConnectionOptionsSpecification) SetEnableAcceleration(v bool) *VpnCo return s } +// SetLocalIpv4NetworkCidr sets the LocalIpv4NetworkCidr field's value. +func (s *VpnConnectionOptionsSpecification) SetLocalIpv4NetworkCidr(v string) *VpnConnectionOptionsSpecification { + s.LocalIpv4NetworkCidr = &v + return s +} + +// SetLocalIpv6NetworkCidr sets the LocalIpv6NetworkCidr field's value. +func (s *VpnConnectionOptionsSpecification) SetLocalIpv6NetworkCidr(v string) *VpnConnectionOptionsSpecification { + s.LocalIpv6NetworkCidr = &v + return s +} + +// SetRemoteIpv4NetworkCidr sets the RemoteIpv4NetworkCidr field's value. +func (s *VpnConnectionOptionsSpecification) SetRemoteIpv4NetworkCidr(v string) *VpnConnectionOptionsSpecification { + s.RemoteIpv4NetworkCidr = &v + return s +} + +// SetRemoteIpv6NetworkCidr sets the RemoteIpv6NetworkCidr field's value. +func (s *VpnConnectionOptionsSpecification) SetRemoteIpv6NetworkCidr(v string) *VpnConnectionOptionsSpecification { + s.RemoteIpv6NetworkCidr = &v + return s +} + // SetStaticRoutesOnly sets the StaticRoutesOnly field's value. func (s *VpnConnectionOptionsSpecification) SetStaticRoutesOnly(v bool) *VpnConnectionOptionsSpecification { s.StaticRoutesOnly = &v return s } +// SetTunnelInsideIpVersion sets the TunnelInsideIpVersion field's value. +func (s *VpnConnectionOptionsSpecification) SetTunnelInsideIpVersion(v string) *VpnConnectionOptionsSpecification { + s.TunnelInsideIpVersion = &v + return s +} + // SetTunnelOptions sets the TunnelOptions field's value. func (s *VpnConnectionOptionsSpecification) SetTunnelOptions(v []*VpnTunnelOptionsSpecification) *VpnConnectionOptionsSpecification { s.TunnelOptions = v @@ -109130,6 +114335,14 @@ func (s *VpnStaticRoute) SetState(v string) *VpnStaticRoute { type VpnTunnelOptionsSpecification struct { _ struct{} `type:"structure"` + // The action to take after DPD timeout occurs. Specify restart to restart the + // IKE initiation. Specify clear to end the IKE session. + // + // Valid Values: clear | none | restart + // + // Default: clear + DPDTimeoutAction *string `type:"string"` + // The number of seconds after which a DPD timeout occurs. // // Constraints: A value between 0 and 30. @@ -109145,19 +114358,19 @@ type VpnTunnelOptionsSpecification struct { // One or more Diffie-Hellman group numbers that are permitted for the VPN tunnel // for phase 1 IKE negotiations. // - // Valid values: 2 | 14 | 15 | 16 | 17 | 18 | 22 | 23 | 24 + // Valid values: 2 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 Phase1DHGroupNumbers []*Phase1DHGroupNumbersRequestListValue `locationName:"Phase1DHGroupNumber" locationNameList:"item" type:"list"` // One or more encryption algorithms that are permitted for the VPN tunnel for // phase 1 IKE negotiations. // - // Valid values: AES128 | AES256 + // Valid values: AES128 | AES256 | AES128-GCM-16 | AES256-GCM-16 Phase1EncryptionAlgorithms []*Phase1EncryptionAlgorithmsRequestListValue `locationName:"Phase1EncryptionAlgorithm" locationNameList:"item" type:"list"` // One or more integrity algorithms that are permitted for the VPN tunnel for // phase 1 IKE negotiations. // - // Valid values: SHA1 | SHA2-256 + // Valid values: SHA1 | SHA2-256 | SHA2-384 | SHA2-512 Phase1IntegrityAlgorithms []*Phase1IntegrityAlgorithmsRequestListValue `locationName:"Phase1IntegrityAlgorithm" locationNameList:"item" type:"list"` // The lifetime for phase 1 of the IKE negotiation, in seconds. @@ -109170,19 +114383,19 @@ type VpnTunnelOptionsSpecification struct { // One or more Diffie-Hellman group numbers that are permitted for the VPN tunnel // for phase 2 IKE negotiations. // - // Valid values: 2 | 5 | 14 | 15 | 16 | 17 | 18 | 22 | 23 | 24 + // Valid values: 2 | 5 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 Phase2DHGroupNumbers []*Phase2DHGroupNumbersRequestListValue `locationName:"Phase2DHGroupNumber" locationNameList:"item" type:"list"` // One or more encryption algorithms that are permitted for the VPN tunnel for // phase 2 IKE negotiations. // - // Valid values: AES128 | AES256 + // Valid values: AES128 | AES256 | AES128-GCM-16 | AES256-GCM-16 Phase2EncryptionAlgorithms []*Phase2EncryptionAlgorithmsRequestListValue `locationName:"Phase2EncryptionAlgorithm" locationNameList:"item" type:"list"` // One or more integrity algorithms that are permitted for the VPN tunnel for // phase 2 IKE negotiations. // - // Valid values: SHA1 | SHA2-256 + // Valid values: SHA1 | SHA2-256 | SHA2-384 | SHA2-512 Phase2IntegrityAlgorithms []*Phase2IntegrityAlgorithmsRequestListValue `locationName:"Phase2IntegrityAlgorithm" locationNameList:"item" type:"list"` // The lifetime for phase 2 of the IKE negotiation, in seconds. @@ -109225,7 +114438,16 @@ type VpnTunnelOptionsSpecification struct { // Default: 1024 ReplayWindowSize *int64 `type:"integer"` - // The range of inside IP addresses for the tunnel. Any specified CIDR blocks + // The action to take when the establishing the tunnel for the VPN connection. + // By default, your customer gateway device must initiate the IKE negotiation + // and bring up the tunnel. Specify start for AWS to initiate the IKE negotiation. + // + // Valid Values: add | start + // + // Default: add + StartupAction *string `type:"string"` + + // The range of inside IPv4 addresses for the tunnel. Any specified CIDR blocks // must be unique across all VPN connections that use the same virtual private // gateway. // @@ -109246,6 +114468,12 @@ type VpnTunnelOptionsSpecification struct { // // * 169.254.169.252/30 TunnelInsideCidr *string `type:"string"` + + // The range of inside IPv6 addresses for the tunnel. Any specified CIDR blocks + // must be unique across all VPN connections that use the same transit gateway. + // + // Constraints: A size /126 CIDR block from the local fd00::/8 range. + TunnelInsideIpv6Cidr *string `type:"string"` } // String returns the string representation @@ -109258,6 +114486,12 @@ func (s VpnTunnelOptionsSpecification) GoString() string { return s.String() } +// SetDPDTimeoutAction sets the DPDTimeoutAction field's value. +func (s *VpnTunnelOptionsSpecification) SetDPDTimeoutAction(v string) *VpnTunnelOptionsSpecification { + s.DPDTimeoutAction = &v + return s +} + // SetDPDTimeoutSeconds sets the DPDTimeoutSeconds field's value. func (s *VpnTunnelOptionsSpecification) SetDPDTimeoutSeconds(v int64) *VpnTunnelOptionsSpecification { s.DPDTimeoutSeconds = &v @@ -109342,12 +114576,24 @@ func (s *VpnTunnelOptionsSpecification) SetReplayWindowSize(v int64) *VpnTunnelO return s } +// SetStartupAction sets the StartupAction field's value. +func (s *VpnTunnelOptionsSpecification) SetStartupAction(v string) *VpnTunnelOptionsSpecification { + s.StartupAction = &v + return s +} + // SetTunnelInsideCidr sets the TunnelInsideCidr field's value. func (s *VpnTunnelOptionsSpecification) SetTunnelInsideCidr(v string) *VpnTunnelOptionsSpecification { s.TunnelInsideCidr = &v return s } +// SetTunnelInsideIpv6Cidr sets the TunnelInsideIpv6Cidr field's value. +func (s *VpnTunnelOptionsSpecification) SetTunnelInsideIpv6Cidr(v string) *VpnTunnelOptionsSpecification { + s.TunnelInsideIpv6Cidr = &v + return s +} + type WithdrawByoipCidrInput struct { _ struct{} `type:"structure"` @@ -109429,6 +114675,14 @@ const ( AccountAttributeNameDefaultVpc = "default-vpc" ) +// AccountAttributeName_Values returns all elements of the AccountAttributeName enum +func AccountAttributeName_Values() []string { + return []string{ + AccountAttributeNameSupportedPlatforms, + AccountAttributeNameDefaultVpc, + } +} + const ( // ActivityStatusError is a ActivityStatus enum value ActivityStatusError = "error" @@ -109443,6 +114697,16 @@ const ( ActivityStatusFulfilled = "fulfilled" ) +// ActivityStatus_Values returns all elements of the ActivityStatus enum +func ActivityStatus_Values() []string { + return []string{ + ActivityStatusError, + ActivityStatusPendingFulfillment, + ActivityStatusPendingTermination, + ActivityStatusFulfilled, + } +} + const ( // AffinityDefault is a Affinity enum value AffinityDefault = "default" @@ -109451,6 +114715,14 @@ const ( AffinityHost = "host" ) +// Affinity_Values returns all elements of the Affinity enum +func Affinity_Values() []string { + return []string{ + AffinityDefault, + AffinityHost, + } +} + const ( // AllocationStateAvailable is a AllocationState enum value AllocationStateAvailable = "available" @@ -109471,6 +114743,18 @@ const ( AllocationStatePending = "pending" ) +// AllocationState_Values returns all elements of the AllocationState enum +func AllocationState_Values() []string { + return []string{ + AllocationStateAvailable, + AllocationStateUnderAssessment, + AllocationStatePermanentFailure, + AllocationStateReleased, + AllocationStateReleasedPermanentFailure, + AllocationStatePending, + } +} + const ( // AllocationStrategyLowestPrice is a AllocationStrategy enum value AllocationStrategyLowestPrice = "lowestPrice" @@ -109482,6 +114766,15 @@ const ( AllocationStrategyCapacityOptimized = "capacityOptimized" ) +// AllocationStrategy_Values returns all elements of the AllocationStrategy enum +func AllocationStrategy_Values() []string { + return []string{ + AllocationStrategyLowestPrice, + AllocationStrategyDiversified, + AllocationStrategyCapacityOptimized, + } +} + const ( // AllowsMultipleInstanceTypesOn is a AllowsMultipleInstanceTypes enum value AllowsMultipleInstanceTypesOn = "on" @@ -109490,6 +114783,14 @@ const ( AllowsMultipleInstanceTypesOff = "off" ) +// AllowsMultipleInstanceTypes_Values returns all elements of the AllowsMultipleInstanceTypes enum +func AllowsMultipleInstanceTypes_Values() []string { + return []string{ + AllowsMultipleInstanceTypesOn, + AllowsMultipleInstanceTypesOff, + } +} + const ( // ArchitectureTypeI386 is a ArchitectureType enum value ArchitectureTypeI386 = "i386" @@ -109501,6 +114802,15 @@ const ( ArchitectureTypeArm64 = "arm64" ) +// ArchitectureType_Values returns all elements of the ArchitectureType enum +func ArchitectureType_Values() []string { + return []string{ + ArchitectureTypeI386, + ArchitectureTypeX8664, + ArchitectureTypeArm64, + } +} + const ( // ArchitectureValuesI386 is a ArchitectureValues enum value ArchitectureValuesI386 = "i386" @@ -109512,11 +114822,27 @@ const ( ArchitectureValuesArm64 = "arm64" ) +// ArchitectureValues_Values returns all elements of the ArchitectureValues enum +func ArchitectureValues_Values() []string { + return []string{ + ArchitectureValuesI386, + ArchitectureValuesX8664, + ArchitectureValuesArm64, + } +} + const ( // AssociatedNetworkTypeVpc is a AssociatedNetworkType enum value AssociatedNetworkTypeVpc = "vpc" ) +// AssociatedNetworkType_Values returns all elements of the AssociatedNetworkType enum +func AssociatedNetworkType_Values() []string { + return []string{ + AssociatedNetworkTypeVpc, + } +} + const ( // AssociationStatusCodeAssociating is a AssociationStatusCode enum value AssociationStatusCodeAssociating = "associating" @@ -109534,6 +114860,17 @@ const ( AssociationStatusCodeDisassociated = "disassociated" ) +// AssociationStatusCode_Values returns all elements of the AssociationStatusCode enum +func AssociationStatusCode_Values() []string { + return []string{ + AssociationStatusCodeAssociating, + AssociationStatusCodeAssociated, + AssociationStatusCodeAssociationFailed, + AssociationStatusCodeDisassociating, + AssociationStatusCodeDisassociated, + } +} + const ( // AttachmentStatusAttaching is a AttachmentStatus enum value AttachmentStatusAttaching = "attaching" @@ -109548,6 +114885,16 @@ const ( AttachmentStatusDetached = "detached" ) +// AttachmentStatus_Values returns all elements of the AttachmentStatus enum +func AttachmentStatus_Values() []string { + return []string{ + AttachmentStatusAttaching, + AttachmentStatusAttached, + AttachmentStatusDetaching, + AttachmentStatusDetached, + } +} + const ( // AutoAcceptSharedAttachmentsValueEnable is a AutoAcceptSharedAttachmentsValue enum value AutoAcceptSharedAttachmentsValueEnable = "enable" @@ -109556,6 +114903,14 @@ const ( AutoAcceptSharedAttachmentsValueDisable = "disable" ) +// AutoAcceptSharedAttachmentsValue_Values returns all elements of the AutoAcceptSharedAttachmentsValue enum +func AutoAcceptSharedAttachmentsValue_Values() []string { + return []string{ + AutoAcceptSharedAttachmentsValueEnable, + AutoAcceptSharedAttachmentsValueDisable, + } +} + const ( // AutoPlacementOn is a AutoPlacement enum value AutoPlacementOn = "on" @@ -109564,6 +114919,14 @@ const ( AutoPlacementOff = "off" ) +// AutoPlacement_Values returns all elements of the AutoPlacement enum +func AutoPlacement_Values() []string { + return []string{ + AutoPlacementOn, + AutoPlacementOff, + } +} + const ( // AvailabilityZoneOptInStatusOptInNotRequired is a AvailabilityZoneOptInStatus enum value AvailabilityZoneOptInStatusOptInNotRequired = "opt-in-not-required" @@ -109575,6 +114938,15 @@ const ( AvailabilityZoneOptInStatusNotOptedIn = "not-opted-in" ) +// AvailabilityZoneOptInStatus_Values returns all elements of the AvailabilityZoneOptInStatus enum +func AvailabilityZoneOptInStatus_Values() []string { + return []string{ + AvailabilityZoneOptInStatusOptInNotRequired, + AvailabilityZoneOptInStatusOptedIn, + AvailabilityZoneOptInStatusNotOptedIn, + } +} + const ( // AvailabilityZoneStateAvailable is a AvailabilityZoneState enum value AvailabilityZoneStateAvailable = "available" @@ -109589,6 +114961,16 @@ const ( AvailabilityZoneStateUnavailable = "unavailable" ) +// AvailabilityZoneState_Values returns all elements of the AvailabilityZoneState enum +func AvailabilityZoneState_Values() []string { + return []string{ + AvailabilityZoneStateAvailable, + AvailabilityZoneStateInformation, + AvailabilityZoneStateImpaired, + AvailabilityZoneStateUnavailable, + } +} + const ( // BatchStateSubmitted is a BatchState enum value BatchStateSubmitted = "submitted" @@ -109612,6 +114994,19 @@ const ( BatchStateModifying = "modifying" ) +// BatchState_Values returns all elements of the BatchState enum +func BatchState_Values() []string { + return []string{ + BatchStateSubmitted, + BatchStateActive, + BatchStateCancelled, + BatchStateFailed, + BatchStateCancelledRunning, + BatchStateCancelledTerminating, + BatchStateModifying, + } +} + const ( // BundleTaskStatePending is a BundleTaskState enum value BundleTaskStatePending = "pending" @@ -109635,6 +115030,19 @@ const ( BundleTaskStateFailed = "failed" ) +// BundleTaskState_Values returns all elements of the BundleTaskState enum +func BundleTaskState_Values() []string { + return []string{ + BundleTaskStatePending, + BundleTaskStateWaitingForShutdown, + BundleTaskStateBundling, + BundleTaskStateStoring, + BundleTaskStateCancelling, + BundleTaskStateComplete, + BundleTaskStateFailed, + } +} + const ( // ByoipCidrStateAdvertised is a ByoipCidrState enum value ByoipCidrStateAdvertised = "advertised" @@ -109661,6 +115069,20 @@ const ( ByoipCidrStateProvisionedNotPubliclyAdvertisable = "provisioned-not-publicly-advertisable" ) +// ByoipCidrState_Values returns all elements of the ByoipCidrState enum +func ByoipCidrState_Values() []string { + return []string{ + ByoipCidrStateAdvertised, + ByoipCidrStateDeprovisioned, + ByoipCidrStateFailedDeprovision, + ByoipCidrStateFailedProvision, + ByoipCidrStatePendingDeprovision, + ByoipCidrStatePendingProvision, + ByoipCidrStateProvisioned, + ByoipCidrStateProvisionedNotPubliclyAdvertisable, + } +} + const ( // CancelBatchErrorCodeFleetRequestIdDoesNotExist is a CancelBatchErrorCode enum value CancelBatchErrorCodeFleetRequestIdDoesNotExist = "fleetRequestIdDoesNotExist" @@ -109675,6 +115097,16 @@ const ( CancelBatchErrorCodeUnexpectedError = "unexpectedError" ) +// CancelBatchErrorCode_Values returns all elements of the CancelBatchErrorCode enum +func CancelBatchErrorCode_Values() []string { + return []string{ + CancelBatchErrorCodeFleetRequestIdDoesNotExist, + CancelBatchErrorCodeFleetRequestIdMalformed, + CancelBatchErrorCodeFleetRequestNotInCancellableState, + CancelBatchErrorCodeUnexpectedError, + } +} + const ( // CancelSpotInstanceRequestStateActive is a CancelSpotInstanceRequestState enum value CancelSpotInstanceRequestStateActive = "active" @@ -109692,6 +115124,17 @@ const ( CancelSpotInstanceRequestStateCompleted = "completed" ) +// CancelSpotInstanceRequestState_Values returns all elements of the CancelSpotInstanceRequestState enum +func CancelSpotInstanceRequestState_Values() []string { + return []string{ + CancelSpotInstanceRequestStateActive, + CancelSpotInstanceRequestStateOpen, + CancelSpotInstanceRequestStateClosed, + CancelSpotInstanceRequestStateCancelled, + CancelSpotInstanceRequestStateCompleted, + } +} + const ( // CapacityReservationInstancePlatformLinuxUnix is a CapacityReservationInstancePlatform enum value CapacityReservationInstancePlatformLinuxUnix = "Linux/UNIX" @@ -109727,6 +115170,23 @@ const ( CapacityReservationInstancePlatformLinuxwithSqlserverEnterprise = "Linux with SQL Server Enterprise" ) +// CapacityReservationInstancePlatform_Values returns all elements of the CapacityReservationInstancePlatform enum +func CapacityReservationInstancePlatform_Values() []string { + return []string{ + CapacityReservationInstancePlatformLinuxUnix, + CapacityReservationInstancePlatformRedHatEnterpriseLinux, + CapacityReservationInstancePlatformSuselinux, + CapacityReservationInstancePlatformWindows, + CapacityReservationInstancePlatformWindowswithSqlserver, + CapacityReservationInstancePlatformWindowswithSqlserverEnterprise, + CapacityReservationInstancePlatformWindowswithSqlserverStandard, + CapacityReservationInstancePlatformWindowswithSqlserverWeb, + CapacityReservationInstancePlatformLinuxwithSqlserverStandard, + CapacityReservationInstancePlatformLinuxwithSqlserverWeb, + CapacityReservationInstancePlatformLinuxwithSqlserverEnterprise, + } +} + const ( // CapacityReservationPreferenceOpen is a CapacityReservationPreference enum value CapacityReservationPreferenceOpen = "open" @@ -109735,6 +115195,14 @@ const ( CapacityReservationPreferenceNone = "none" ) +// CapacityReservationPreference_Values returns all elements of the CapacityReservationPreference enum +func CapacityReservationPreference_Values() []string { + return []string{ + CapacityReservationPreferenceOpen, + CapacityReservationPreferenceNone, + } +} + const ( // CapacityReservationStateActive is a CapacityReservationState enum value CapacityReservationStateActive = "active" @@ -109752,6 +115220,17 @@ const ( CapacityReservationStateFailed = "failed" ) +// CapacityReservationState_Values returns all elements of the CapacityReservationState enum +func CapacityReservationState_Values() []string { + return []string{ + CapacityReservationStateActive, + CapacityReservationStateExpired, + CapacityReservationStateCancelled, + CapacityReservationStatePending, + CapacityReservationStateFailed, + } +} + const ( // CapacityReservationTenancyDefault is a CapacityReservationTenancy enum value CapacityReservationTenancyDefault = "default" @@ -109760,6 +115239,38 @@ const ( CapacityReservationTenancyDedicated = "dedicated" ) +// CapacityReservationTenancy_Values returns all elements of the CapacityReservationTenancy enum +func CapacityReservationTenancy_Values() []string { + return []string{ + CapacityReservationTenancyDefault, + CapacityReservationTenancyDedicated, + } +} + +const ( + // CarrierGatewayStatePending is a CarrierGatewayState enum value + CarrierGatewayStatePending = "pending" + + // CarrierGatewayStateAvailable is a CarrierGatewayState enum value + CarrierGatewayStateAvailable = "available" + + // CarrierGatewayStateDeleting is a CarrierGatewayState enum value + CarrierGatewayStateDeleting = "deleting" + + // CarrierGatewayStateDeleted is a CarrierGatewayState enum value + CarrierGatewayStateDeleted = "deleted" +) + +// CarrierGatewayState_Values returns all elements of the CarrierGatewayState enum +func CarrierGatewayState_Values() []string { + return []string{ + CarrierGatewayStatePending, + CarrierGatewayStateAvailable, + CarrierGatewayStateDeleting, + CarrierGatewayStateDeleted, + } +} + const ( // ClientCertificateRevocationListStatusCodePending is a ClientCertificateRevocationListStatusCode enum value ClientCertificateRevocationListStatusCodePending = "pending" @@ -109768,14 +115279,34 @@ const ( ClientCertificateRevocationListStatusCodeActive = "active" ) +// ClientCertificateRevocationListStatusCode_Values returns all elements of the ClientCertificateRevocationListStatusCode enum +func ClientCertificateRevocationListStatusCode_Values() []string { + return []string{ + ClientCertificateRevocationListStatusCodePending, + ClientCertificateRevocationListStatusCodeActive, + } +} + const ( // ClientVpnAuthenticationTypeCertificateAuthentication is a ClientVpnAuthenticationType enum value ClientVpnAuthenticationTypeCertificateAuthentication = "certificate-authentication" // ClientVpnAuthenticationTypeDirectoryServiceAuthentication is a ClientVpnAuthenticationType enum value ClientVpnAuthenticationTypeDirectoryServiceAuthentication = "directory-service-authentication" + + // ClientVpnAuthenticationTypeFederatedAuthentication is a ClientVpnAuthenticationType enum value + ClientVpnAuthenticationTypeFederatedAuthentication = "federated-authentication" ) +// ClientVpnAuthenticationType_Values returns all elements of the ClientVpnAuthenticationType enum +func ClientVpnAuthenticationType_Values() []string { + return []string{ + ClientVpnAuthenticationTypeCertificateAuthentication, + ClientVpnAuthenticationTypeDirectoryServiceAuthentication, + ClientVpnAuthenticationTypeFederatedAuthentication, + } +} + const ( // ClientVpnAuthorizationRuleStatusCodeAuthorizing is a ClientVpnAuthorizationRuleStatusCode enum value ClientVpnAuthorizationRuleStatusCodeAuthorizing = "authorizing" @@ -109790,6 +115321,16 @@ const ( ClientVpnAuthorizationRuleStatusCodeRevoking = "revoking" ) +// ClientVpnAuthorizationRuleStatusCode_Values returns all elements of the ClientVpnAuthorizationRuleStatusCode enum +func ClientVpnAuthorizationRuleStatusCode_Values() []string { + return []string{ + ClientVpnAuthorizationRuleStatusCodeAuthorizing, + ClientVpnAuthorizationRuleStatusCodeActive, + ClientVpnAuthorizationRuleStatusCodeFailed, + ClientVpnAuthorizationRuleStatusCodeRevoking, + } +} + const ( // ClientVpnConnectionStatusCodeActive is a ClientVpnConnectionStatusCode enum value ClientVpnConnectionStatusCodeActive = "active" @@ -109804,6 +115345,16 @@ const ( ClientVpnConnectionStatusCodeTerminated = "terminated" ) +// ClientVpnConnectionStatusCode_Values returns all elements of the ClientVpnConnectionStatusCode enum +func ClientVpnConnectionStatusCode_Values() []string { + return []string{ + ClientVpnConnectionStatusCodeActive, + ClientVpnConnectionStatusCodeFailedToTerminate, + ClientVpnConnectionStatusCodeTerminating, + ClientVpnConnectionStatusCodeTerminated, + } +} + const ( // ClientVpnEndpointStatusCodePendingAssociate is a ClientVpnEndpointStatusCode enum value ClientVpnEndpointStatusCodePendingAssociate = "pending-associate" @@ -109818,6 +115369,16 @@ const ( ClientVpnEndpointStatusCodeDeleted = "deleted" ) +// ClientVpnEndpointStatusCode_Values returns all elements of the ClientVpnEndpointStatusCode enum +func ClientVpnEndpointStatusCode_Values() []string { + return []string{ + ClientVpnEndpointStatusCodePendingAssociate, + ClientVpnEndpointStatusCodeAvailable, + ClientVpnEndpointStatusCodeDeleting, + ClientVpnEndpointStatusCodeDeleted, + } +} + const ( // ClientVpnRouteStatusCodeCreating is a ClientVpnRouteStatusCode enum value ClientVpnRouteStatusCodeCreating = "creating" @@ -109832,6 +115393,16 @@ const ( ClientVpnRouteStatusCodeDeleting = "deleting" ) +// ClientVpnRouteStatusCode_Values returns all elements of the ClientVpnRouteStatusCode enum +func ClientVpnRouteStatusCode_Values() []string { + return []string{ + ClientVpnRouteStatusCodeCreating, + ClientVpnRouteStatusCodeActive, + ClientVpnRouteStatusCodeFailed, + ClientVpnRouteStatusCodeDeleting, + } +} + const ( // ConnectionNotificationStateEnabled is a ConnectionNotificationState enum value ConnectionNotificationStateEnabled = "Enabled" @@ -109840,16 +115411,38 @@ const ( ConnectionNotificationStateDisabled = "Disabled" ) +// ConnectionNotificationState_Values returns all elements of the ConnectionNotificationState enum +func ConnectionNotificationState_Values() []string { + return []string{ + ConnectionNotificationStateEnabled, + ConnectionNotificationStateDisabled, + } +} + const ( // ConnectionNotificationTypeTopic is a ConnectionNotificationType enum value ConnectionNotificationTypeTopic = "Topic" ) +// ConnectionNotificationType_Values returns all elements of the ConnectionNotificationType enum +func ConnectionNotificationType_Values() []string { + return []string{ + ConnectionNotificationTypeTopic, + } +} + const ( // ContainerFormatOva is a ContainerFormat enum value ContainerFormatOva = "ova" ) +// ContainerFormat_Values returns all elements of the ContainerFormat enum +func ContainerFormat_Values() []string { + return []string{ + ContainerFormatOva, + } +} + const ( // ConversionTaskStateActive is a ConversionTaskState enum value ConversionTaskStateActive = "active" @@ -109864,16 +115457,40 @@ const ( ConversionTaskStateCompleted = "completed" ) +// ConversionTaskState_Values returns all elements of the ConversionTaskState enum +func ConversionTaskState_Values() []string { + return []string{ + ConversionTaskStateActive, + ConversionTaskStateCancelling, + ConversionTaskStateCancelled, + ConversionTaskStateCompleted, + } +} + const ( // CopyTagsFromSourceVolume is a CopyTagsFromSource enum value CopyTagsFromSourceVolume = "volume" ) +// CopyTagsFromSource_Values returns all elements of the CopyTagsFromSource enum +func CopyTagsFromSource_Values() []string { + return []string{ + CopyTagsFromSourceVolume, + } +} + const ( // CurrencyCodeValuesUsd is a CurrencyCodeValues enum value CurrencyCodeValuesUsd = "USD" ) +// CurrencyCodeValues_Values returns all elements of the CurrencyCodeValues enum +func CurrencyCodeValues_Values() []string { + return []string{ + CurrencyCodeValuesUsd, + } +} + const ( // DatafeedSubscriptionStateActive is a DatafeedSubscriptionState enum value DatafeedSubscriptionStateActive = "Active" @@ -109882,6 +115499,14 @@ const ( DatafeedSubscriptionStateInactive = "Inactive" ) +// DatafeedSubscriptionState_Values returns all elements of the DatafeedSubscriptionState enum +func DatafeedSubscriptionState_Values() []string { + return []string{ + DatafeedSubscriptionStateActive, + DatafeedSubscriptionStateInactive, + } +} + const ( // DefaultRouteTableAssociationValueEnable is a DefaultRouteTableAssociationValue enum value DefaultRouteTableAssociationValueEnable = "enable" @@ -109890,6 +115515,14 @@ const ( DefaultRouteTableAssociationValueDisable = "disable" ) +// DefaultRouteTableAssociationValue_Values returns all elements of the DefaultRouteTableAssociationValue enum +func DefaultRouteTableAssociationValue_Values() []string { + return []string{ + DefaultRouteTableAssociationValueEnable, + DefaultRouteTableAssociationValueDisable, + } +} + const ( // DefaultRouteTablePropagationValueEnable is a DefaultRouteTablePropagationValue enum value DefaultRouteTablePropagationValueEnable = "enable" @@ -109898,6 +115531,14 @@ const ( DefaultRouteTablePropagationValueDisable = "disable" ) +// DefaultRouteTablePropagationValue_Values returns all elements of the DefaultRouteTablePropagationValue enum +func DefaultRouteTablePropagationValue_Values() []string { + return []string{ + DefaultRouteTablePropagationValueEnable, + DefaultRouteTablePropagationValueDisable, + } +} + const ( // DefaultTargetCapacityTypeSpot is a DefaultTargetCapacityType enum value DefaultTargetCapacityTypeSpot = "spot" @@ -109906,6 +115547,14 @@ const ( DefaultTargetCapacityTypeOnDemand = "on-demand" ) +// DefaultTargetCapacityType_Values returns all elements of the DefaultTargetCapacityType enum +func DefaultTargetCapacityType_Values() []string { + return []string{ + DefaultTargetCapacityTypeSpot, + DefaultTargetCapacityTypeOnDemand, + } +} + const ( // DeleteFleetErrorCodeFleetIdDoesNotExist is a DeleteFleetErrorCode enum value DeleteFleetErrorCodeFleetIdDoesNotExist = "fleetIdDoesNotExist" @@ -109920,6 +115569,16 @@ const ( DeleteFleetErrorCodeUnexpectedError = "unexpectedError" ) +// DeleteFleetErrorCode_Values returns all elements of the DeleteFleetErrorCode enum +func DeleteFleetErrorCode_Values() []string { + return []string{ + DeleteFleetErrorCodeFleetIdDoesNotExist, + DeleteFleetErrorCodeFleetIdMalformed, + DeleteFleetErrorCodeFleetNotInDeletableState, + DeleteFleetErrorCodeUnexpectedError, + } +} + const ( // DeleteQueuedReservedInstancesErrorCodeReservedInstancesIdInvalid is a DeleteQueuedReservedInstancesErrorCode enum value DeleteQueuedReservedInstancesErrorCodeReservedInstancesIdInvalid = "reserved-instances-id-invalid" @@ -109931,6 +115590,15 @@ const ( DeleteQueuedReservedInstancesErrorCodeUnexpectedError = "unexpected-error" ) +// DeleteQueuedReservedInstancesErrorCode_Values returns all elements of the DeleteQueuedReservedInstancesErrorCode enum +func DeleteQueuedReservedInstancesErrorCode_Values() []string { + return []string{ + DeleteQueuedReservedInstancesErrorCodeReservedInstancesIdInvalid, + DeleteQueuedReservedInstancesErrorCodeReservedInstancesNotInQueuedState, + DeleteQueuedReservedInstancesErrorCodeUnexpectedError, + } +} + const ( // DeviceTypeEbs is a DeviceType enum value DeviceTypeEbs = "ebs" @@ -109939,6 +115607,14 @@ const ( DeviceTypeInstanceStore = "instance-store" ) +// DeviceType_Values returns all elements of the DeviceType enum +func DeviceType_Values() []string { + return []string{ + DeviceTypeEbs, + DeviceTypeInstanceStore, + } +} + const ( // DiskImageFormatVmdk is a DiskImageFormat enum value DiskImageFormatVmdk = "VMDK" @@ -109950,6 +115626,15 @@ const ( DiskImageFormatVhd = "VHD" ) +// DiskImageFormat_Values returns all elements of the DiskImageFormat enum +func DiskImageFormat_Values() []string { + return []string{ + DiskImageFormatVmdk, + DiskImageFormatRaw, + DiskImageFormatVhd, + } +} + const ( // DiskTypeHdd is a DiskType enum value DiskTypeHdd = "hdd" @@ -109958,6 +115643,14 @@ const ( DiskTypeSsd = "ssd" ) +// DiskType_Values returns all elements of the DiskType enum +func DiskType_Values() []string { + return []string{ + DiskTypeHdd, + DiskTypeSsd, + } +} + const ( // DnsNameStatePendingVerification is a DnsNameState enum value DnsNameStatePendingVerification = "pendingVerification" @@ -109969,6 +115662,15 @@ const ( DnsNameStateFailed = "failed" ) +// DnsNameState_Values returns all elements of the DnsNameState enum +func DnsNameState_Values() []string { + return []string{ + DnsNameStatePendingVerification, + DnsNameStateVerified, + DnsNameStateFailed, + } +} + const ( // DnsSupportValueEnable is a DnsSupportValue enum value DnsSupportValueEnable = "enable" @@ -109977,6 +115679,14 @@ const ( DnsSupportValueDisable = "disable" ) +// DnsSupportValue_Values returns all elements of the DnsSupportValue enum +func DnsSupportValue_Values() []string { + return []string{ + DnsSupportValueEnable, + DnsSupportValueDisable, + } +} + const ( // DomainTypeVpc is a DomainType enum value DomainTypeVpc = "vpc" @@ -109985,6 +115695,14 @@ const ( DomainTypeStandard = "standard" ) +// DomainType_Values returns all elements of the DomainType enum +func DomainType_Values() []string { + return []string{ + DomainTypeVpc, + DomainTypeStandard, + } +} + const ( // EbsEncryptionSupportUnsupported is a EbsEncryptionSupport enum value EbsEncryptionSupportUnsupported = "unsupported" @@ -109993,6 +115711,34 @@ const ( EbsEncryptionSupportSupported = "supported" ) +// EbsEncryptionSupport_Values returns all elements of the EbsEncryptionSupport enum +func EbsEncryptionSupport_Values() []string { + return []string{ + EbsEncryptionSupportUnsupported, + EbsEncryptionSupportSupported, + } +} + +const ( + // EbsNvmeSupportUnsupported is a EbsNvmeSupport enum value + EbsNvmeSupportUnsupported = "unsupported" + + // EbsNvmeSupportSupported is a EbsNvmeSupport enum value + EbsNvmeSupportSupported = "supported" + + // EbsNvmeSupportRequired is a EbsNvmeSupport enum value + EbsNvmeSupportRequired = "required" +) + +// EbsNvmeSupport_Values returns all elements of the EbsNvmeSupport enum +func EbsNvmeSupport_Values() []string { + return []string{ + EbsNvmeSupportUnsupported, + EbsNvmeSupportSupported, + EbsNvmeSupportRequired, + } +} + const ( // EbsOptimizedSupportUnsupported is a EbsOptimizedSupport enum value EbsOptimizedSupportUnsupported = "unsupported" @@ -110004,11 +115750,27 @@ const ( EbsOptimizedSupportDefault = "default" ) +// EbsOptimizedSupport_Values returns all elements of the EbsOptimizedSupport enum +func EbsOptimizedSupport_Values() []string { + return []string{ + EbsOptimizedSupportUnsupported, + EbsOptimizedSupportSupported, + EbsOptimizedSupportDefault, + } +} + const ( // ElasticGpuStateAttached is a ElasticGpuState enum value ElasticGpuStateAttached = "ATTACHED" ) +// ElasticGpuState_Values returns all elements of the ElasticGpuState enum +func ElasticGpuState_Values() []string { + return []string{ + ElasticGpuStateAttached, + } +} + const ( // ElasticGpuStatusOk is a ElasticGpuStatus enum value ElasticGpuStatusOk = "OK" @@ -110017,6 +115779,14 @@ const ( ElasticGpuStatusImpaired = "IMPAIRED" ) +// ElasticGpuStatus_Values returns all elements of the ElasticGpuStatus enum +func ElasticGpuStatus_Values() []string { + return []string{ + ElasticGpuStatusOk, + ElasticGpuStatusImpaired, + } +} + const ( // EnaSupportUnsupported is a EnaSupport enum value EnaSupportUnsupported = "unsupported" @@ -110028,6 +115798,15 @@ const ( EnaSupportRequired = "required" ) +// EnaSupport_Values returns all elements of the EnaSupport enum +func EnaSupport_Values() []string { + return []string{ + EnaSupportUnsupported, + EnaSupportSupported, + EnaSupportRequired, + } +} + const ( // EndDateTypeUnlimited is a EndDateType enum value EndDateTypeUnlimited = "unlimited" @@ -110036,6 +115815,14 @@ const ( EndDateTypeLimited = "limited" ) +// EndDateType_Values returns all elements of the EndDateType enum +func EndDateType_Values() []string { + return []string{ + EndDateTypeUnlimited, + EndDateTypeLimited, + } +} + const ( // EventCodeInstanceReboot is a EventCode enum value EventCodeInstanceReboot = "instance-reboot" @@ -110053,6 +115840,17 @@ const ( EventCodeInstanceStop = "instance-stop" ) +// EventCode_Values returns all elements of the EventCode enum +func EventCode_Values() []string { + return []string{ + EventCodeInstanceReboot, + EventCodeSystemReboot, + EventCodeSystemMaintenance, + EventCodeInstanceRetirement, + EventCodeInstanceStop, + } +} + const ( // EventTypeInstanceChange is a EventType enum value EventTypeInstanceChange = "instanceChange" @@ -110067,6 +115865,16 @@ const ( EventTypeInformation = "information" ) +// EventType_Values returns all elements of the EventType enum +func EventType_Values() []string { + return []string{ + EventTypeInstanceChange, + EventTypeFleetRequestChange, + EventTypeError, + EventTypeInformation, + } +} + const ( // ExcessCapacityTerminationPolicyNoTermination is a ExcessCapacityTerminationPolicy enum value ExcessCapacityTerminationPolicyNoTermination = "noTermination" @@ -110075,6 +115883,14 @@ const ( ExcessCapacityTerminationPolicyDefault = "default" ) +// ExcessCapacityTerminationPolicy_Values returns all elements of the ExcessCapacityTerminationPolicy enum +func ExcessCapacityTerminationPolicy_Values() []string { + return []string{ + ExcessCapacityTerminationPolicyNoTermination, + ExcessCapacityTerminationPolicyDefault, + } +} + const ( // ExportEnvironmentCitrix is a ExportEnvironment enum value ExportEnvironmentCitrix = "citrix" @@ -110086,6 +115902,15 @@ const ( ExportEnvironmentMicrosoft = "microsoft" ) +// ExportEnvironment_Values returns all elements of the ExportEnvironment enum +func ExportEnvironment_Values() []string { + return []string{ + ExportEnvironmentCitrix, + ExportEnvironmentVmware, + ExportEnvironmentMicrosoft, + } +} + const ( // ExportTaskStateActive is a ExportTaskState enum value ExportTaskStateActive = "active" @@ -110100,6 +115925,16 @@ const ( ExportTaskStateCompleted = "completed" ) +// ExportTaskState_Values returns all elements of the ExportTaskState enum +func ExportTaskState_Values() []string { + return []string{ + ExportTaskStateActive, + ExportTaskStateCancelling, + ExportTaskStateCancelled, + ExportTaskStateCompleted, + } +} + const ( // FastSnapshotRestoreStateCodeEnabling is a FastSnapshotRestoreStateCode enum value FastSnapshotRestoreStateCodeEnabling = "enabling" @@ -110117,6 +115952,17 @@ const ( FastSnapshotRestoreStateCodeDisabled = "disabled" ) +// FastSnapshotRestoreStateCode_Values returns all elements of the FastSnapshotRestoreStateCode enum +func FastSnapshotRestoreStateCode_Values() []string { + return []string{ + FastSnapshotRestoreStateCodeEnabling, + FastSnapshotRestoreStateCodeOptimizing, + FastSnapshotRestoreStateCodeEnabled, + FastSnapshotRestoreStateCodeDisabling, + FastSnapshotRestoreStateCodeDisabled, + } +} + const ( // FleetActivityStatusError is a FleetActivityStatus enum value FleetActivityStatusError = "error" @@ -110131,11 +115977,28 @@ const ( FleetActivityStatusFulfilled = "fulfilled" ) +// FleetActivityStatus_Values returns all elements of the FleetActivityStatus enum +func FleetActivityStatus_Values() []string { + return []string{ + FleetActivityStatusError, + FleetActivityStatusPendingFulfillment, + FleetActivityStatusPendingTermination, + FleetActivityStatusFulfilled, + } +} + const ( // FleetCapacityReservationUsageStrategyUseCapacityReservationsFirst is a FleetCapacityReservationUsageStrategy enum value FleetCapacityReservationUsageStrategyUseCapacityReservationsFirst = "use-capacity-reservations-first" ) +// FleetCapacityReservationUsageStrategy_Values returns all elements of the FleetCapacityReservationUsageStrategy enum +func FleetCapacityReservationUsageStrategy_Values() []string { + return []string{ + FleetCapacityReservationUsageStrategyUseCapacityReservationsFirst, + } +} + const ( // FleetEventTypeInstanceChange is a FleetEventType enum value FleetEventTypeInstanceChange = "instance-change" @@ -110147,6 +116010,15 @@ const ( FleetEventTypeServiceError = "service-error" ) +// FleetEventType_Values returns all elements of the FleetEventType enum +func FleetEventType_Values() []string { + return []string{ + FleetEventTypeInstanceChange, + FleetEventTypeFleetChange, + FleetEventTypeServiceError, + } +} + const ( // FleetExcessCapacityTerminationPolicyNoTermination is a FleetExcessCapacityTerminationPolicy enum value FleetExcessCapacityTerminationPolicyNoTermination = "no-termination" @@ -110155,6 +116027,14 @@ const ( FleetExcessCapacityTerminationPolicyTermination = "termination" ) +// FleetExcessCapacityTerminationPolicy_Values returns all elements of the FleetExcessCapacityTerminationPolicy enum +func FleetExcessCapacityTerminationPolicy_Values() []string { + return []string{ + FleetExcessCapacityTerminationPolicyNoTermination, + FleetExcessCapacityTerminationPolicyTermination, + } +} + const ( // FleetOnDemandAllocationStrategyLowestPrice is a FleetOnDemandAllocationStrategy enum value FleetOnDemandAllocationStrategyLowestPrice = "lowest-price" @@ -110163,6 +116043,14 @@ const ( FleetOnDemandAllocationStrategyPrioritized = "prioritized" ) +// FleetOnDemandAllocationStrategy_Values returns all elements of the FleetOnDemandAllocationStrategy enum +func FleetOnDemandAllocationStrategy_Values() []string { + return []string{ + FleetOnDemandAllocationStrategyLowestPrice, + FleetOnDemandAllocationStrategyPrioritized, + } +} + const ( // FleetStateCodeSubmitted is a FleetStateCode enum value FleetStateCodeSubmitted = "submitted" @@ -110186,6 +116074,19 @@ const ( FleetStateCodeModifying = "modifying" ) +// FleetStateCode_Values returns all elements of the FleetStateCode enum +func FleetStateCode_Values() []string { + return []string{ + FleetStateCodeSubmitted, + FleetStateCodeActive, + FleetStateCodeDeleted, + FleetStateCodeFailed, + FleetStateCodeDeletedRunning, + FleetStateCodeDeletedTerminating, + FleetStateCodeModifying, + } +} + const ( // FleetTypeRequest is a FleetType enum value FleetTypeRequest = "request" @@ -110197,6 +116098,15 @@ const ( FleetTypeInstant = "instant" ) +// FleetType_Values returns all elements of the FleetType enum +func FleetType_Values() []string { + return []string{ + FleetTypeRequest, + FleetTypeMaintain, + FleetTypeInstant, + } +} + const ( // FlowLogsResourceTypeVpc is a FlowLogsResourceType enum value FlowLogsResourceTypeVpc = "VPC" @@ -110208,6 +116118,15 @@ const ( FlowLogsResourceTypeNetworkInterface = "NetworkInterface" ) +// FlowLogsResourceType_Values returns all elements of the FlowLogsResourceType enum +func FlowLogsResourceType_Values() []string { + return []string{ + FlowLogsResourceTypeVpc, + FlowLogsResourceTypeSubnet, + FlowLogsResourceTypeNetworkInterface, + } +} + const ( // FpgaImageAttributeNameDescription is a FpgaImageAttributeName enum value FpgaImageAttributeNameDescription = "description" @@ -110222,6 +116141,16 @@ const ( FpgaImageAttributeNameProductCodes = "productCodes" ) +// FpgaImageAttributeName_Values returns all elements of the FpgaImageAttributeName enum +func FpgaImageAttributeName_Values() []string { + return []string{ + FpgaImageAttributeNameDescription, + FpgaImageAttributeNameName, + FpgaImageAttributeNameLoadPermission, + FpgaImageAttributeNameProductCodes, + } +} + const ( // FpgaImageStateCodePending is a FpgaImageStateCode enum value FpgaImageStateCodePending = "pending" @@ -110236,11 +116165,28 @@ const ( FpgaImageStateCodeUnavailable = "unavailable" ) +// FpgaImageStateCode_Values returns all elements of the FpgaImageStateCode enum +func FpgaImageStateCode_Values() []string { + return []string{ + FpgaImageStateCodePending, + FpgaImageStateCodeFailed, + FpgaImageStateCodeAvailable, + FpgaImageStateCodeUnavailable, + } +} + const ( // GatewayTypeIpsec1 is a GatewayType enum value GatewayTypeIpsec1 = "ipsec.1" ) +// GatewayType_Values returns all elements of the GatewayType enum +func GatewayType_Values() []string { + return []string{ + GatewayTypeIpsec1, + } +} + const ( // HostRecoveryOn is a HostRecovery enum value HostRecoveryOn = "on" @@ -110249,6 +116195,14 @@ const ( HostRecoveryOff = "off" ) +// HostRecovery_Values returns all elements of the HostRecovery enum +func HostRecovery_Values() []string { + return []string{ + HostRecoveryOn, + HostRecoveryOff, + } +} + const ( // HostTenancyDedicated is a HostTenancy enum value HostTenancyDedicated = "dedicated" @@ -110257,6 +116211,14 @@ const ( HostTenancyHost = "host" ) +// HostTenancy_Values returns all elements of the HostTenancy enum +func HostTenancy_Values() []string { + return []string{ + HostTenancyDedicated, + HostTenancyHost, + } +} + const ( // HttpTokensStateOptional is a HttpTokensState enum value HttpTokensStateOptional = "optional" @@ -110265,6 +116227,14 @@ const ( HttpTokensStateRequired = "required" ) +// HttpTokensState_Values returns all elements of the HttpTokensState enum +func HttpTokensState_Values() []string { + return []string{ + HttpTokensStateOptional, + HttpTokensStateRequired, + } +} + const ( // HypervisorTypeOvm is a HypervisorType enum value HypervisorTypeOvm = "ovm" @@ -110273,6 +116243,14 @@ const ( HypervisorTypeXen = "xen" ) +// HypervisorType_Values returns all elements of the HypervisorType enum +func HypervisorType_Values() []string { + return []string{ + HypervisorTypeOvm, + HypervisorTypeXen, + } +} + const ( // IamInstanceProfileAssociationStateAssociating is a IamInstanceProfileAssociationState enum value IamInstanceProfileAssociationStateAssociating = "associating" @@ -110287,6 +116265,16 @@ const ( IamInstanceProfileAssociationStateDisassociated = "disassociated" ) +// IamInstanceProfileAssociationState_Values returns all elements of the IamInstanceProfileAssociationState enum +func IamInstanceProfileAssociationState_Values() []string { + return []string{ + IamInstanceProfileAssociationStateAssociating, + IamInstanceProfileAssociationStateAssociated, + IamInstanceProfileAssociationStateDisassociating, + IamInstanceProfileAssociationStateDisassociated, + } +} + const ( // ImageAttributeNameDescription is a ImageAttributeName enum value ImageAttributeNameDescription = "description" @@ -110310,6 +116298,19 @@ const ( ImageAttributeNameSriovNetSupport = "sriovNetSupport" ) +// ImageAttributeName_Values returns all elements of the ImageAttributeName enum +func ImageAttributeName_Values() []string { + return []string{ + ImageAttributeNameDescription, + ImageAttributeNameKernel, + ImageAttributeNameRamdisk, + ImageAttributeNameLaunchPermission, + ImageAttributeNameProductCodes, + ImageAttributeNameBlockDeviceMapping, + ImageAttributeNameSriovNetSupport, + } +} + const ( // ImageStatePending is a ImageState enum value ImageStatePending = "pending" @@ -110333,6 +116334,19 @@ const ( ImageStateError = "error" ) +// ImageState_Values returns all elements of the ImageState enum +func ImageState_Values() []string { + return []string{ + ImageStatePending, + ImageStateAvailable, + ImageStateInvalid, + ImageStateDeregistered, + ImageStateTransient, + ImageStateFailed, + ImageStateError, + } +} + const ( // ImageTypeValuesMachine is a ImageTypeValues enum value ImageTypeValuesMachine = "machine" @@ -110344,6 +116358,15 @@ const ( ImageTypeValuesRamdisk = "ramdisk" ) +// ImageTypeValues_Values returns all elements of the ImageTypeValues enum +func ImageTypeValues_Values() []string { + return []string{ + ImageTypeValuesMachine, + ImageTypeValuesKernel, + ImageTypeValuesRamdisk, + } +} + const ( // InstanceAttributeNameInstanceType is a InstanceAttributeName enum value InstanceAttributeNameInstanceType = "instanceType" @@ -110388,6 +116411,26 @@ const ( InstanceAttributeNameEnaSupport = "enaSupport" ) +// InstanceAttributeName_Values returns all elements of the InstanceAttributeName enum +func InstanceAttributeName_Values() []string { + return []string{ + InstanceAttributeNameInstanceType, + InstanceAttributeNameKernel, + InstanceAttributeNameRamdisk, + InstanceAttributeNameUserData, + InstanceAttributeNameDisableApiTermination, + InstanceAttributeNameInstanceInitiatedShutdownBehavior, + InstanceAttributeNameRootDeviceName, + InstanceAttributeNameBlockDeviceMapping, + InstanceAttributeNameProductCodes, + InstanceAttributeNameSourceDestCheck, + InstanceAttributeNameGroupSet, + InstanceAttributeNameEbsOptimized, + InstanceAttributeNameSriovNetSupport, + InstanceAttributeNameEnaSupport, + } +} + const ( // InstanceHealthStatusHealthy is a InstanceHealthStatus enum value InstanceHealthStatusHealthy = "healthy" @@ -110396,6 +116439,14 @@ const ( InstanceHealthStatusUnhealthy = "unhealthy" ) +// InstanceHealthStatus_Values returns all elements of the InstanceHealthStatus enum +func InstanceHealthStatus_Values() []string { + return []string{ + InstanceHealthStatusHealthy, + InstanceHealthStatusUnhealthy, + } +} + const ( // InstanceInterruptionBehaviorHibernate is a InstanceInterruptionBehavior enum value InstanceInterruptionBehaviorHibernate = "hibernate" @@ -110407,6 +116458,15 @@ const ( InstanceInterruptionBehaviorTerminate = "terminate" ) +// InstanceInterruptionBehavior_Values returns all elements of the InstanceInterruptionBehavior enum +func InstanceInterruptionBehavior_Values() []string { + return []string{ + InstanceInterruptionBehaviorHibernate, + InstanceInterruptionBehaviorStop, + InstanceInterruptionBehaviorTerminate, + } +} + const ( // InstanceLifecycleSpot is a InstanceLifecycle enum value InstanceLifecycleSpot = "spot" @@ -110415,6 +116475,14 @@ const ( InstanceLifecycleOnDemand = "on-demand" ) +// InstanceLifecycle_Values returns all elements of the InstanceLifecycle enum +func InstanceLifecycle_Values() []string { + return []string{ + InstanceLifecycleSpot, + InstanceLifecycleOnDemand, + } +} + const ( // InstanceLifecycleTypeSpot is a InstanceLifecycleType enum value InstanceLifecycleTypeSpot = "spot" @@ -110423,6 +116491,14 @@ const ( InstanceLifecycleTypeScheduled = "scheduled" ) +// InstanceLifecycleType_Values returns all elements of the InstanceLifecycleType enum +func InstanceLifecycleType_Values() []string { + return []string{ + InstanceLifecycleTypeSpot, + InstanceLifecycleTypeScheduled, + } +} + const ( // InstanceMatchCriteriaOpen is a InstanceMatchCriteria enum value InstanceMatchCriteriaOpen = "open" @@ -110431,6 +116507,14 @@ const ( InstanceMatchCriteriaTargeted = "targeted" ) +// InstanceMatchCriteria_Values returns all elements of the InstanceMatchCriteria enum +func InstanceMatchCriteria_Values() []string { + return []string{ + InstanceMatchCriteriaOpen, + InstanceMatchCriteriaTargeted, + } +} + const ( // InstanceMetadataEndpointStateDisabled is a InstanceMetadataEndpointState enum value InstanceMetadataEndpointStateDisabled = "disabled" @@ -110439,6 +116523,14 @@ const ( InstanceMetadataEndpointStateEnabled = "enabled" ) +// InstanceMetadataEndpointState_Values returns all elements of the InstanceMetadataEndpointState enum +func InstanceMetadataEndpointState_Values() []string { + return []string{ + InstanceMetadataEndpointStateDisabled, + InstanceMetadataEndpointStateEnabled, + } +} + const ( // InstanceMetadataOptionsStatePending is a InstanceMetadataOptionsState enum value InstanceMetadataOptionsStatePending = "pending" @@ -110447,6 +116539,14 @@ const ( InstanceMetadataOptionsStateApplied = "applied" ) +// InstanceMetadataOptionsState_Values returns all elements of the InstanceMetadataOptionsState enum +func InstanceMetadataOptionsState_Values() []string { + return []string{ + InstanceMetadataOptionsStatePending, + InstanceMetadataOptionsStateApplied, + } +} + const ( // InstanceStateNamePending is a InstanceStateName enum value InstanceStateNamePending = "pending" @@ -110467,6 +116567,18 @@ const ( InstanceStateNameStopped = "stopped" ) +// InstanceStateName_Values returns all elements of the InstanceStateName enum +func InstanceStateName_Values() []string { + return []string{ + InstanceStateNamePending, + InstanceStateNameRunning, + InstanceStateNameShuttingDown, + InstanceStateNameTerminated, + InstanceStateNameStopping, + InstanceStateNameStopped, + } +} + const ( // InstanceTypeT1Micro is a InstanceType enum value InstanceTypeT1Micro = "t1.micro" @@ -110534,6 +116646,27 @@ const ( // InstanceTypeT3a2xlarge is a InstanceType enum value InstanceTypeT3a2xlarge = "t3a.2xlarge" + // InstanceTypeT4gNano is a InstanceType enum value + InstanceTypeT4gNano = "t4g.nano" + + // InstanceTypeT4gMicro is a InstanceType enum value + InstanceTypeT4gMicro = "t4g.micro" + + // InstanceTypeT4gSmall is a InstanceType enum value + InstanceTypeT4gSmall = "t4g.small" + + // InstanceTypeT4gMedium is a InstanceType enum value + InstanceTypeT4gMedium = "t4g.medium" + + // InstanceTypeT4gLarge is a InstanceType enum value + InstanceTypeT4gLarge = "t4g.large" + + // InstanceTypeT4gXlarge is a InstanceType enum value + InstanceTypeT4gXlarge = "t4g.xlarge" + + // InstanceTypeT4g2xlarge is a InstanceType enum value + InstanceTypeT4g2xlarge = "t4g.2xlarge" + // InstanceTypeM1Small is a InstanceType enum value InstanceTypeM1Small = "m1.small" @@ -110723,6 +116856,60 @@ const ( // InstanceTypeR5ad24xlarge is a InstanceType enum value InstanceTypeR5ad24xlarge = "r5ad.24xlarge" + // InstanceTypeR6gMetal is a InstanceType enum value + InstanceTypeR6gMetal = "r6g.metal" + + // InstanceTypeR6gMedium is a InstanceType enum value + InstanceTypeR6gMedium = "r6g.medium" + + // InstanceTypeR6gLarge is a InstanceType enum value + InstanceTypeR6gLarge = "r6g.large" + + // InstanceTypeR6gXlarge is a InstanceType enum value + InstanceTypeR6gXlarge = "r6g.xlarge" + + // InstanceTypeR6g2xlarge is a InstanceType enum value + InstanceTypeR6g2xlarge = "r6g.2xlarge" + + // InstanceTypeR6g4xlarge is a InstanceType enum value + InstanceTypeR6g4xlarge = "r6g.4xlarge" + + // InstanceTypeR6g8xlarge is a InstanceType enum value + InstanceTypeR6g8xlarge = "r6g.8xlarge" + + // InstanceTypeR6g12xlarge is a InstanceType enum value + InstanceTypeR6g12xlarge = "r6g.12xlarge" + + // InstanceTypeR6g16xlarge is a InstanceType enum value + InstanceTypeR6g16xlarge = "r6g.16xlarge" + + // InstanceTypeR6gdMetal is a InstanceType enum value + InstanceTypeR6gdMetal = "r6gd.metal" + + // InstanceTypeR6gdMedium is a InstanceType enum value + InstanceTypeR6gdMedium = "r6gd.medium" + + // InstanceTypeR6gdLarge is a InstanceType enum value + InstanceTypeR6gdLarge = "r6gd.large" + + // InstanceTypeR6gdXlarge is a InstanceType enum value + InstanceTypeR6gdXlarge = "r6gd.xlarge" + + // InstanceTypeR6gd2xlarge is a InstanceType enum value + InstanceTypeR6gd2xlarge = "r6gd.2xlarge" + + // InstanceTypeR6gd4xlarge is a InstanceType enum value + InstanceTypeR6gd4xlarge = "r6gd.4xlarge" + + // InstanceTypeR6gd8xlarge is a InstanceType enum value + InstanceTypeR6gd8xlarge = "r6gd.8xlarge" + + // InstanceTypeR6gd12xlarge is a InstanceType enum value + InstanceTypeR6gd12xlarge = "r6gd.12xlarge" + + // InstanceTypeR6gd16xlarge is a InstanceType enum value + InstanceTypeR6gd16xlarge = "r6gd.16xlarge" + // InstanceTypeX116xlarge is a InstanceType enum value InstanceTypeX116xlarge = "x1.16xlarge" @@ -110873,6 +117060,54 @@ const ( // InstanceTypeC5Metal is a InstanceType enum value InstanceTypeC5Metal = "c5.metal" + // InstanceTypeC5aLarge is a InstanceType enum value + InstanceTypeC5aLarge = "c5a.large" + + // InstanceTypeC5aXlarge is a InstanceType enum value + InstanceTypeC5aXlarge = "c5a.xlarge" + + // InstanceTypeC5a2xlarge is a InstanceType enum value + InstanceTypeC5a2xlarge = "c5a.2xlarge" + + // InstanceTypeC5a4xlarge is a InstanceType enum value + InstanceTypeC5a4xlarge = "c5a.4xlarge" + + // InstanceTypeC5a8xlarge is a InstanceType enum value + InstanceTypeC5a8xlarge = "c5a.8xlarge" + + // InstanceTypeC5a12xlarge is a InstanceType enum value + InstanceTypeC5a12xlarge = "c5a.12xlarge" + + // InstanceTypeC5a16xlarge is a InstanceType enum value + InstanceTypeC5a16xlarge = "c5a.16xlarge" + + // InstanceTypeC5a24xlarge is a InstanceType enum value + InstanceTypeC5a24xlarge = "c5a.24xlarge" + + // InstanceTypeC5adLarge is a InstanceType enum value + InstanceTypeC5adLarge = "c5ad.large" + + // InstanceTypeC5adXlarge is a InstanceType enum value + InstanceTypeC5adXlarge = "c5ad.xlarge" + + // InstanceTypeC5ad2xlarge is a InstanceType enum value + InstanceTypeC5ad2xlarge = "c5ad.2xlarge" + + // InstanceTypeC5ad4xlarge is a InstanceType enum value + InstanceTypeC5ad4xlarge = "c5ad.4xlarge" + + // InstanceTypeC5ad8xlarge is a InstanceType enum value + InstanceTypeC5ad8xlarge = "c5ad.8xlarge" + + // InstanceTypeC5ad12xlarge is a InstanceType enum value + InstanceTypeC5ad12xlarge = "c5ad.12xlarge" + + // InstanceTypeC5ad16xlarge is a InstanceType enum value + InstanceTypeC5ad16xlarge = "c5ad.16xlarge" + + // InstanceTypeC5ad24xlarge is a InstanceType enum value + InstanceTypeC5ad24xlarge = "c5ad.24xlarge" + // InstanceTypeC5dLarge is a InstanceType enum value InstanceTypeC5dLarge = "c5d.large" @@ -110918,6 +117153,60 @@ const ( // InstanceTypeC5n18xlarge is a InstanceType enum value InstanceTypeC5n18xlarge = "c5n.18xlarge" + // InstanceTypeC6gMetal is a InstanceType enum value + InstanceTypeC6gMetal = "c6g.metal" + + // InstanceTypeC6gMedium is a InstanceType enum value + InstanceTypeC6gMedium = "c6g.medium" + + // InstanceTypeC6gLarge is a InstanceType enum value + InstanceTypeC6gLarge = "c6g.large" + + // InstanceTypeC6gXlarge is a InstanceType enum value + InstanceTypeC6gXlarge = "c6g.xlarge" + + // InstanceTypeC6g2xlarge is a InstanceType enum value + InstanceTypeC6g2xlarge = "c6g.2xlarge" + + // InstanceTypeC6g4xlarge is a InstanceType enum value + InstanceTypeC6g4xlarge = "c6g.4xlarge" + + // InstanceTypeC6g8xlarge is a InstanceType enum value + InstanceTypeC6g8xlarge = "c6g.8xlarge" + + // InstanceTypeC6g12xlarge is a InstanceType enum value + InstanceTypeC6g12xlarge = "c6g.12xlarge" + + // InstanceTypeC6g16xlarge is a InstanceType enum value + InstanceTypeC6g16xlarge = "c6g.16xlarge" + + // InstanceTypeC6gdMetal is a InstanceType enum value + InstanceTypeC6gdMetal = "c6gd.metal" + + // InstanceTypeC6gdMedium is a InstanceType enum value + InstanceTypeC6gdMedium = "c6gd.medium" + + // InstanceTypeC6gdLarge is a InstanceType enum value + InstanceTypeC6gdLarge = "c6gd.large" + + // InstanceTypeC6gdXlarge is a InstanceType enum value + InstanceTypeC6gdXlarge = "c6gd.xlarge" + + // InstanceTypeC6gd2xlarge is a InstanceType enum value + InstanceTypeC6gd2xlarge = "c6gd.2xlarge" + + // InstanceTypeC6gd4xlarge is a InstanceType enum value + InstanceTypeC6gd4xlarge = "c6gd.4xlarge" + + // InstanceTypeC6gd8xlarge is a InstanceType enum value + InstanceTypeC6gd8xlarge = "c6gd.8xlarge" + + // InstanceTypeC6gd12xlarge is a InstanceType enum value + InstanceTypeC6gd12xlarge = "c6gd.12xlarge" + + // InstanceTypeC6gd16xlarge is a InstanceType enum value + InstanceTypeC6gd16xlarge = "c6gd.16xlarge" + // InstanceTypeCc14xlarge is a InstanceType enum value InstanceTypeCc14xlarge = "cc1.4xlarge" @@ -110960,6 +117249,9 @@ const ( // InstanceTypeG4dn16xlarge is a InstanceType enum value InstanceTypeG4dn16xlarge = "g4dn.16xlarge" + // InstanceTypeG4dnMetal is a InstanceType enum value + InstanceTypeG4dnMetal = "g4dn.metal" + // InstanceTypeCg14xlarge is a InstanceType enum value InstanceTypeCg14xlarge = "cg1.4xlarge" @@ -111280,8 +117572,417 @@ const ( // InstanceTypeInf124xlarge is a InstanceType enum value InstanceTypeInf124xlarge = "inf1.24xlarge" + + // InstanceTypeM6gMetal is a InstanceType enum value + InstanceTypeM6gMetal = "m6g.metal" + + // InstanceTypeM6gMedium is a InstanceType enum value + InstanceTypeM6gMedium = "m6g.medium" + + // InstanceTypeM6gLarge is a InstanceType enum value + InstanceTypeM6gLarge = "m6g.large" + + // InstanceTypeM6gXlarge is a InstanceType enum value + InstanceTypeM6gXlarge = "m6g.xlarge" + + // InstanceTypeM6g2xlarge is a InstanceType enum value + InstanceTypeM6g2xlarge = "m6g.2xlarge" + + // InstanceTypeM6g4xlarge is a InstanceType enum value + InstanceTypeM6g4xlarge = "m6g.4xlarge" + + // InstanceTypeM6g8xlarge is a InstanceType enum value + InstanceTypeM6g8xlarge = "m6g.8xlarge" + + // InstanceTypeM6g12xlarge is a InstanceType enum value + InstanceTypeM6g12xlarge = "m6g.12xlarge" + + // InstanceTypeM6g16xlarge is a InstanceType enum value + InstanceTypeM6g16xlarge = "m6g.16xlarge" + + // InstanceTypeM6gdMetal is a InstanceType enum value + InstanceTypeM6gdMetal = "m6gd.metal" + + // InstanceTypeM6gdMedium is a InstanceType enum value + InstanceTypeM6gdMedium = "m6gd.medium" + + // InstanceTypeM6gdLarge is a InstanceType enum value + InstanceTypeM6gdLarge = "m6gd.large" + + // InstanceTypeM6gdXlarge is a InstanceType enum value + InstanceTypeM6gdXlarge = "m6gd.xlarge" + + // InstanceTypeM6gd2xlarge is a InstanceType enum value + InstanceTypeM6gd2xlarge = "m6gd.2xlarge" + + // InstanceTypeM6gd4xlarge is a InstanceType enum value + InstanceTypeM6gd4xlarge = "m6gd.4xlarge" + + // InstanceTypeM6gd8xlarge is a InstanceType enum value + InstanceTypeM6gd8xlarge = "m6gd.8xlarge" + + // InstanceTypeM6gd12xlarge is a InstanceType enum value + InstanceTypeM6gd12xlarge = "m6gd.12xlarge" + + // InstanceTypeM6gd16xlarge is a InstanceType enum value + InstanceTypeM6gd16xlarge = "m6gd.16xlarge" ) +// InstanceType_Values returns all elements of the InstanceType enum +func InstanceType_Values() []string { + return []string{ + InstanceTypeT1Micro, + InstanceTypeT2Nano, + InstanceTypeT2Micro, + InstanceTypeT2Small, + InstanceTypeT2Medium, + InstanceTypeT2Large, + InstanceTypeT2Xlarge, + InstanceTypeT22xlarge, + InstanceTypeT3Nano, + InstanceTypeT3Micro, + InstanceTypeT3Small, + InstanceTypeT3Medium, + InstanceTypeT3Large, + InstanceTypeT3Xlarge, + InstanceTypeT32xlarge, + InstanceTypeT3aNano, + InstanceTypeT3aMicro, + InstanceTypeT3aSmall, + InstanceTypeT3aMedium, + InstanceTypeT3aLarge, + InstanceTypeT3aXlarge, + InstanceTypeT3a2xlarge, + InstanceTypeT4gNano, + InstanceTypeT4gMicro, + InstanceTypeT4gSmall, + InstanceTypeT4gMedium, + InstanceTypeT4gLarge, + InstanceTypeT4gXlarge, + InstanceTypeT4g2xlarge, + InstanceTypeM1Small, + InstanceTypeM1Medium, + InstanceTypeM1Large, + InstanceTypeM1Xlarge, + InstanceTypeM3Medium, + InstanceTypeM3Large, + InstanceTypeM3Xlarge, + InstanceTypeM32xlarge, + InstanceTypeM4Large, + InstanceTypeM4Xlarge, + InstanceTypeM42xlarge, + InstanceTypeM44xlarge, + InstanceTypeM410xlarge, + InstanceTypeM416xlarge, + InstanceTypeM2Xlarge, + InstanceTypeM22xlarge, + InstanceTypeM24xlarge, + InstanceTypeCr18xlarge, + InstanceTypeR3Large, + InstanceTypeR3Xlarge, + InstanceTypeR32xlarge, + InstanceTypeR34xlarge, + InstanceTypeR38xlarge, + InstanceTypeR4Large, + InstanceTypeR4Xlarge, + InstanceTypeR42xlarge, + InstanceTypeR44xlarge, + InstanceTypeR48xlarge, + InstanceTypeR416xlarge, + InstanceTypeR5Large, + InstanceTypeR5Xlarge, + InstanceTypeR52xlarge, + InstanceTypeR54xlarge, + InstanceTypeR58xlarge, + InstanceTypeR512xlarge, + InstanceTypeR516xlarge, + InstanceTypeR524xlarge, + InstanceTypeR5Metal, + InstanceTypeR5aLarge, + InstanceTypeR5aXlarge, + InstanceTypeR5a2xlarge, + InstanceTypeR5a4xlarge, + InstanceTypeR5a8xlarge, + InstanceTypeR5a12xlarge, + InstanceTypeR5a16xlarge, + InstanceTypeR5a24xlarge, + InstanceTypeR5dLarge, + InstanceTypeR5dXlarge, + InstanceTypeR5d2xlarge, + InstanceTypeR5d4xlarge, + InstanceTypeR5d8xlarge, + InstanceTypeR5d12xlarge, + InstanceTypeR5d16xlarge, + InstanceTypeR5d24xlarge, + InstanceTypeR5dMetal, + InstanceTypeR5adLarge, + InstanceTypeR5adXlarge, + InstanceTypeR5ad2xlarge, + InstanceTypeR5ad4xlarge, + InstanceTypeR5ad8xlarge, + InstanceTypeR5ad12xlarge, + InstanceTypeR5ad16xlarge, + InstanceTypeR5ad24xlarge, + InstanceTypeR6gMetal, + InstanceTypeR6gMedium, + InstanceTypeR6gLarge, + InstanceTypeR6gXlarge, + InstanceTypeR6g2xlarge, + InstanceTypeR6g4xlarge, + InstanceTypeR6g8xlarge, + InstanceTypeR6g12xlarge, + InstanceTypeR6g16xlarge, + InstanceTypeR6gdMetal, + InstanceTypeR6gdMedium, + InstanceTypeR6gdLarge, + InstanceTypeR6gdXlarge, + InstanceTypeR6gd2xlarge, + InstanceTypeR6gd4xlarge, + InstanceTypeR6gd8xlarge, + InstanceTypeR6gd12xlarge, + InstanceTypeR6gd16xlarge, + InstanceTypeX116xlarge, + InstanceTypeX132xlarge, + InstanceTypeX1eXlarge, + InstanceTypeX1e2xlarge, + InstanceTypeX1e4xlarge, + InstanceTypeX1e8xlarge, + InstanceTypeX1e16xlarge, + InstanceTypeX1e32xlarge, + InstanceTypeI2Xlarge, + InstanceTypeI22xlarge, + InstanceTypeI24xlarge, + InstanceTypeI28xlarge, + InstanceTypeI3Large, + InstanceTypeI3Xlarge, + InstanceTypeI32xlarge, + InstanceTypeI34xlarge, + InstanceTypeI38xlarge, + InstanceTypeI316xlarge, + InstanceTypeI3Metal, + InstanceTypeI3enLarge, + InstanceTypeI3enXlarge, + InstanceTypeI3en2xlarge, + InstanceTypeI3en3xlarge, + InstanceTypeI3en6xlarge, + InstanceTypeI3en12xlarge, + InstanceTypeI3en24xlarge, + InstanceTypeI3enMetal, + InstanceTypeHi14xlarge, + InstanceTypeHs18xlarge, + InstanceTypeC1Medium, + InstanceTypeC1Xlarge, + InstanceTypeC3Large, + InstanceTypeC3Xlarge, + InstanceTypeC32xlarge, + InstanceTypeC34xlarge, + InstanceTypeC38xlarge, + InstanceTypeC4Large, + InstanceTypeC4Xlarge, + InstanceTypeC42xlarge, + InstanceTypeC44xlarge, + InstanceTypeC48xlarge, + InstanceTypeC5Large, + InstanceTypeC5Xlarge, + InstanceTypeC52xlarge, + InstanceTypeC54xlarge, + InstanceTypeC59xlarge, + InstanceTypeC512xlarge, + InstanceTypeC518xlarge, + InstanceTypeC524xlarge, + InstanceTypeC5Metal, + InstanceTypeC5aLarge, + InstanceTypeC5aXlarge, + InstanceTypeC5a2xlarge, + InstanceTypeC5a4xlarge, + InstanceTypeC5a8xlarge, + InstanceTypeC5a12xlarge, + InstanceTypeC5a16xlarge, + InstanceTypeC5a24xlarge, + InstanceTypeC5adLarge, + InstanceTypeC5adXlarge, + InstanceTypeC5ad2xlarge, + InstanceTypeC5ad4xlarge, + InstanceTypeC5ad8xlarge, + InstanceTypeC5ad12xlarge, + InstanceTypeC5ad16xlarge, + InstanceTypeC5ad24xlarge, + InstanceTypeC5dLarge, + InstanceTypeC5dXlarge, + InstanceTypeC5d2xlarge, + InstanceTypeC5d4xlarge, + InstanceTypeC5d9xlarge, + InstanceTypeC5d12xlarge, + InstanceTypeC5d18xlarge, + InstanceTypeC5d24xlarge, + InstanceTypeC5dMetal, + InstanceTypeC5nLarge, + InstanceTypeC5nXlarge, + InstanceTypeC5n2xlarge, + InstanceTypeC5n4xlarge, + InstanceTypeC5n9xlarge, + InstanceTypeC5n18xlarge, + InstanceTypeC6gMetal, + InstanceTypeC6gMedium, + InstanceTypeC6gLarge, + InstanceTypeC6gXlarge, + InstanceTypeC6g2xlarge, + InstanceTypeC6g4xlarge, + InstanceTypeC6g8xlarge, + InstanceTypeC6g12xlarge, + InstanceTypeC6g16xlarge, + InstanceTypeC6gdMetal, + InstanceTypeC6gdMedium, + InstanceTypeC6gdLarge, + InstanceTypeC6gdXlarge, + InstanceTypeC6gd2xlarge, + InstanceTypeC6gd4xlarge, + InstanceTypeC6gd8xlarge, + InstanceTypeC6gd12xlarge, + InstanceTypeC6gd16xlarge, + InstanceTypeCc14xlarge, + InstanceTypeCc28xlarge, + InstanceTypeG22xlarge, + InstanceTypeG28xlarge, + InstanceTypeG34xlarge, + InstanceTypeG38xlarge, + InstanceTypeG316xlarge, + InstanceTypeG3sXlarge, + InstanceTypeG4dnXlarge, + InstanceTypeG4dn2xlarge, + InstanceTypeG4dn4xlarge, + InstanceTypeG4dn8xlarge, + InstanceTypeG4dn12xlarge, + InstanceTypeG4dn16xlarge, + InstanceTypeG4dnMetal, + InstanceTypeCg14xlarge, + InstanceTypeP2Xlarge, + InstanceTypeP28xlarge, + InstanceTypeP216xlarge, + InstanceTypeP32xlarge, + InstanceTypeP38xlarge, + InstanceTypeP316xlarge, + InstanceTypeP3dn24xlarge, + InstanceTypeD2Xlarge, + InstanceTypeD22xlarge, + InstanceTypeD24xlarge, + InstanceTypeD28xlarge, + InstanceTypeF12xlarge, + InstanceTypeF14xlarge, + InstanceTypeF116xlarge, + InstanceTypeM5Large, + InstanceTypeM5Xlarge, + InstanceTypeM52xlarge, + InstanceTypeM54xlarge, + InstanceTypeM58xlarge, + InstanceTypeM512xlarge, + InstanceTypeM516xlarge, + InstanceTypeM524xlarge, + InstanceTypeM5Metal, + InstanceTypeM5aLarge, + InstanceTypeM5aXlarge, + InstanceTypeM5a2xlarge, + InstanceTypeM5a4xlarge, + InstanceTypeM5a8xlarge, + InstanceTypeM5a12xlarge, + InstanceTypeM5a16xlarge, + InstanceTypeM5a24xlarge, + InstanceTypeM5dLarge, + InstanceTypeM5dXlarge, + InstanceTypeM5d2xlarge, + InstanceTypeM5d4xlarge, + InstanceTypeM5d8xlarge, + InstanceTypeM5d12xlarge, + InstanceTypeM5d16xlarge, + InstanceTypeM5d24xlarge, + InstanceTypeM5dMetal, + InstanceTypeM5adLarge, + InstanceTypeM5adXlarge, + InstanceTypeM5ad2xlarge, + InstanceTypeM5ad4xlarge, + InstanceTypeM5ad8xlarge, + InstanceTypeM5ad12xlarge, + InstanceTypeM5ad16xlarge, + InstanceTypeM5ad24xlarge, + InstanceTypeH12xlarge, + InstanceTypeH14xlarge, + InstanceTypeH18xlarge, + InstanceTypeH116xlarge, + InstanceTypeZ1dLarge, + InstanceTypeZ1dXlarge, + InstanceTypeZ1d2xlarge, + InstanceTypeZ1d3xlarge, + InstanceTypeZ1d6xlarge, + InstanceTypeZ1d12xlarge, + InstanceTypeZ1dMetal, + InstanceTypeU6tb1Metal, + InstanceTypeU9tb1Metal, + InstanceTypeU12tb1Metal, + InstanceTypeU18tb1Metal, + InstanceTypeU24tb1Metal, + InstanceTypeA1Medium, + InstanceTypeA1Large, + InstanceTypeA1Xlarge, + InstanceTypeA12xlarge, + InstanceTypeA14xlarge, + InstanceTypeA1Metal, + InstanceTypeM5dnLarge, + InstanceTypeM5dnXlarge, + InstanceTypeM5dn2xlarge, + InstanceTypeM5dn4xlarge, + InstanceTypeM5dn8xlarge, + InstanceTypeM5dn12xlarge, + InstanceTypeM5dn16xlarge, + InstanceTypeM5dn24xlarge, + InstanceTypeM5nLarge, + InstanceTypeM5nXlarge, + InstanceTypeM5n2xlarge, + InstanceTypeM5n4xlarge, + InstanceTypeM5n8xlarge, + InstanceTypeM5n12xlarge, + InstanceTypeM5n16xlarge, + InstanceTypeM5n24xlarge, + InstanceTypeR5dnLarge, + InstanceTypeR5dnXlarge, + InstanceTypeR5dn2xlarge, + InstanceTypeR5dn4xlarge, + InstanceTypeR5dn8xlarge, + InstanceTypeR5dn12xlarge, + InstanceTypeR5dn16xlarge, + InstanceTypeR5dn24xlarge, + InstanceTypeR5nLarge, + InstanceTypeR5nXlarge, + InstanceTypeR5n2xlarge, + InstanceTypeR5n4xlarge, + InstanceTypeR5n8xlarge, + InstanceTypeR5n12xlarge, + InstanceTypeR5n16xlarge, + InstanceTypeR5n24xlarge, + InstanceTypeInf1Xlarge, + InstanceTypeInf12xlarge, + InstanceTypeInf16xlarge, + InstanceTypeInf124xlarge, + InstanceTypeM6gMetal, + InstanceTypeM6gMedium, + InstanceTypeM6gLarge, + InstanceTypeM6gXlarge, + InstanceTypeM6g2xlarge, + InstanceTypeM6g4xlarge, + InstanceTypeM6g8xlarge, + InstanceTypeM6g12xlarge, + InstanceTypeM6g16xlarge, + InstanceTypeM6gdMetal, + InstanceTypeM6gdMedium, + InstanceTypeM6gdLarge, + InstanceTypeM6gdXlarge, + InstanceTypeM6gd2xlarge, + InstanceTypeM6gd4xlarge, + InstanceTypeM6gd8xlarge, + InstanceTypeM6gd12xlarge, + InstanceTypeM6gd16xlarge, + } +} + const ( // InstanceTypeHypervisorNitro is a InstanceTypeHypervisor enum value InstanceTypeHypervisorNitro = "nitro" @@ -111290,6 +117991,14 @@ const ( InstanceTypeHypervisorXen = "xen" ) +// InstanceTypeHypervisor_Values returns all elements of the InstanceTypeHypervisor enum +func InstanceTypeHypervisor_Values() []string { + return []string{ + InstanceTypeHypervisorNitro, + InstanceTypeHypervisorXen, + } +} + const ( // InterfacePermissionTypeInstanceAttach is a InterfacePermissionType enum value InterfacePermissionTypeInstanceAttach = "INSTANCE-ATTACH" @@ -111298,6 +118007,14 @@ const ( InterfacePermissionTypeEipAssociate = "EIP-ASSOCIATE" ) +// InterfacePermissionType_Values returns all elements of the InterfacePermissionType enum +func InterfacePermissionType_Values() []string { + return []string{ + InterfacePermissionTypeInstanceAttach, + InterfacePermissionTypeEipAssociate, + } +} + const ( // Ipv6SupportValueEnable is a Ipv6SupportValue enum value Ipv6SupportValueEnable = "enable" @@ -111306,6 +118023,14 @@ const ( Ipv6SupportValueDisable = "disable" ) +// Ipv6SupportValue_Values returns all elements of the Ipv6SupportValue enum +func Ipv6SupportValue_Values() []string { + return []string{ + Ipv6SupportValueEnable, + Ipv6SupportValueDisable, + } +} + const ( // LaunchTemplateErrorCodeLaunchTemplateIdDoesNotExist is a LaunchTemplateErrorCode enum value LaunchTemplateErrorCodeLaunchTemplateIdDoesNotExist = "launchTemplateIdDoesNotExist" @@ -111326,6 +118051,18 @@ const ( LaunchTemplateErrorCodeUnexpectedError = "unexpectedError" ) +// LaunchTemplateErrorCode_Values returns all elements of the LaunchTemplateErrorCode enum +func LaunchTemplateErrorCode_Values() []string { + return []string{ + LaunchTemplateErrorCodeLaunchTemplateIdDoesNotExist, + LaunchTemplateErrorCodeLaunchTemplateIdMalformed, + LaunchTemplateErrorCodeLaunchTemplateNameDoesNotExist, + LaunchTemplateErrorCodeLaunchTemplateNameMalformed, + LaunchTemplateErrorCodeLaunchTemplateVersionDoesNotExist, + LaunchTemplateErrorCodeUnexpectedError, + } +} + const ( // LaunchTemplateHttpTokensStateOptional is a LaunchTemplateHttpTokensState enum value LaunchTemplateHttpTokensStateOptional = "optional" @@ -111334,6 +118071,14 @@ const ( LaunchTemplateHttpTokensStateRequired = "required" ) +// LaunchTemplateHttpTokensState_Values returns all elements of the LaunchTemplateHttpTokensState enum +func LaunchTemplateHttpTokensState_Values() []string { + return []string{ + LaunchTemplateHttpTokensStateOptional, + LaunchTemplateHttpTokensStateRequired, + } +} + const ( // LaunchTemplateInstanceMetadataEndpointStateDisabled is a LaunchTemplateInstanceMetadataEndpointState enum value LaunchTemplateInstanceMetadataEndpointStateDisabled = "disabled" @@ -111342,6 +118087,14 @@ const ( LaunchTemplateInstanceMetadataEndpointStateEnabled = "enabled" ) +// LaunchTemplateInstanceMetadataEndpointState_Values returns all elements of the LaunchTemplateInstanceMetadataEndpointState enum +func LaunchTemplateInstanceMetadataEndpointState_Values() []string { + return []string{ + LaunchTemplateInstanceMetadataEndpointStateDisabled, + LaunchTemplateInstanceMetadataEndpointStateEnabled, + } +} + const ( // LaunchTemplateInstanceMetadataOptionsStatePending is a LaunchTemplateInstanceMetadataOptionsState enum value LaunchTemplateInstanceMetadataOptionsStatePending = "pending" @@ -111350,6 +118103,14 @@ const ( LaunchTemplateInstanceMetadataOptionsStateApplied = "applied" ) +// LaunchTemplateInstanceMetadataOptionsState_Values returns all elements of the LaunchTemplateInstanceMetadataOptionsState enum +func LaunchTemplateInstanceMetadataOptionsState_Values() []string { + return []string{ + LaunchTemplateInstanceMetadataOptionsStatePending, + LaunchTemplateInstanceMetadataOptionsStateApplied, + } +} + const ( // ListingStateAvailable is a ListingState enum value ListingStateAvailable = "available" @@ -111364,6 +118125,16 @@ const ( ListingStatePending = "pending" ) +// ListingState_Values returns all elements of the ListingState enum +func ListingState_Values() []string { + return []string{ + ListingStateAvailable, + ListingStateSold, + ListingStateCancelled, + ListingStatePending, + } +} + const ( // ListingStatusActive is a ListingStatus enum value ListingStatusActive = "active" @@ -111378,6 +118149,16 @@ const ( ListingStatusClosed = "closed" ) +// ListingStatus_Values returns all elements of the ListingStatus enum +func ListingStatus_Values() []string { + return []string{ + ListingStatusActive, + ListingStatusPending, + ListingStatusCancelled, + ListingStatusClosed, + } +} + const ( // LocalGatewayRouteStatePending is a LocalGatewayRouteState enum value LocalGatewayRouteStatePending = "pending" @@ -111395,6 +118176,17 @@ const ( LocalGatewayRouteStateDeleted = "deleted" ) +// LocalGatewayRouteState_Values returns all elements of the LocalGatewayRouteState enum +func LocalGatewayRouteState_Values() []string { + return []string{ + LocalGatewayRouteStatePending, + LocalGatewayRouteStateActive, + LocalGatewayRouteStateBlackhole, + LocalGatewayRouteStateDeleting, + LocalGatewayRouteStateDeleted, + } +} + const ( // LocalGatewayRouteTypeStatic is a LocalGatewayRouteType enum value LocalGatewayRouteTypeStatic = "static" @@ -111403,6 +118195,14 @@ const ( LocalGatewayRouteTypePropagated = "propagated" ) +// LocalGatewayRouteType_Values returns all elements of the LocalGatewayRouteType enum +func LocalGatewayRouteType_Values() []string { + return []string{ + LocalGatewayRouteTypeStatic, + LocalGatewayRouteTypePropagated, + } +} + const ( // LocationTypeRegion is a LocationType enum value LocationTypeRegion = "region" @@ -111414,6 +118214,15 @@ const ( LocationTypeAvailabilityZoneId = "availability-zone-id" ) +// LocationType_Values returns all elements of the LocationType enum +func LocationType_Values() []string { + return []string{ + LocationTypeRegion, + LocationTypeAvailabilityZone, + LocationTypeAvailabilityZoneId, + } +} + const ( // LogDestinationTypeCloudWatchLogs is a LogDestinationType enum value LogDestinationTypeCloudWatchLogs = "cloud-watch-logs" @@ -111422,11 +118231,26 @@ const ( LogDestinationTypeS3 = "s3" ) +// LogDestinationType_Values returns all elements of the LogDestinationType enum +func LogDestinationType_Values() []string { + return []string{ + LogDestinationTypeCloudWatchLogs, + LogDestinationTypeS3, + } +} + const ( // MarketTypeSpot is a MarketType enum value MarketTypeSpot = "spot" ) +// MarketType_Values returns all elements of the MarketType enum +func MarketType_Values() []string { + return []string{ + MarketTypeSpot, + } +} + const ( // MembershipTypeStatic is a MembershipType enum value MembershipTypeStatic = "static" @@ -111435,6 +118259,14 @@ const ( MembershipTypeIgmp = "igmp" ) +// MembershipType_Values returns all elements of the MembershipType enum +func MembershipType_Values() []string { + return []string{ + MembershipTypeStatic, + MembershipTypeIgmp, + } +} + const ( // ModifyAvailabilityZoneOptInStatusOptedIn is a ModifyAvailabilityZoneOptInStatus enum value ModifyAvailabilityZoneOptInStatusOptedIn = "opted-in" @@ -111443,6 +118275,14 @@ const ( ModifyAvailabilityZoneOptInStatusNotOptedIn = "not-opted-in" ) +// ModifyAvailabilityZoneOptInStatus_Values returns all elements of the ModifyAvailabilityZoneOptInStatus enum +func ModifyAvailabilityZoneOptInStatus_Values() []string { + return []string{ + ModifyAvailabilityZoneOptInStatusOptedIn, + ModifyAvailabilityZoneOptInStatusNotOptedIn, + } +} + const ( // MonitoringStateDisabled is a MonitoringState enum value MonitoringStateDisabled = "disabled" @@ -111457,6 +118297,16 @@ const ( MonitoringStatePending = "pending" ) +// MonitoringState_Values returns all elements of the MonitoringState enum +func MonitoringState_Values() []string { + return []string{ + MonitoringStateDisabled, + MonitoringStateDisabling, + MonitoringStateEnabled, + MonitoringStatePending, + } +} + const ( // MoveStatusMovingToVpc is a MoveStatus enum value MoveStatusMovingToVpc = "movingToVpc" @@ -111465,6 +118315,14 @@ const ( MoveStatusRestoringToClassic = "restoringToClassic" ) +// MoveStatus_Values returns all elements of the MoveStatus enum +func MoveStatus_Values() []string { + return []string{ + MoveStatusMovingToVpc, + MoveStatusRestoringToClassic, + } +} + const ( // MulticastSupportValueEnable is a MulticastSupportValue enum value MulticastSupportValueEnable = "enable" @@ -111473,6 +118331,14 @@ const ( MulticastSupportValueDisable = "disable" ) +// MulticastSupportValue_Values returns all elements of the MulticastSupportValue enum +func MulticastSupportValue_Values() []string { + return []string{ + MulticastSupportValueEnable, + MulticastSupportValueDisable, + } +} + const ( // NatGatewayStatePending is a NatGatewayState enum value NatGatewayStatePending = "pending" @@ -111490,6 +118356,17 @@ const ( NatGatewayStateDeleted = "deleted" ) +// NatGatewayState_Values returns all elements of the NatGatewayState enum +func NatGatewayState_Values() []string { + return []string{ + NatGatewayStatePending, + NatGatewayStateFailed, + NatGatewayStateAvailable, + NatGatewayStateDeleting, + NatGatewayStateDeleted, + } +} + const ( // NetworkInterfaceAttributeDescription is a NetworkInterfaceAttribute enum value NetworkInterfaceAttributeDescription = "description" @@ -111504,11 +118381,28 @@ const ( NetworkInterfaceAttributeAttachment = "attachment" ) +// NetworkInterfaceAttribute_Values returns all elements of the NetworkInterfaceAttribute enum +func NetworkInterfaceAttribute_Values() []string { + return []string{ + NetworkInterfaceAttributeDescription, + NetworkInterfaceAttributeGroupSet, + NetworkInterfaceAttributeSourceDestCheck, + NetworkInterfaceAttributeAttachment, + } +} + const ( // NetworkInterfaceCreationTypeEfa is a NetworkInterfaceCreationType enum value NetworkInterfaceCreationTypeEfa = "efa" ) +// NetworkInterfaceCreationType_Values returns all elements of the NetworkInterfaceCreationType enum +func NetworkInterfaceCreationType_Values() []string { + return []string{ + NetworkInterfaceCreationTypeEfa, + } +} + const ( // NetworkInterfacePermissionStateCodePending is a NetworkInterfacePermissionStateCode enum value NetworkInterfacePermissionStateCodePending = "pending" @@ -111523,6 +118417,16 @@ const ( NetworkInterfacePermissionStateCodeRevoked = "revoked" ) +// NetworkInterfacePermissionStateCode_Values returns all elements of the NetworkInterfacePermissionStateCode enum +func NetworkInterfacePermissionStateCode_Values() []string { + return []string{ + NetworkInterfacePermissionStateCodePending, + NetworkInterfacePermissionStateCodeGranted, + NetworkInterfacePermissionStateCodeRevoking, + NetworkInterfacePermissionStateCodeRevoked, + } +} + const ( // NetworkInterfaceStatusAvailable is a NetworkInterfaceStatus enum value NetworkInterfaceStatusAvailable = "available" @@ -111540,6 +118444,17 @@ const ( NetworkInterfaceStatusDetaching = "detaching" ) +// NetworkInterfaceStatus_Values returns all elements of the NetworkInterfaceStatus enum +func NetworkInterfaceStatus_Values() []string { + return []string{ + NetworkInterfaceStatusAvailable, + NetworkInterfaceStatusAssociated, + NetworkInterfaceStatusAttaching, + NetworkInterfaceStatusInUse, + NetworkInterfaceStatusDetaching, + } +} + const ( // NetworkInterfaceTypeInterface is a NetworkInterfaceType enum value NetworkInterfaceTypeInterface = "interface" @@ -111551,6 +118466,15 @@ const ( NetworkInterfaceTypeEfa = "efa" ) +// NetworkInterfaceType_Values returns all elements of the NetworkInterfaceType enum +func NetworkInterfaceType_Values() []string { + return []string{ + NetworkInterfaceTypeInterface, + NetworkInterfaceTypeNatGateway, + NetworkInterfaceTypeEfa, + } +} + const ( // OfferingClassTypeStandard is a OfferingClassType enum value OfferingClassTypeStandard = "standard" @@ -111559,6 +118483,14 @@ const ( OfferingClassTypeConvertible = "convertible" ) +// OfferingClassType_Values returns all elements of the OfferingClassType enum +func OfferingClassType_Values() []string { + return []string{ + OfferingClassTypeStandard, + OfferingClassTypeConvertible, + } +} + const ( // OfferingTypeValuesHeavyUtilization is a OfferingTypeValues enum value OfferingTypeValuesHeavyUtilization = "Heavy Utilization" @@ -111579,6 +118511,18 @@ const ( OfferingTypeValuesAllUpfront = "All Upfront" ) +// OfferingTypeValues_Values returns all elements of the OfferingTypeValues enum +func OfferingTypeValues_Values() []string { + return []string{ + OfferingTypeValuesHeavyUtilization, + OfferingTypeValuesMediumUtilization, + OfferingTypeValuesLightUtilization, + OfferingTypeValuesNoUpfront, + OfferingTypeValuesPartialUpfront, + OfferingTypeValuesAllUpfront, + } +} + const ( // OnDemandAllocationStrategyLowestPrice is a OnDemandAllocationStrategy enum value OnDemandAllocationStrategyLowestPrice = "lowestPrice" @@ -111587,6 +118531,14 @@ const ( OnDemandAllocationStrategyPrioritized = "prioritized" ) +// OnDemandAllocationStrategy_Values returns all elements of the OnDemandAllocationStrategy enum +func OnDemandAllocationStrategy_Values() []string { + return []string{ + OnDemandAllocationStrategyLowestPrice, + OnDemandAllocationStrategyPrioritized, + } +} + const ( // OperationTypeAdd is a OperationType enum value OperationTypeAdd = "add" @@ -111595,6 +118547,14 @@ const ( OperationTypeRemove = "remove" ) +// OperationType_Values returns all elements of the OperationType enum +func OperationType_Values() []string { + return []string{ + OperationTypeAdd, + OperationTypeRemove, + } +} + const ( // PaymentOptionAllUpfront is a PaymentOption enum value PaymentOptionAllUpfront = "AllUpfront" @@ -111606,11 +118566,27 @@ const ( PaymentOptionNoUpfront = "NoUpfront" ) +// PaymentOption_Values returns all elements of the PaymentOption enum +func PaymentOption_Values() []string { + return []string{ + PaymentOptionAllUpfront, + PaymentOptionPartialUpfront, + PaymentOptionNoUpfront, + } +} + const ( // PermissionGroupAll is a PermissionGroup enum value PermissionGroupAll = "all" ) +// PermissionGroup_Values returns all elements of the PermissionGroup enum +func PermissionGroup_Values() []string { + return []string{ + PermissionGroupAll, + } +} + const ( // PlacementGroupStatePending is a PlacementGroupState enum value PlacementGroupStatePending = "pending" @@ -111625,6 +118601,16 @@ const ( PlacementGroupStateDeleted = "deleted" ) +// PlacementGroupState_Values returns all elements of the PlacementGroupState enum +func PlacementGroupState_Values() []string { + return []string{ + PlacementGroupStatePending, + PlacementGroupStateAvailable, + PlacementGroupStateDeleting, + PlacementGroupStateDeleted, + } +} + const ( // PlacementGroupStrategyCluster is a PlacementGroupStrategy enum value PlacementGroupStrategyCluster = "cluster" @@ -111636,6 +118622,15 @@ const ( PlacementGroupStrategySpread = "spread" ) +// PlacementGroupStrategy_Values returns all elements of the PlacementGroupStrategy enum +func PlacementGroupStrategy_Values() []string { + return []string{ + PlacementGroupStrategyCluster, + PlacementGroupStrategyPartition, + PlacementGroupStrategySpread, + } +} + const ( // PlacementStrategyCluster is a PlacementStrategy enum value PlacementStrategyCluster = "cluster" @@ -111647,11 +118642,83 @@ const ( PlacementStrategyPartition = "partition" ) +// PlacementStrategy_Values returns all elements of the PlacementStrategy enum +func PlacementStrategy_Values() []string { + return []string{ + PlacementStrategyCluster, + PlacementStrategySpread, + PlacementStrategyPartition, + } +} + const ( // PlatformValuesWindows is a PlatformValues enum value PlatformValuesWindows = "Windows" ) +// PlatformValues_Values returns all elements of the PlatformValues enum +func PlatformValues_Values() []string { + return []string{ + PlatformValuesWindows, + } +} + +const ( + // PrefixListStateCreateInProgress is a PrefixListState enum value + PrefixListStateCreateInProgress = "create-in-progress" + + // PrefixListStateCreateComplete is a PrefixListState enum value + PrefixListStateCreateComplete = "create-complete" + + // PrefixListStateCreateFailed is a PrefixListState enum value + PrefixListStateCreateFailed = "create-failed" + + // PrefixListStateModifyInProgress is a PrefixListState enum value + PrefixListStateModifyInProgress = "modify-in-progress" + + // PrefixListStateModifyComplete is a PrefixListState enum value + PrefixListStateModifyComplete = "modify-complete" + + // PrefixListStateModifyFailed is a PrefixListState enum value + PrefixListStateModifyFailed = "modify-failed" + + // PrefixListStateRestoreInProgress is a PrefixListState enum value + PrefixListStateRestoreInProgress = "restore-in-progress" + + // PrefixListStateRestoreComplete is a PrefixListState enum value + PrefixListStateRestoreComplete = "restore-complete" + + // PrefixListStateRestoreFailed is a PrefixListState enum value + PrefixListStateRestoreFailed = "restore-failed" + + // PrefixListStateDeleteInProgress is a PrefixListState enum value + PrefixListStateDeleteInProgress = "delete-in-progress" + + // PrefixListStateDeleteComplete is a PrefixListState enum value + PrefixListStateDeleteComplete = "delete-complete" + + // PrefixListStateDeleteFailed is a PrefixListState enum value + PrefixListStateDeleteFailed = "delete-failed" +) + +// PrefixListState_Values returns all elements of the PrefixListState enum +func PrefixListState_Values() []string { + return []string{ + PrefixListStateCreateInProgress, + PrefixListStateCreateComplete, + PrefixListStateCreateFailed, + PrefixListStateModifyInProgress, + PrefixListStateModifyComplete, + PrefixListStateModifyFailed, + PrefixListStateRestoreInProgress, + PrefixListStateRestoreComplete, + PrefixListStateRestoreFailed, + PrefixListStateDeleteInProgress, + PrefixListStateDeleteComplete, + PrefixListStateDeleteFailed, + } +} + const ( // PrincipalTypeAll is a PrincipalType enum value PrincipalTypeAll = "All" @@ -111672,6 +118739,18 @@ const ( PrincipalTypeRole = "Role" ) +// PrincipalType_Values returns all elements of the PrincipalType enum +func PrincipalType_Values() []string { + return []string{ + PrincipalTypeAll, + PrincipalTypeService, + PrincipalTypeOrganizationUnit, + PrincipalTypeAccount, + PrincipalTypeUser, + PrincipalTypeRole, + } +} + const ( // ProductCodeValuesDevpay is a ProductCodeValues enum value ProductCodeValuesDevpay = "devpay" @@ -111680,6 +118759,14 @@ const ( ProductCodeValuesMarketplace = "marketplace" ) +// ProductCodeValues_Values returns all elements of the ProductCodeValues enum +func ProductCodeValues_Values() []string { + return []string{ + ProductCodeValuesDevpay, + ProductCodeValuesMarketplace, + } +} + const ( // RIProductDescriptionLinuxUnix is a RIProductDescription enum value RIProductDescriptionLinuxUnix = "Linux/UNIX" @@ -111694,11 +118781,28 @@ const ( RIProductDescriptionWindowsAmazonVpc = "Windows (Amazon VPC)" ) +// RIProductDescription_Values returns all elements of the RIProductDescription enum +func RIProductDescription_Values() []string { + return []string{ + RIProductDescriptionLinuxUnix, + RIProductDescriptionLinuxUnixamazonVpc, + RIProductDescriptionWindows, + RIProductDescriptionWindowsAmazonVpc, + } +} + const ( // RecurringChargeFrequencyHourly is a RecurringChargeFrequency enum value RecurringChargeFrequencyHourly = "Hourly" ) +// RecurringChargeFrequency_Values returns all elements of the RecurringChargeFrequency enum +func RecurringChargeFrequency_Values() []string { + return []string{ + RecurringChargeFrequencyHourly, + } +} + const ( // ReportInstanceReasonCodesInstanceStuckInState is a ReportInstanceReasonCodes enum value ReportInstanceReasonCodesInstanceStuckInState = "instance-stuck-in-state" @@ -111728,6 +118832,21 @@ const ( ReportInstanceReasonCodesOther = "other" ) +// ReportInstanceReasonCodes_Values returns all elements of the ReportInstanceReasonCodes enum +func ReportInstanceReasonCodes_Values() []string { + return []string{ + ReportInstanceReasonCodesInstanceStuckInState, + ReportInstanceReasonCodesUnresponsive, + ReportInstanceReasonCodesNotAcceptingCredentials, + ReportInstanceReasonCodesPasswordNotAvailable, + ReportInstanceReasonCodesPerformanceNetwork, + ReportInstanceReasonCodesPerformanceInstanceStore, + ReportInstanceReasonCodesPerformanceEbsVolume, + ReportInstanceReasonCodesPerformanceOther, + ReportInstanceReasonCodesOther, + } +} + const ( // ReportStatusTypeOk is a ReportStatusType enum value ReportStatusTypeOk = "ok" @@ -111736,6 +118855,14 @@ const ( ReportStatusTypeImpaired = "impaired" ) +// ReportStatusType_Values returns all elements of the ReportStatusType enum +func ReportStatusType_Values() []string { + return []string{ + ReportStatusTypeOk, + ReportStatusTypeImpaired, + } +} + const ( // ReservationStatePaymentPending is a ReservationState enum value ReservationStatePaymentPending = "payment-pending" @@ -111750,6 +118877,16 @@ const ( ReservationStateRetired = "retired" ) +// ReservationState_Values returns all elements of the ReservationState enum +func ReservationState_Values() []string { + return []string{ + ReservationStatePaymentPending, + ReservationStatePaymentFailed, + ReservationStateActive, + ReservationStateRetired, + } +} + const ( // ReservedInstanceStatePaymentPending is a ReservedInstanceState enum value ReservedInstanceStatePaymentPending = "payment-pending" @@ -111770,16 +118907,42 @@ const ( ReservedInstanceStateQueuedDeleted = "queued-deleted" ) +// ReservedInstanceState_Values returns all elements of the ReservedInstanceState enum +func ReservedInstanceState_Values() []string { + return []string{ + ReservedInstanceStatePaymentPending, + ReservedInstanceStateActive, + ReservedInstanceStatePaymentFailed, + ReservedInstanceStateRetired, + ReservedInstanceStateQueued, + ReservedInstanceStateQueuedDeleted, + } +} + const ( // ResetFpgaImageAttributeNameLoadPermission is a ResetFpgaImageAttributeName enum value ResetFpgaImageAttributeNameLoadPermission = "loadPermission" ) +// ResetFpgaImageAttributeName_Values returns all elements of the ResetFpgaImageAttributeName enum +func ResetFpgaImageAttributeName_Values() []string { + return []string{ + ResetFpgaImageAttributeNameLoadPermission, + } +} + const ( // ResetImageAttributeNameLaunchPermission is a ResetImageAttributeName enum value ResetImageAttributeNameLaunchPermission = "launchPermission" ) +// ResetImageAttributeName_Values returns all elements of the ResetImageAttributeName enum +func ResetImageAttributeName_Values() []string { + return []string{ + ResetImageAttributeNameLaunchPermission, + } +} + const ( // ResourceTypeClientVpnEndpoint is a ResourceType enum value ResourceTypeClientVpnEndpoint = "client-vpn-endpoint" @@ -111793,9 +118956,21 @@ const ( // ResourceTypeDhcpOptions is a ResourceType enum value ResourceTypeDhcpOptions = "dhcp-options" + // ResourceTypeEgressOnlyInternetGateway is a ResourceType enum value + ResourceTypeEgressOnlyInternetGateway = "egress-only-internet-gateway" + // ResourceTypeElasticIp is a ResourceType enum value ResourceTypeElasticIp = "elastic-ip" + // ResourceTypeElasticGpu is a ResourceType enum value + ResourceTypeElasticGpu = "elastic-gpu" + + // ResourceTypeExportImageTask is a ResourceType enum value + ResourceTypeExportImageTask = "export-image-task" + + // ResourceTypeExportInstanceTask is a ResourceType enum value + ResourceTypeExportInstanceTask = "export-instance-task" + // ResourceTypeFleet is a ResourceType enum value ResourceTypeFleet = "fleet" @@ -111808,6 +118983,12 @@ const ( // ResourceTypeImage is a ResourceType enum value ResourceTypeImage = "image" + // ResourceTypeImportImageTask is a ResourceType enum value + ResourceTypeImportImageTask = "import-image-task" + + // ResourceTypeImportSnapshotTask is a ResourceType enum value + ResourceTypeImportSnapshotTask = "import-snapshot-task" + // ResourceTypeInstance is a ResourceType enum value ResourceTypeInstance = "instance" @@ -111820,6 +119001,9 @@ const ( // ResourceTypeLaunchTemplate is a ResourceType enum value ResourceTypeLaunchTemplate = "launch-template" + // ResourceTypeLocalGatewayRouteTableVpcAssociation is a ResourceType enum value + ResourceTypeLocalGatewayRouteTableVpcAssociation = "local-gateway-route-table-vpc-association" + // ResourceTypeNatgateway is a ResourceType enum value ResourceTypeNatgateway = "natgateway" @@ -111893,6 +119077,56 @@ const ( ResourceTypeVpcFlowLog = "vpc-flow-log" ) +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeClientVpnEndpoint, + ResourceTypeCustomerGateway, + ResourceTypeDedicatedHost, + ResourceTypeDhcpOptions, + ResourceTypeEgressOnlyInternetGateway, + ResourceTypeElasticIp, + ResourceTypeElasticGpu, + ResourceTypeExportImageTask, + ResourceTypeExportInstanceTask, + ResourceTypeFleet, + ResourceTypeFpgaImage, + ResourceTypeHostReservation, + ResourceTypeImage, + ResourceTypeImportImageTask, + ResourceTypeImportSnapshotTask, + ResourceTypeInstance, + ResourceTypeInternetGateway, + ResourceTypeKeyPair, + ResourceTypeLaunchTemplate, + ResourceTypeLocalGatewayRouteTableVpcAssociation, + ResourceTypeNatgateway, + ResourceTypeNetworkAcl, + ResourceTypeNetworkInterface, + ResourceTypePlacementGroup, + ResourceTypeReservedInstances, + ResourceTypeRouteTable, + ResourceTypeSecurityGroup, + ResourceTypeSnapshot, + ResourceTypeSpotFleetRequest, + ResourceTypeSpotInstancesRequest, + ResourceTypeSubnet, + ResourceTypeTrafficMirrorFilter, + ResourceTypeTrafficMirrorSession, + ResourceTypeTrafficMirrorTarget, + ResourceTypeTransitGateway, + ResourceTypeTransitGatewayAttachment, + ResourceTypeTransitGatewayMulticastDomain, + ResourceTypeTransitGatewayRouteTable, + ResourceTypeVolume, + ResourceTypeVpc, + ResourceTypeVpcPeeringConnection, + ResourceTypeVpnConnection, + ResourceTypeVpnGateway, + ResourceTypeVpcFlowLog, + } +} + const ( // RootDeviceTypeEbs is a RootDeviceType enum value RootDeviceTypeEbs = "ebs" @@ -111901,6 +119135,14 @@ const ( RootDeviceTypeInstanceStore = "instance-store" ) +// RootDeviceType_Values returns all elements of the RootDeviceType enum +func RootDeviceType_Values() []string { + return []string{ + RootDeviceTypeEbs, + RootDeviceTypeInstanceStore, + } +} + const ( // RouteOriginCreateRouteTable is a RouteOrigin enum value RouteOriginCreateRouteTable = "CreateRouteTable" @@ -111912,6 +119154,15 @@ const ( RouteOriginEnableVgwRoutePropagation = "EnableVgwRoutePropagation" ) +// RouteOrigin_Values returns all elements of the RouteOrigin enum +func RouteOrigin_Values() []string { + return []string{ + RouteOriginCreateRouteTable, + RouteOriginCreateRoute, + RouteOriginEnableVgwRoutePropagation, + } +} + const ( // RouteStateActive is a RouteState enum value RouteStateActive = "active" @@ -111920,6 +119171,14 @@ const ( RouteStateBlackhole = "blackhole" ) +// RouteState_Values returns all elements of the RouteState enum +func RouteState_Values() []string { + return []string{ + RouteStateActive, + RouteStateBlackhole, + } +} + const ( // RouteTableAssociationStateCodeAssociating is a RouteTableAssociationStateCode enum value RouteTableAssociationStateCodeAssociating = "associating" @@ -111937,6 +119196,17 @@ const ( RouteTableAssociationStateCodeFailed = "failed" ) +// RouteTableAssociationStateCode_Values returns all elements of the RouteTableAssociationStateCode enum +func RouteTableAssociationStateCode_Values() []string { + return []string{ + RouteTableAssociationStateCodeAssociating, + RouteTableAssociationStateCodeAssociated, + RouteTableAssociationStateCodeDisassociating, + RouteTableAssociationStateCodeDisassociated, + RouteTableAssociationStateCodeFailed, + } +} + const ( // RuleActionAllow is a RuleAction enum value RuleActionAllow = "allow" @@ -111945,6 +119215,14 @@ const ( RuleActionDeny = "deny" ) +// RuleAction_Values returns all elements of the RuleAction enum +func RuleAction_Values() []string { + return []string{ + RuleActionAllow, + RuleActionDeny, + } +} + const ( // ScopeAvailabilityZone is a Scope enum value ScopeAvailabilityZone = "Availability Zone" @@ -111953,6 +119231,14 @@ const ( ScopeRegion = "Region" ) +// Scope_Values returns all elements of the Scope enum +func Scope_Values() []string { + return []string{ + ScopeAvailabilityZone, + ScopeRegion, + } +} + const ( // ServiceStatePending is a ServiceState enum value ServiceStatePending = "Pending" @@ -111970,6 +119256,17 @@ const ( ServiceStateFailed = "Failed" ) +// ServiceState_Values returns all elements of the ServiceState enum +func ServiceState_Values() []string { + return []string{ + ServiceStatePending, + ServiceStateAvailable, + ServiceStateDeleting, + ServiceStateDeleted, + ServiceStateFailed, + } +} + const ( // ServiceTypeInterface is a ServiceType enum value ServiceTypeInterface = "Interface" @@ -111978,6 +119275,14 @@ const ( ServiceTypeGateway = "Gateway" ) +// ServiceType_Values returns all elements of the ServiceType enum +func ServiceType_Values() []string { + return []string{ + ServiceTypeInterface, + ServiceTypeGateway, + } +} + const ( // ShutdownBehaviorStop is a ShutdownBehavior enum value ShutdownBehaviorStop = "stop" @@ -111986,6 +119291,14 @@ const ( ShutdownBehaviorTerminate = "terminate" ) +// ShutdownBehavior_Values returns all elements of the ShutdownBehavior enum +func ShutdownBehavior_Values() []string { + return []string{ + ShutdownBehaviorStop, + ShutdownBehaviorTerminate, + } +} + const ( // SnapshotAttributeNameProductCodes is a SnapshotAttributeName enum value SnapshotAttributeNameProductCodes = "productCodes" @@ -111994,6 +119307,14 @@ const ( SnapshotAttributeNameCreateVolumePermission = "createVolumePermission" ) +// SnapshotAttributeName_Values returns all elements of the SnapshotAttributeName enum +func SnapshotAttributeName_Values() []string { + return []string{ + SnapshotAttributeNameProductCodes, + SnapshotAttributeNameCreateVolumePermission, + } +} + const ( // SnapshotStatePending is a SnapshotState enum value SnapshotStatePending = "pending" @@ -112005,6 +119326,15 @@ const ( SnapshotStateError = "error" ) +// SnapshotState_Values returns all elements of the SnapshotState enum +func SnapshotState_Values() []string { + return []string{ + SnapshotStatePending, + SnapshotStateCompleted, + SnapshotStateError, + } +} + const ( // SpotAllocationStrategyLowestPrice is a SpotAllocationStrategy enum value SpotAllocationStrategyLowestPrice = "lowest-price" @@ -112016,6 +119346,15 @@ const ( SpotAllocationStrategyCapacityOptimized = "capacity-optimized" ) +// SpotAllocationStrategy_Values returns all elements of the SpotAllocationStrategy enum +func SpotAllocationStrategy_Values() []string { + return []string{ + SpotAllocationStrategyLowestPrice, + SpotAllocationStrategyDiversified, + SpotAllocationStrategyCapacityOptimized, + } +} + const ( // SpotInstanceInterruptionBehaviorHibernate is a SpotInstanceInterruptionBehavior enum value SpotInstanceInterruptionBehaviorHibernate = "hibernate" @@ -112027,6 +119366,15 @@ const ( SpotInstanceInterruptionBehaviorTerminate = "terminate" ) +// SpotInstanceInterruptionBehavior_Values returns all elements of the SpotInstanceInterruptionBehavior enum +func SpotInstanceInterruptionBehavior_Values() []string { + return []string{ + SpotInstanceInterruptionBehaviorHibernate, + SpotInstanceInterruptionBehaviorStop, + SpotInstanceInterruptionBehaviorTerminate, + } +} + const ( // SpotInstanceStateOpen is a SpotInstanceState enum value SpotInstanceStateOpen = "open" @@ -112044,6 +119392,17 @@ const ( SpotInstanceStateFailed = "failed" ) +// SpotInstanceState_Values returns all elements of the SpotInstanceState enum +func SpotInstanceState_Values() []string { + return []string{ + SpotInstanceStateOpen, + SpotInstanceStateActive, + SpotInstanceStateClosed, + SpotInstanceStateCancelled, + SpotInstanceStateFailed, + } +} + const ( // SpotInstanceTypeOneTime is a SpotInstanceType enum value SpotInstanceTypeOneTime = "one-time" @@ -112052,6 +119411,14 @@ const ( SpotInstanceTypePersistent = "persistent" ) +// SpotInstanceType_Values returns all elements of the SpotInstanceType enum +func SpotInstanceType_Values() []string { + return []string{ + SpotInstanceTypeOneTime, + SpotInstanceTypePersistent, + } +} + const ( // StatePendingAcceptance is a State enum value StatePendingAcceptance = "PendingAcceptance" @@ -112078,6 +119445,20 @@ const ( StateExpired = "Expired" ) +// State_Values returns all elements of the State enum +func State_Values() []string { + return []string{ + StatePendingAcceptance, + StatePending, + StateAvailable, + StateDeleting, + StateDeleted, + StateRejected, + StateFailed, + StateExpired, + } +} + const ( // StatusMoveInProgress is a Status enum value StatusMoveInProgress = "MoveInProgress" @@ -112089,11 +119470,27 @@ const ( StatusInClassic = "InClassic" ) +// Status_Values returns all elements of the Status enum +func Status_Values() []string { + return []string{ + StatusMoveInProgress, + StatusInVpc, + StatusInClassic, + } +} + const ( // StatusNameReachability is a StatusName enum value StatusNameReachability = "reachability" ) +// StatusName_Values returns all elements of the StatusName enum +func StatusName_Values() []string { + return []string{ + StatusNameReachability, + } +} + const ( // StatusTypePassed is a StatusType enum value StatusTypePassed = "passed" @@ -112108,6 +119505,16 @@ const ( StatusTypeInitializing = "initializing" ) +// StatusType_Values returns all elements of the StatusType enum +func StatusType_Values() []string { + return []string{ + StatusTypePassed, + StatusTypeFailed, + StatusTypeInsufficientData, + StatusTypeInitializing, + } +} + const ( // SubnetCidrBlockStateCodeAssociating is a SubnetCidrBlockStateCode enum value SubnetCidrBlockStateCodeAssociating = "associating" @@ -112128,6 +119535,18 @@ const ( SubnetCidrBlockStateCodeFailed = "failed" ) +// SubnetCidrBlockStateCode_Values returns all elements of the SubnetCidrBlockStateCode enum +func SubnetCidrBlockStateCode_Values() []string { + return []string{ + SubnetCidrBlockStateCodeAssociating, + SubnetCidrBlockStateCodeAssociated, + SubnetCidrBlockStateCodeDisassociating, + SubnetCidrBlockStateCodeDisassociated, + SubnetCidrBlockStateCodeFailing, + SubnetCidrBlockStateCodeFailed, + } +} + const ( // SubnetStatePending is a SubnetState enum value SubnetStatePending = "pending" @@ -112136,6 +119555,14 @@ const ( SubnetStateAvailable = "available" ) +// SubnetState_Values returns all elements of the SubnetState enum +func SubnetState_Values() []string { + return []string{ + SubnetStatePending, + SubnetStateAvailable, + } +} + const ( // SummaryStatusOk is a SummaryStatus enum value SummaryStatusOk = "ok" @@ -112153,6 +119580,17 @@ const ( SummaryStatusInitializing = "initializing" ) +// SummaryStatus_Values returns all elements of the SummaryStatus enum +func SummaryStatus_Values() []string { + return []string{ + SummaryStatusOk, + SummaryStatusImpaired, + SummaryStatusInsufficientData, + SummaryStatusNotApplicable, + SummaryStatusInitializing, + } +} + const ( // TelemetryStatusUp is a TelemetryStatus enum value TelemetryStatusUp = "UP" @@ -112161,6 +119599,14 @@ const ( TelemetryStatusDown = "DOWN" ) +// TelemetryStatus_Values returns all elements of the TelemetryStatus enum +func TelemetryStatus_Values() []string { + return []string{ + TelemetryStatusUp, + TelemetryStatusDown, + } +} + const ( // TenancyDefault is a Tenancy enum value TenancyDefault = "default" @@ -112172,6 +119618,15 @@ const ( TenancyHost = "host" ) +// Tenancy_Values returns all elements of the Tenancy enum +func Tenancy_Values() []string { + return []string{ + TenancyDefault, + TenancyDedicated, + TenancyHost, + } +} + const ( // TrafficDirectionIngress is a TrafficDirection enum value TrafficDirectionIngress = "ingress" @@ -112180,6 +119635,14 @@ const ( TrafficDirectionEgress = "egress" ) +// TrafficDirection_Values returns all elements of the TrafficDirection enum +func TrafficDirection_Values() []string { + return []string{ + TrafficDirectionIngress, + TrafficDirectionEgress, + } +} + const ( // TrafficMirrorFilterRuleFieldDestinationPortRange is a TrafficMirrorFilterRuleField enum value TrafficMirrorFilterRuleFieldDestinationPortRange = "destination-port-range" @@ -112194,11 +119657,28 @@ const ( TrafficMirrorFilterRuleFieldDescription = "description" ) +// TrafficMirrorFilterRuleField_Values returns all elements of the TrafficMirrorFilterRuleField enum +func TrafficMirrorFilterRuleField_Values() []string { + return []string{ + TrafficMirrorFilterRuleFieldDestinationPortRange, + TrafficMirrorFilterRuleFieldSourcePortRange, + TrafficMirrorFilterRuleFieldProtocol, + TrafficMirrorFilterRuleFieldDescription, + } +} + const ( // TrafficMirrorNetworkServiceAmazonDns is a TrafficMirrorNetworkService enum value TrafficMirrorNetworkServiceAmazonDns = "amazon-dns" ) +// TrafficMirrorNetworkService_Values returns all elements of the TrafficMirrorNetworkService enum +func TrafficMirrorNetworkService_Values() []string { + return []string{ + TrafficMirrorNetworkServiceAmazonDns, + } +} + const ( // TrafficMirrorRuleActionAccept is a TrafficMirrorRuleAction enum value TrafficMirrorRuleActionAccept = "accept" @@ -112207,6 +119687,14 @@ const ( TrafficMirrorRuleActionReject = "reject" ) +// TrafficMirrorRuleAction_Values returns all elements of the TrafficMirrorRuleAction enum +func TrafficMirrorRuleAction_Values() []string { + return []string{ + TrafficMirrorRuleActionAccept, + TrafficMirrorRuleActionReject, + } +} + const ( // TrafficMirrorSessionFieldPacketLength is a TrafficMirrorSessionField enum value TrafficMirrorSessionFieldPacketLength = "packet-length" @@ -112218,6 +119706,15 @@ const ( TrafficMirrorSessionFieldVirtualNetworkId = "virtual-network-id" ) +// TrafficMirrorSessionField_Values returns all elements of the TrafficMirrorSessionField enum +func TrafficMirrorSessionField_Values() []string { + return []string{ + TrafficMirrorSessionFieldPacketLength, + TrafficMirrorSessionFieldDescription, + TrafficMirrorSessionFieldVirtualNetworkId, + } +} + const ( // TrafficMirrorTargetTypeNetworkInterface is a TrafficMirrorTargetType enum value TrafficMirrorTargetTypeNetworkInterface = "network-interface" @@ -112226,6 +119723,14 @@ const ( TrafficMirrorTargetTypeNetworkLoadBalancer = "network-load-balancer" ) +// TrafficMirrorTargetType_Values returns all elements of the TrafficMirrorTargetType enum +func TrafficMirrorTargetType_Values() []string { + return []string{ + TrafficMirrorTargetTypeNetworkInterface, + TrafficMirrorTargetTypeNetworkLoadBalancer, + } +} + const ( // TrafficTypeAccept is a TrafficType enum value TrafficTypeAccept = "ACCEPT" @@ -112237,6 +119742,15 @@ const ( TrafficTypeAll = "ALL" ) +// TrafficType_Values returns all elements of the TrafficType enum +func TrafficType_Values() []string { + return []string{ + TrafficTypeAccept, + TrafficTypeReject, + TrafficTypeAll, + } +} + const ( // TransitGatewayAssociationStateAssociating is a TransitGatewayAssociationState enum value TransitGatewayAssociationStateAssociating = "associating" @@ -112251,6 +119765,16 @@ const ( TransitGatewayAssociationStateDisassociated = "disassociated" ) +// TransitGatewayAssociationState_Values returns all elements of the TransitGatewayAssociationState enum +func TransitGatewayAssociationState_Values() []string { + return []string{ + TransitGatewayAssociationStateAssociating, + TransitGatewayAssociationStateAssociated, + TransitGatewayAssociationStateDisassociating, + TransitGatewayAssociationStateDisassociated, + } +} + const ( // TransitGatewayAttachmentResourceTypeVpc is a TransitGatewayAttachmentResourceType enum value TransitGatewayAttachmentResourceTypeVpc = "vpc" @@ -112261,14 +119785,31 @@ const ( // TransitGatewayAttachmentResourceTypeDirectConnectGateway is a TransitGatewayAttachmentResourceType enum value TransitGatewayAttachmentResourceTypeDirectConnectGateway = "direct-connect-gateway" + // TransitGatewayAttachmentResourceTypePeering is a TransitGatewayAttachmentResourceType enum value + TransitGatewayAttachmentResourceTypePeering = "peering" + // TransitGatewayAttachmentResourceTypeTgwPeering is a TransitGatewayAttachmentResourceType enum value TransitGatewayAttachmentResourceTypeTgwPeering = "tgw-peering" ) +// TransitGatewayAttachmentResourceType_Values returns all elements of the TransitGatewayAttachmentResourceType enum +func TransitGatewayAttachmentResourceType_Values() []string { + return []string{ + TransitGatewayAttachmentResourceTypeVpc, + TransitGatewayAttachmentResourceTypeVpn, + TransitGatewayAttachmentResourceTypeDirectConnectGateway, + TransitGatewayAttachmentResourceTypePeering, + TransitGatewayAttachmentResourceTypeTgwPeering, + } +} + const ( // TransitGatewayAttachmentStateInitiating is a TransitGatewayAttachmentState enum value TransitGatewayAttachmentStateInitiating = "initiating" + // TransitGatewayAttachmentStateInitiatingRequest is a TransitGatewayAttachmentState enum value + TransitGatewayAttachmentStateInitiatingRequest = "initiatingRequest" + // TransitGatewayAttachmentStatePendingAcceptance is a TransitGatewayAttachmentState enum value TransitGatewayAttachmentStatePendingAcceptance = "pendingAcceptance" @@ -112303,6 +119844,25 @@ const ( TransitGatewayAttachmentStateFailing = "failing" ) +// TransitGatewayAttachmentState_Values returns all elements of the TransitGatewayAttachmentState enum +func TransitGatewayAttachmentState_Values() []string { + return []string{ + TransitGatewayAttachmentStateInitiating, + TransitGatewayAttachmentStateInitiatingRequest, + TransitGatewayAttachmentStatePendingAcceptance, + TransitGatewayAttachmentStateRollingBack, + TransitGatewayAttachmentStatePending, + TransitGatewayAttachmentStateAvailable, + TransitGatewayAttachmentStateModifying, + TransitGatewayAttachmentStateDeleting, + TransitGatewayAttachmentStateDeleted, + TransitGatewayAttachmentStateFailed, + TransitGatewayAttachmentStateRejected, + TransitGatewayAttachmentStateRejecting, + TransitGatewayAttachmentStateFailing, + } +} + const ( // TransitGatewayMulitcastDomainAssociationStateAssociating is a TransitGatewayMulitcastDomainAssociationState enum value TransitGatewayMulitcastDomainAssociationStateAssociating = "associating" @@ -112317,6 +119877,16 @@ const ( TransitGatewayMulitcastDomainAssociationStateDisassociated = "disassociated" ) +// TransitGatewayMulitcastDomainAssociationState_Values returns all elements of the TransitGatewayMulitcastDomainAssociationState enum +func TransitGatewayMulitcastDomainAssociationState_Values() []string { + return []string{ + TransitGatewayMulitcastDomainAssociationStateAssociating, + TransitGatewayMulitcastDomainAssociationStateAssociated, + TransitGatewayMulitcastDomainAssociationStateDisassociating, + TransitGatewayMulitcastDomainAssociationStateDisassociated, + } +} + const ( // TransitGatewayMulticastDomainStatePending is a TransitGatewayMulticastDomainState enum value TransitGatewayMulticastDomainStatePending = "pending" @@ -112331,6 +119901,40 @@ const ( TransitGatewayMulticastDomainStateDeleted = "deleted" ) +// TransitGatewayMulticastDomainState_Values returns all elements of the TransitGatewayMulticastDomainState enum +func TransitGatewayMulticastDomainState_Values() []string { + return []string{ + TransitGatewayMulticastDomainStatePending, + TransitGatewayMulticastDomainStateAvailable, + TransitGatewayMulticastDomainStateDeleting, + TransitGatewayMulticastDomainStateDeleted, + } +} + +const ( + // TransitGatewayPrefixListReferenceStatePending is a TransitGatewayPrefixListReferenceState enum value + TransitGatewayPrefixListReferenceStatePending = "pending" + + // TransitGatewayPrefixListReferenceStateAvailable is a TransitGatewayPrefixListReferenceState enum value + TransitGatewayPrefixListReferenceStateAvailable = "available" + + // TransitGatewayPrefixListReferenceStateModifying is a TransitGatewayPrefixListReferenceState enum value + TransitGatewayPrefixListReferenceStateModifying = "modifying" + + // TransitGatewayPrefixListReferenceStateDeleting is a TransitGatewayPrefixListReferenceState enum value + TransitGatewayPrefixListReferenceStateDeleting = "deleting" +) + +// TransitGatewayPrefixListReferenceState_Values returns all elements of the TransitGatewayPrefixListReferenceState enum +func TransitGatewayPrefixListReferenceState_Values() []string { + return []string{ + TransitGatewayPrefixListReferenceStatePending, + TransitGatewayPrefixListReferenceStateAvailable, + TransitGatewayPrefixListReferenceStateModifying, + TransitGatewayPrefixListReferenceStateDeleting, + } +} + const ( // TransitGatewayPropagationStateEnabling is a TransitGatewayPropagationState enum value TransitGatewayPropagationStateEnabling = "enabling" @@ -112345,6 +119949,16 @@ const ( TransitGatewayPropagationStateDisabled = "disabled" ) +// TransitGatewayPropagationState_Values returns all elements of the TransitGatewayPropagationState enum +func TransitGatewayPropagationState_Values() []string { + return []string{ + TransitGatewayPropagationStateEnabling, + TransitGatewayPropagationStateEnabled, + TransitGatewayPropagationStateDisabling, + TransitGatewayPropagationStateDisabled, + } +} + const ( // TransitGatewayRouteStatePending is a TransitGatewayRouteState enum value TransitGatewayRouteStatePending = "pending" @@ -112362,6 +119976,17 @@ const ( TransitGatewayRouteStateDeleted = "deleted" ) +// TransitGatewayRouteState_Values returns all elements of the TransitGatewayRouteState enum +func TransitGatewayRouteState_Values() []string { + return []string{ + TransitGatewayRouteStatePending, + TransitGatewayRouteStateActive, + TransitGatewayRouteStateBlackhole, + TransitGatewayRouteStateDeleting, + TransitGatewayRouteStateDeleted, + } +} + const ( // TransitGatewayRouteTableStatePending is a TransitGatewayRouteTableState enum value TransitGatewayRouteTableStatePending = "pending" @@ -112376,6 +120001,16 @@ const ( TransitGatewayRouteTableStateDeleted = "deleted" ) +// TransitGatewayRouteTableState_Values returns all elements of the TransitGatewayRouteTableState enum +func TransitGatewayRouteTableState_Values() []string { + return []string{ + TransitGatewayRouteTableStatePending, + TransitGatewayRouteTableStateAvailable, + TransitGatewayRouteTableStateDeleting, + TransitGatewayRouteTableStateDeleted, + } +} + const ( // TransitGatewayRouteTypeStatic is a TransitGatewayRouteType enum value TransitGatewayRouteTypeStatic = "static" @@ -112384,6 +120019,14 @@ const ( TransitGatewayRouteTypePropagated = "propagated" ) +// TransitGatewayRouteType_Values returns all elements of the TransitGatewayRouteType enum +func TransitGatewayRouteType_Values() []string { + return []string{ + TransitGatewayRouteTypeStatic, + TransitGatewayRouteTypePropagated, + } +} + const ( // TransitGatewayStatePending is a TransitGatewayState enum value TransitGatewayStatePending = "pending" @@ -112401,6 +120044,17 @@ const ( TransitGatewayStateDeleted = "deleted" ) +// TransitGatewayState_Values returns all elements of the TransitGatewayState enum +func TransitGatewayState_Values() []string { + return []string{ + TransitGatewayStatePending, + TransitGatewayStateAvailable, + TransitGatewayStateModifying, + TransitGatewayStateDeleting, + TransitGatewayStateDeleted, + } +} + const ( // TransportProtocolTcp is a TransportProtocol enum value TransportProtocolTcp = "tcp" @@ -112409,6 +120063,30 @@ const ( TransportProtocolUdp = "udp" ) +// TransportProtocol_Values returns all elements of the TransportProtocol enum +func TransportProtocol_Values() []string { + return []string{ + TransportProtocolTcp, + TransportProtocolUdp, + } +} + +const ( + // TunnelInsideIpVersionIpv4 is a TunnelInsideIpVersion enum value + TunnelInsideIpVersionIpv4 = "ipv4" + + // TunnelInsideIpVersionIpv6 is a TunnelInsideIpVersion enum value + TunnelInsideIpVersionIpv6 = "ipv6" +) + +// TunnelInsideIpVersion_Values returns all elements of the TunnelInsideIpVersion enum +func TunnelInsideIpVersion_Values() []string { + return []string{ + TunnelInsideIpVersionIpv4, + TunnelInsideIpVersionIpv6, + } +} + const ( // UnlimitedSupportedInstanceFamilyT2 is a UnlimitedSupportedInstanceFamily enum value UnlimitedSupportedInstanceFamilyT2 = "t2" @@ -112418,8 +120096,21 @@ const ( // UnlimitedSupportedInstanceFamilyT3a is a UnlimitedSupportedInstanceFamily enum value UnlimitedSupportedInstanceFamilyT3a = "t3a" + + // UnlimitedSupportedInstanceFamilyT4g is a UnlimitedSupportedInstanceFamily enum value + UnlimitedSupportedInstanceFamilyT4g = "t4g" ) +// UnlimitedSupportedInstanceFamily_Values returns all elements of the UnlimitedSupportedInstanceFamily enum +func UnlimitedSupportedInstanceFamily_Values() []string { + return []string{ + UnlimitedSupportedInstanceFamilyT2, + UnlimitedSupportedInstanceFamilyT3, + UnlimitedSupportedInstanceFamilyT3a, + UnlimitedSupportedInstanceFamilyT4g, + } +} + const ( // UnsuccessfulInstanceCreditSpecificationErrorCodeInvalidInstanceIdMalformed is a UnsuccessfulInstanceCreditSpecificationErrorCode enum value UnsuccessfulInstanceCreditSpecificationErrorCodeInvalidInstanceIdMalformed = "InvalidInstanceID.Malformed" @@ -112434,6 +120125,16 @@ const ( UnsuccessfulInstanceCreditSpecificationErrorCodeInstanceCreditSpecificationNotSupported = "InstanceCreditSpecification.NotSupported" ) +// UnsuccessfulInstanceCreditSpecificationErrorCode_Values returns all elements of the UnsuccessfulInstanceCreditSpecificationErrorCode enum +func UnsuccessfulInstanceCreditSpecificationErrorCode_Values() []string { + return []string{ + UnsuccessfulInstanceCreditSpecificationErrorCodeInvalidInstanceIdMalformed, + UnsuccessfulInstanceCreditSpecificationErrorCodeInvalidInstanceIdNotFound, + UnsuccessfulInstanceCreditSpecificationErrorCodeIncorrectInstanceState, + UnsuccessfulInstanceCreditSpecificationErrorCodeInstanceCreditSpecificationNotSupported, + } +} + const ( // UsageClassTypeSpot is a UsageClassType enum value UsageClassTypeSpot = "spot" @@ -112442,6 +120143,14 @@ const ( UsageClassTypeOnDemand = "on-demand" ) +// UsageClassType_Values returns all elements of the UsageClassType enum +func UsageClassType_Values() []string { + return []string{ + UsageClassTypeSpot, + UsageClassTypeOnDemand, + } +} + const ( // VirtualizationTypeHvm is a VirtualizationType enum value VirtualizationTypeHvm = "hvm" @@ -112450,6 +120159,14 @@ const ( VirtualizationTypeParavirtual = "paravirtual" ) +// VirtualizationType_Values returns all elements of the VirtualizationType enum +func VirtualizationType_Values() []string { + return []string{ + VirtualizationTypeHvm, + VirtualizationTypeParavirtual, + } +} + const ( // VolumeAttachmentStateAttaching is a VolumeAttachmentState enum value VolumeAttachmentStateAttaching = "attaching" @@ -112467,6 +120184,17 @@ const ( VolumeAttachmentStateBusy = "busy" ) +// VolumeAttachmentState_Values returns all elements of the VolumeAttachmentState enum +func VolumeAttachmentState_Values() []string { + return []string{ + VolumeAttachmentStateAttaching, + VolumeAttachmentStateAttached, + VolumeAttachmentStateDetaching, + VolumeAttachmentStateDetached, + VolumeAttachmentStateBusy, + } +} + const ( // VolumeAttributeNameAutoEnableIo is a VolumeAttributeName enum value VolumeAttributeNameAutoEnableIo = "autoEnableIO" @@ -112475,6 +120203,14 @@ const ( VolumeAttributeNameProductCodes = "productCodes" ) +// VolumeAttributeName_Values returns all elements of the VolumeAttributeName enum +func VolumeAttributeName_Values() []string { + return []string{ + VolumeAttributeNameAutoEnableIo, + VolumeAttributeNameProductCodes, + } +} + const ( // VolumeModificationStateModifying is a VolumeModificationState enum value VolumeModificationStateModifying = "modifying" @@ -112489,6 +120225,16 @@ const ( VolumeModificationStateFailed = "failed" ) +// VolumeModificationState_Values returns all elements of the VolumeModificationState enum +func VolumeModificationState_Values() []string { + return []string{ + VolumeModificationStateModifying, + VolumeModificationStateOptimizing, + VolumeModificationStateCompleted, + VolumeModificationStateFailed, + } +} + const ( // VolumeStateCreating is a VolumeState enum value VolumeStateCreating = "creating" @@ -112509,6 +120255,18 @@ const ( VolumeStateError = "error" ) +// VolumeState_Values returns all elements of the VolumeState enum +func VolumeState_Values() []string { + return []string{ + VolumeStateCreating, + VolumeStateAvailable, + VolumeStateInUse, + VolumeStateDeleting, + VolumeStateDeleted, + VolumeStateError, + } +} + const ( // VolumeStatusInfoStatusOk is a VolumeStatusInfoStatus enum value VolumeStatusInfoStatusOk = "ok" @@ -112520,6 +120278,15 @@ const ( VolumeStatusInfoStatusInsufficientData = "insufficient-data" ) +// VolumeStatusInfoStatus_Values returns all elements of the VolumeStatusInfoStatus enum +func VolumeStatusInfoStatus_Values() []string { + return []string{ + VolumeStatusInfoStatusOk, + VolumeStatusInfoStatusImpaired, + VolumeStatusInfoStatusInsufficientData, + } +} + const ( // VolumeStatusNameIoEnabled is a VolumeStatusName enum value VolumeStatusNameIoEnabled = "io-enabled" @@ -112528,6 +120295,14 @@ const ( VolumeStatusNameIoPerformance = "io-performance" ) +// VolumeStatusName_Values returns all elements of the VolumeStatusName enum +func VolumeStatusName_Values() []string { + return []string{ + VolumeStatusNameIoEnabled, + VolumeStatusNameIoPerformance, + } +} + const ( // VolumeTypeStandard is a VolumeType enum value VolumeTypeStandard = "standard" @@ -112535,6 +120310,9 @@ const ( // VolumeTypeIo1 is a VolumeType enum value VolumeTypeIo1 = "io1" + // VolumeTypeIo2 is a VolumeType enum value + VolumeTypeIo2 = "io2" + // VolumeTypeGp2 is a VolumeType enum value VolumeTypeGp2 = "gp2" @@ -112545,6 +120323,18 @@ const ( VolumeTypeSt1 = "st1" ) +// VolumeType_Values returns all elements of the VolumeType enum +func VolumeType_Values() []string { + return []string{ + VolumeTypeStandard, + VolumeTypeIo1, + VolumeTypeIo2, + VolumeTypeGp2, + VolumeTypeSc1, + VolumeTypeSt1, + } +} + const ( // VpcAttributeNameEnableDnsSupport is a VpcAttributeName enum value VpcAttributeNameEnableDnsSupport = "enableDnsSupport" @@ -112553,6 +120343,14 @@ const ( VpcAttributeNameEnableDnsHostnames = "enableDnsHostnames" ) +// VpcAttributeName_Values returns all elements of the VpcAttributeName enum +func VpcAttributeName_Values() []string { + return []string{ + VpcAttributeNameEnableDnsSupport, + VpcAttributeNameEnableDnsHostnames, + } +} + const ( // VpcCidrBlockStateCodeAssociating is a VpcCidrBlockStateCode enum value VpcCidrBlockStateCodeAssociating = "associating" @@ -112573,6 +120371,18 @@ const ( VpcCidrBlockStateCodeFailed = "failed" ) +// VpcCidrBlockStateCode_Values returns all elements of the VpcCidrBlockStateCode enum +func VpcCidrBlockStateCode_Values() []string { + return []string{ + VpcCidrBlockStateCodeAssociating, + VpcCidrBlockStateCodeAssociated, + VpcCidrBlockStateCodeDisassociating, + VpcCidrBlockStateCodeDisassociated, + VpcCidrBlockStateCodeFailing, + VpcCidrBlockStateCodeFailed, + } +} + const ( // VpcEndpointTypeInterface is a VpcEndpointType enum value VpcEndpointTypeInterface = "Interface" @@ -112581,6 +120391,14 @@ const ( VpcEndpointTypeGateway = "Gateway" ) +// VpcEndpointType_Values returns all elements of the VpcEndpointType enum +func VpcEndpointType_Values() []string { + return []string{ + VpcEndpointTypeInterface, + VpcEndpointTypeGateway, + } +} + const ( // VpcPeeringConnectionStateReasonCodeInitiatingRequest is a VpcPeeringConnectionStateReasonCode enum value VpcPeeringConnectionStateReasonCodeInitiatingRequest = "initiating-request" @@ -112610,6 +120428,21 @@ const ( VpcPeeringConnectionStateReasonCodeDeleting = "deleting" ) +// VpcPeeringConnectionStateReasonCode_Values returns all elements of the VpcPeeringConnectionStateReasonCode enum +func VpcPeeringConnectionStateReasonCode_Values() []string { + return []string{ + VpcPeeringConnectionStateReasonCodeInitiatingRequest, + VpcPeeringConnectionStateReasonCodePendingAcceptance, + VpcPeeringConnectionStateReasonCodeActive, + VpcPeeringConnectionStateReasonCodeDeleted, + VpcPeeringConnectionStateReasonCodeRejected, + VpcPeeringConnectionStateReasonCodeFailed, + VpcPeeringConnectionStateReasonCodeExpired, + VpcPeeringConnectionStateReasonCodeProvisioning, + VpcPeeringConnectionStateReasonCodeDeleting, + } +} + const ( // VpcStatePending is a VpcState enum value VpcStatePending = "pending" @@ -112618,11 +120451,26 @@ const ( VpcStateAvailable = "available" ) +// VpcState_Values returns all elements of the VpcState enum +func VpcState_Values() []string { + return []string{ + VpcStatePending, + VpcStateAvailable, + } +} + const ( // VpcTenancyDefault is a VpcTenancy enum value VpcTenancyDefault = "default" ) +// VpcTenancy_Values returns all elements of the VpcTenancy enum +func VpcTenancy_Values() []string { + return []string{ + VpcTenancyDefault, + } +} + const ( // VpnEcmpSupportValueEnable is a VpnEcmpSupportValue enum value VpnEcmpSupportValueEnable = "enable" @@ -112631,11 +120479,26 @@ const ( VpnEcmpSupportValueDisable = "disable" ) +// VpnEcmpSupportValue_Values returns all elements of the VpnEcmpSupportValue enum +func VpnEcmpSupportValue_Values() []string { + return []string{ + VpnEcmpSupportValueEnable, + VpnEcmpSupportValueDisable, + } +} + const ( // VpnProtocolOpenvpn is a VpnProtocol enum value VpnProtocolOpenvpn = "openvpn" ) +// VpnProtocol_Values returns all elements of the VpnProtocol enum +func VpnProtocol_Values() []string { + return []string{ + VpnProtocolOpenvpn, + } +} + const ( // VpnStatePending is a VpnState enum value VpnStatePending = "pending" @@ -112650,7 +120513,24 @@ const ( VpnStateDeleted = "deleted" ) +// VpnState_Values returns all elements of the VpnState enum +func VpnState_Values() []string { + return []string{ + VpnStatePending, + VpnStateAvailable, + VpnStateDeleting, + VpnStateDeleted, + } +} + const ( // VpnStaticRouteSourceStatic is a VpnStaticRouteSource enum value VpnStaticRouteSourceStatic = "Static" ) + +// VpnStaticRouteSource_Values returns all elements of the VpnStaticRouteSource enum +func VpnStaticRouteSource_Values() []string { + return []string{ + VpnStaticRouteSourceStatic, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations.go index efec8d8a9..3ad305918 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ec2/customizations.go @@ -26,8 +26,12 @@ func init() { // only set the retryer on request if config doesn't have a retryer if r.Config.Retryer == nil && (r.Operation.Name == opModifyNetworkInterfaceAttribute || r.Operation.Name == opAssignPrivateIpAddresses) { + maxRetries := client.DefaultRetryerMaxNumRetries + if m := r.Config.MaxRetries; m != nil && *m != aws.UseServiceDefaultRetries { + maxRetries = *m + } r.Retryer = client.DefaultRetryer{ - NumMaxRetries: client.DefaultRetryerMaxNumRetries, + NumMaxRetries: maxRetries, MinRetryDelay: customRetryerMinRetryDelay, MinThrottleDelay: customRetryerMinRetryDelay, MaxRetryDelay: customRetryerMaxRetryDelay, diff --git a/vendor/github.com/aws/aws-sdk-go/service/ec2/ec2iface/interface.go b/vendor/github.com/aws/aws-sdk-go/service/ec2/ec2iface/interface.go index 8cfda3d6c..6e1ae78f1 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ec2/ec2iface/interface.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ec2/ec2iface/interface.go @@ -228,6 +228,10 @@ type EC2API interface { CreateCapacityReservationWithContext(aws.Context, *ec2.CreateCapacityReservationInput, ...request.Option) (*ec2.CreateCapacityReservationOutput, error) CreateCapacityReservationRequest(*ec2.CreateCapacityReservationInput) (*request.Request, *ec2.CreateCapacityReservationOutput) + CreateCarrierGateway(*ec2.CreateCarrierGatewayInput) (*ec2.CreateCarrierGatewayOutput, error) + CreateCarrierGatewayWithContext(aws.Context, *ec2.CreateCarrierGatewayInput, ...request.Option) (*ec2.CreateCarrierGatewayOutput, error) + CreateCarrierGatewayRequest(*ec2.CreateCarrierGatewayInput) (*request.Request, *ec2.CreateCarrierGatewayOutput) + CreateClientVpnEndpoint(*ec2.CreateClientVpnEndpointInput) (*ec2.CreateClientVpnEndpointOutput, error) CreateClientVpnEndpointWithContext(aws.Context, *ec2.CreateClientVpnEndpointInput, ...request.Option) (*ec2.CreateClientVpnEndpointOutput, error) CreateClientVpnEndpointRequest(*ec2.CreateClientVpnEndpointInput) (*request.Request, *ec2.CreateClientVpnEndpointOutput) @@ -300,6 +304,10 @@ type EC2API interface { CreateLocalGatewayRouteTableVpcAssociationWithContext(aws.Context, *ec2.CreateLocalGatewayRouteTableVpcAssociationInput, ...request.Option) (*ec2.CreateLocalGatewayRouteTableVpcAssociationOutput, error) CreateLocalGatewayRouteTableVpcAssociationRequest(*ec2.CreateLocalGatewayRouteTableVpcAssociationInput) (*request.Request, *ec2.CreateLocalGatewayRouteTableVpcAssociationOutput) + CreateManagedPrefixList(*ec2.CreateManagedPrefixListInput) (*ec2.CreateManagedPrefixListOutput, error) + CreateManagedPrefixListWithContext(aws.Context, *ec2.CreateManagedPrefixListInput, ...request.Option) (*ec2.CreateManagedPrefixListOutput, error) + CreateManagedPrefixListRequest(*ec2.CreateManagedPrefixListInput) (*request.Request, *ec2.CreateManagedPrefixListOutput) + CreateNatGateway(*ec2.CreateNatGatewayInput) (*ec2.CreateNatGatewayOutput, error) CreateNatGatewayWithContext(aws.Context, *ec2.CreateNatGatewayInput, ...request.Option) (*ec2.CreateNatGatewayOutput, error) CreateNatGatewayRequest(*ec2.CreateNatGatewayInput) (*request.Request, *ec2.CreateNatGatewayOutput) @@ -388,6 +396,10 @@ type EC2API interface { CreateTransitGatewayPeeringAttachmentWithContext(aws.Context, *ec2.CreateTransitGatewayPeeringAttachmentInput, ...request.Option) (*ec2.CreateTransitGatewayPeeringAttachmentOutput, error) CreateTransitGatewayPeeringAttachmentRequest(*ec2.CreateTransitGatewayPeeringAttachmentInput) (*request.Request, *ec2.CreateTransitGatewayPeeringAttachmentOutput) + CreateTransitGatewayPrefixListReference(*ec2.CreateTransitGatewayPrefixListReferenceInput) (*ec2.CreateTransitGatewayPrefixListReferenceOutput, error) + CreateTransitGatewayPrefixListReferenceWithContext(aws.Context, *ec2.CreateTransitGatewayPrefixListReferenceInput, ...request.Option) (*ec2.CreateTransitGatewayPrefixListReferenceOutput, error) + CreateTransitGatewayPrefixListReferenceRequest(*ec2.CreateTransitGatewayPrefixListReferenceInput) (*request.Request, *ec2.CreateTransitGatewayPrefixListReferenceOutput) + CreateTransitGatewayRoute(*ec2.CreateTransitGatewayRouteInput) (*ec2.CreateTransitGatewayRouteOutput, error) CreateTransitGatewayRouteWithContext(aws.Context, *ec2.CreateTransitGatewayRouteInput, ...request.Option) (*ec2.CreateTransitGatewayRouteOutput, error) CreateTransitGatewayRouteRequest(*ec2.CreateTransitGatewayRouteInput) (*request.Request, *ec2.CreateTransitGatewayRouteOutput) @@ -436,6 +448,10 @@ type EC2API interface { CreateVpnGatewayWithContext(aws.Context, *ec2.CreateVpnGatewayInput, ...request.Option) (*ec2.CreateVpnGatewayOutput, error) CreateVpnGatewayRequest(*ec2.CreateVpnGatewayInput) (*request.Request, *ec2.CreateVpnGatewayOutput) + DeleteCarrierGateway(*ec2.DeleteCarrierGatewayInput) (*ec2.DeleteCarrierGatewayOutput, error) + DeleteCarrierGatewayWithContext(aws.Context, *ec2.DeleteCarrierGatewayInput, ...request.Option) (*ec2.DeleteCarrierGatewayOutput, error) + DeleteCarrierGatewayRequest(*ec2.DeleteCarrierGatewayInput) (*request.Request, *ec2.DeleteCarrierGatewayOutput) + DeleteClientVpnEndpoint(*ec2.DeleteClientVpnEndpointInput) (*ec2.DeleteClientVpnEndpointOutput, error) DeleteClientVpnEndpointWithContext(aws.Context, *ec2.DeleteClientVpnEndpointInput, ...request.Option) (*ec2.DeleteClientVpnEndpointOutput, error) DeleteClientVpnEndpointRequest(*ec2.DeleteClientVpnEndpointInput) (*request.Request, *ec2.DeleteClientVpnEndpointOutput) @@ -492,6 +508,10 @@ type EC2API interface { DeleteLocalGatewayRouteTableVpcAssociationWithContext(aws.Context, *ec2.DeleteLocalGatewayRouteTableVpcAssociationInput, ...request.Option) (*ec2.DeleteLocalGatewayRouteTableVpcAssociationOutput, error) DeleteLocalGatewayRouteTableVpcAssociationRequest(*ec2.DeleteLocalGatewayRouteTableVpcAssociationInput) (*request.Request, *ec2.DeleteLocalGatewayRouteTableVpcAssociationOutput) + DeleteManagedPrefixList(*ec2.DeleteManagedPrefixListInput) (*ec2.DeleteManagedPrefixListOutput, error) + DeleteManagedPrefixListWithContext(aws.Context, *ec2.DeleteManagedPrefixListInput, ...request.Option) (*ec2.DeleteManagedPrefixListOutput, error) + DeleteManagedPrefixListRequest(*ec2.DeleteManagedPrefixListInput) (*request.Request, *ec2.DeleteManagedPrefixListOutput) + DeleteNatGateway(*ec2.DeleteNatGatewayInput) (*ec2.DeleteNatGatewayOutput, error) DeleteNatGatewayWithContext(aws.Context, *ec2.DeleteNatGatewayInput, ...request.Option) (*ec2.DeleteNatGatewayOutput, error) DeleteNatGatewayRequest(*ec2.DeleteNatGatewayInput) (*request.Request, *ec2.DeleteNatGatewayOutput) @@ -576,6 +596,10 @@ type EC2API interface { DeleteTransitGatewayPeeringAttachmentWithContext(aws.Context, *ec2.DeleteTransitGatewayPeeringAttachmentInput, ...request.Option) (*ec2.DeleteTransitGatewayPeeringAttachmentOutput, error) DeleteTransitGatewayPeeringAttachmentRequest(*ec2.DeleteTransitGatewayPeeringAttachmentInput) (*request.Request, *ec2.DeleteTransitGatewayPeeringAttachmentOutput) + DeleteTransitGatewayPrefixListReference(*ec2.DeleteTransitGatewayPrefixListReferenceInput) (*ec2.DeleteTransitGatewayPrefixListReferenceOutput, error) + DeleteTransitGatewayPrefixListReferenceWithContext(aws.Context, *ec2.DeleteTransitGatewayPrefixListReferenceInput, ...request.Option) (*ec2.DeleteTransitGatewayPrefixListReferenceOutput, error) + DeleteTransitGatewayPrefixListReferenceRequest(*ec2.DeleteTransitGatewayPrefixListReferenceInput) (*request.Request, *ec2.DeleteTransitGatewayPrefixListReferenceOutput) + DeleteTransitGatewayRoute(*ec2.DeleteTransitGatewayRouteInput) (*ec2.DeleteTransitGatewayRouteOutput, error) DeleteTransitGatewayRouteWithContext(aws.Context, *ec2.DeleteTransitGatewayRouteInput, ...request.Option) (*ec2.DeleteTransitGatewayRouteOutput, error) DeleteTransitGatewayRouteRequest(*ec2.DeleteTransitGatewayRouteInput) (*request.Request, *ec2.DeleteTransitGatewayRouteOutput) @@ -678,6 +702,13 @@ type EC2API interface { DescribeCapacityReservationsPages(*ec2.DescribeCapacityReservationsInput, func(*ec2.DescribeCapacityReservationsOutput, bool) bool) error DescribeCapacityReservationsPagesWithContext(aws.Context, *ec2.DescribeCapacityReservationsInput, func(*ec2.DescribeCapacityReservationsOutput, bool) bool, ...request.Option) error + DescribeCarrierGateways(*ec2.DescribeCarrierGatewaysInput) (*ec2.DescribeCarrierGatewaysOutput, error) + DescribeCarrierGatewaysWithContext(aws.Context, *ec2.DescribeCarrierGatewaysInput, ...request.Option) (*ec2.DescribeCarrierGatewaysOutput, error) + DescribeCarrierGatewaysRequest(*ec2.DescribeCarrierGatewaysInput) (*request.Request, *ec2.DescribeCarrierGatewaysOutput) + + DescribeCarrierGatewaysPages(*ec2.DescribeCarrierGatewaysInput, func(*ec2.DescribeCarrierGatewaysOutput, bool) bool) error + DescribeCarrierGatewaysPagesWithContext(aws.Context, *ec2.DescribeCarrierGatewaysInput, func(*ec2.DescribeCarrierGatewaysOutput, bool) bool, ...request.Option) error + DescribeClassicLinkInstances(*ec2.DescribeClassicLinkInstancesInput) (*ec2.DescribeClassicLinkInstancesOutput, error) DescribeClassicLinkInstancesWithContext(aws.Context, *ec2.DescribeClassicLinkInstancesInput, ...request.Option) (*ec2.DescribeClassicLinkInstancesOutput, error) DescribeClassicLinkInstancesRequest(*ec2.DescribeClassicLinkInstancesInput) (*request.Request, *ec2.DescribeClassicLinkInstancesOutput) @@ -979,6 +1010,13 @@ type EC2API interface { DescribeLocalGatewaysPages(*ec2.DescribeLocalGatewaysInput, func(*ec2.DescribeLocalGatewaysOutput, bool) bool) error DescribeLocalGatewaysPagesWithContext(aws.Context, *ec2.DescribeLocalGatewaysInput, func(*ec2.DescribeLocalGatewaysOutput, bool) bool, ...request.Option) error + DescribeManagedPrefixLists(*ec2.DescribeManagedPrefixListsInput) (*ec2.DescribeManagedPrefixListsOutput, error) + DescribeManagedPrefixListsWithContext(aws.Context, *ec2.DescribeManagedPrefixListsInput, ...request.Option) (*ec2.DescribeManagedPrefixListsOutput, error) + DescribeManagedPrefixListsRequest(*ec2.DescribeManagedPrefixListsInput) (*request.Request, *ec2.DescribeManagedPrefixListsOutput) + + DescribeManagedPrefixListsPages(*ec2.DescribeManagedPrefixListsInput, func(*ec2.DescribeManagedPrefixListsOutput, bool) bool) error + DescribeManagedPrefixListsPagesWithContext(aws.Context, *ec2.DescribeManagedPrefixListsInput, func(*ec2.DescribeManagedPrefixListsOutput, bool) bool, ...request.Option) error + DescribeMovingAddresses(*ec2.DescribeMovingAddressesInput) (*ec2.DescribeMovingAddressesOutput, error) DescribeMovingAddressesWithContext(aws.Context, *ec2.DescribeMovingAddressesInput, ...request.Option) (*ec2.DescribeMovingAddressesOutput, error) DescribeMovingAddressesRequest(*ec2.DescribeMovingAddressesInput) (*request.Request, *ec2.DescribeMovingAddressesOutput) @@ -1485,6 +1523,13 @@ type EC2API interface { GetEbsEncryptionByDefaultWithContext(aws.Context, *ec2.GetEbsEncryptionByDefaultInput, ...request.Option) (*ec2.GetEbsEncryptionByDefaultOutput, error) GetEbsEncryptionByDefaultRequest(*ec2.GetEbsEncryptionByDefaultInput) (*request.Request, *ec2.GetEbsEncryptionByDefaultOutput) + GetGroupsForCapacityReservation(*ec2.GetGroupsForCapacityReservationInput) (*ec2.GetGroupsForCapacityReservationOutput, error) + GetGroupsForCapacityReservationWithContext(aws.Context, *ec2.GetGroupsForCapacityReservationInput, ...request.Option) (*ec2.GetGroupsForCapacityReservationOutput, error) + GetGroupsForCapacityReservationRequest(*ec2.GetGroupsForCapacityReservationInput) (*request.Request, *ec2.GetGroupsForCapacityReservationOutput) + + GetGroupsForCapacityReservationPages(*ec2.GetGroupsForCapacityReservationInput, func(*ec2.GetGroupsForCapacityReservationOutput, bool) bool) error + GetGroupsForCapacityReservationPagesWithContext(aws.Context, *ec2.GetGroupsForCapacityReservationInput, func(*ec2.GetGroupsForCapacityReservationOutput, bool) bool, ...request.Option) error + GetHostReservationPurchasePreview(*ec2.GetHostReservationPurchasePreviewInput) (*ec2.GetHostReservationPurchasePreviewOutput, error) GetHostReservationPurchasePreviewWithContext(aws.Context, *ec2.GetHostReservationPurchasePreviewInput, ...request.Option) (*ec2.GetHostReservationPurchasePreviewOutput, error) GetHostReservationPurchasePreviewRequest(*ec2.GetHostReservationPurchasePreviewInput) (*request.Request, *ec2.GetHostReservationPurchasePreviewOutput) @@ -1493,6 +1538,20 @@ type EC2API interface { GetLaunchTemplateDataWithContext(aws.Context, *ec2.GetLaunchTemplateDataInput, ...request.Option) (*ec2.GetLaunchTemplateDataOutput, error) GetLaunchTemplateDataRequest(*ec2.GetLaunchTemplateDataInput) (*request.Request, *ec2.GetLaunchTemplateDataOutput) + GetManagedPrefixListAssociations(*ec2.GetManagedPrefixListAssociationsInput) (*ec2.GetManagedPrefixListAssociationsOutput, error) + GetManagedPrefixListAssociationsWithContext(aws.Context, *ec2.GetManagedPrefixListAssociationsInput, ...request.Option) (*ec2.GetManagedPrefixListAssociationsOutput, error) + GetManagedPrefixListAssociationsRequest(*ec2.GetManagedPrefixListAssociationsInput) (*request.Request, *ec2.GetManagedPrefixListAssociationsOutput) + + GetManagedPrefixListAssociationsPages(*ec2.GetManagedPrefixListAssociationsInput, func(*ec2.GetManagedPrefixListAssociationsOutput, bool) bool) error + GetManagedPrefixListAssociationsPagesWithContext(aws.Context, *ec2.GetManagedPrefixListAssociationsInput, func(*ec2.GetManagedPrefixListAssociationsOutput, bool) bool, ...request.Option) error + + GetManagedPrefixListEntries(*ec2.GetManagedPrefixListEntriesInput) (*ec2.GetManagedPrefixListEntriesOutput, error) + GetManagedPrefixListEntriesWithContext(aws.Context, *ec2.GetManagedPrefixListEntriesInput, ...request.Option) (*ec2.GetManagedPrefixListEntriesOutput, error) + GetManagedPrefixListEntriesRequest(*ec2.GetManagedPrefixListEntriesInput) (*request.Request, *ec2.GetManagedPrefixListEntriesOutput) + + GetManagedPrefixListEntriesPages(*ec2.GetManagedPrefixListEntriesInput, func(*ec2.GetManagedPrefixListEntriesOutput, bool) bool) error + GetManagedPrefixListEntriesPagesWithContext(aws.Context, *ec2.GetManagedPrefixListEntriesInput, func(*ec2.GetManagedPrefixListEntriesOutput, bool) bool, ...request.Option) error + GetPasswordData(*ec2.GetPasswordDataInput) (*ec2.GetPasswordDataOutput, error) GetPasswordDataWithContext(aws.Context, *ec2.GetPasswordDataInput, ...request.Option) (*ec2.GetPasswordDataOutput, error) GetPasswordDataRequest(*ec2.GetPasswordDataInput) (*request.Request, *ec2.GetPasswordDataOutput) @@ -1515,6 +1574,13 @@ type EC2API interface { GetTransitGatewayMulticastDomainAssociationsPages(*ec2.GetTransitGatewayMulticastDomainAssociationsInput, func(*ec2.GetTransitGatewayMulticastDomainAssociationsOutput, bool) bool) error GetTransitGatewayMulticastDomainAssociationsPagesWithContext(aws.Context, *ec2.GetTransitGatewayMulticastDomainAssociationsInput, func(*ec2.GetTransitGatewayMulticastDomainAssociationsOutput, bool) bool, ...request.Option) error + GetTransitGatewayPrefixListReferences(*ec2.GetTransitGatewayPrefixListReferencesInput) (*ec2.GetTransitGatewayPrefixListReferencesOutput, error) + GetTransitGatewayPrefixListReferencesWithContext(aws.Context, *ec2.GetTransitGatewayPrefixListReferencesInput, ...request.Option) (*ec2.GetTransitGatewayPrefixListReferencesOutput, error) + GetTransitGatewayPrefixListReferencesRequest(*ec2.GetTransitGatewayPrefixListReferencesInput) (*request.Request, *ec2.GetTransitGatewayPrefixListReferencesOutput) + + GetTransitGatewayPrefixListReferencesPages(*ec2.GetTransitGatewayPrefixListReferencesInput, func(*ec2.GetTransitGatewayPrefixListReferencesOutput, bool) bool) error + GetTransitGatewayPrefixListReferencesPagesWithContext(aws.Context, *ec2.GetTransitGatewayPrefixListReferencesInput, func(*ec2.GetTransitGatewayPrefixListReferencesOutput, bool) bool, ...request.Option) error + GetTransitGatewayRouteTableAssociations(*ec2.GetTransitGatewayRouteTableAssociationsInput) (*ec2.GetTransitGatewayRouteTableAssociationsOutput, error) GetTransitGatewayRouteTableAssociationsWithContext(aws.Context, *ec2.GetTransitGatewayRouteTableAssociationsInput, ...request.Option) (*ec2.GetTransitGatewayRouteTableAssociationsOutput, error) GetTransitGatewayRouteTableAssociationsRequest(*ec2.GetTransitGatewayRouteTableAssociationsInput) (*request.Request, *ec2.GetTransitGatewayRouteTableAssociationsOutput) @@ -1625,6 +1691,10 @@ type EC2API interface { ModifyLaunchTemplateWithContext(aws.Context, *ec2.ModifyLaunchTemplateInput, ...request.Option) (*ec2.ModifyLaunchTemplateOutput, error) ModifyLaunchTemplateRequest(*ec2.ModifyLaunchTemplateInput) (*request.Request, *ec2.ModifyLaunchTemplateOutput) + ModifyManagedPrefixList(*ec2.ModifyManagedPrefixListInput) (*ec2.ModifyManagedPrefixListOutput, error) + ModifyManagedPrefixListWithContext(aws.Context, *ec2.ModifyManagedPrefixListInput, ...request.Option) (*ec2.ModifyManagedPrefixListOutput, error) + ModifyManagedPrefixListRequest(*ec2.ModifyManagedPrefixListInput) (*request.Request, *ec2.ModifyManagedPrefixListOutput) + ModifyNetworkInterfaceAttribute(*ec2.ModifyNetworkInterfaceAttributeInput) (*ec2.ModifyNetworkInterfaceAttributeOutput, error) ModifyNetworkInterfaceAttributeWithContext(aws.Context, *ec2.ModifyNetworkInterfaceAttributeInput, ...request.Option) (*ec2.ModifyNetworkInterfaceAttributeOutput, error) ModifyNetworkInterfaceAttributeRequest(*ec2.ModifyNetworkInterfaceAttributeInput) (*request.Request, *ec2.ModifyNetworkInterfaceAttributeOutput) @@ -1657,6 +1727,14 @@ type EC2API interface { ModifyTrafficMirrorSessionWithContext(aws.Context, *ec2.ModifyTrafficMirrorSessionInput, ...request.Option) (*ec2.ModifyTrafficMirrorSessionOutput, error) ModifyTrafficMirrorSessionRequest(*ec2.ModifyTrafficMirrorSessionInput) (*request.Request, *ec2.ModifyTrafficMirrorSessionOutput) + ModifyTransitGateway(*ec2.ModifyTransitGatewayInput) (*ec2.ModifyTransitGatewayOutput, error) + ModifyTransitGatewayWithContext(aws.Context, *ec2.ModifyTransitGatewayInput, ...request.Option) (*ec2.ModifyTransitGatewayOutput, error) + ModifyTransitGatewayRequest(*ec2.ModifyTransitGatewayInput) (*request.Request, *ec2.ModifyTransitGatewayOutput) + + ModifyTransitGatewayPrefixListReference(*ec2.ModifyTransitGatewayPrefixListReferenceInput) (*ec2.ModifyTransitGatewayPrefixListReferenceOutput, error) + ModifyTransitGatewayPrefixListReferenceWithContext(aws.Context, *ec2.ModifyTransitGatewayPrefixListReferenceInput, ...request.Option) (*ec2.ModifyTransitGatewayPrefixListReferenceOutput, error) + ModifyTransitGatewayPrefixListReferenceRequest(*ec2.ModifyTransitGatewayPrefixListReferenceInput) (*request.Request, *ec2.ModifyTransitGatewayPrefixListReferenceOutput) + ModifyTransitGatewayVpcAttachment(*ec2.ModifyTransitGatewayVpcAttachmentInput) (*ec2.ModifyTransitGatewayVpcAttachmentOutput, error) ModifyTransitGatewayVpcAttachmentWithContext(aws.Context, *ec2.ModifyTransitGatewayVpcAttachmentInput, ...request.Option) (*ec2.ModifyTransitGatewayVpcAttachmentOutput, error) ModifyTransitGatewayVpcAttachmentRequest(*ec2.ModifyTransitGatewayVpcAttachmentInput) (*request.Request, *ec2.ModifyTransitGatewayVpcAttachmentOutput) @@ -1701,6 +1779,10 @@ type EC2API interface { ModifyVpnConnectionWithContext(aws.Context, *ec2.ModifyVpnConnectionInput, ...request.Option) (*ec2.ModifyVpnConnectionOutput, error) ModifyVpnConnectionRequest(*ec2.ModifyVpnConnectionInput) (*request.Request, *ec2.ModifyVpnConnectionOutput) + ModifyVpnConnectionOptions(*ec2.ModifyVpnConnectionOptionsInput) (*ec2.ModifyVpnConnectionOptionsOutput, error) + ModifyVpnConnectionOptionsWithContext(aws.Context, *ec2.ModifyVpnConnectionOptionsInput, ...request.Option) (*ec2.ModifyVpnConnectionOptionsOutput, error) + ModifyVpnConnectionOptionsRequest(*ec2.ModifyVpnConnectionOptionsInput) (*request.Request, *ec2.ModifyVpnConnectionOptionsOutput) + ModifyVpnTunnelCertificate(*ec2.ModifyVpnTunnelCertificateInput) (*ec2.ModifyVpnTunnelCertificateOutput, error) ModifyVpnTunnelCertificateWithContext(aws.Context, *ec2.ModifyVpnTunnelCertificateInput, ...request.Option) (*ec2.ModifyVpnTunnelCertificateOutput, error) ModifyVpnTunnelCertificateRequest(*ec2.ModifyVpnTunnelCertificateInput) (*request.Request, *ec2.ModifyVpnTunnelCertificateOutput) @@ -1841,6 +1923,10 @@ type EC2API interface { RestoreAddressToClassicWithContext(aws.Context, *ec2.RestoreAddressToClassicInput, ...request.Option) (*ec2.RestoreAddressToClassicOutput, error) RestoreAddressToClassicRequest(*ec2.RestoreAddressToClassicInput) (*request.Request, *ec2.RestoreAddressToClassicOutput) + RestoreManagedPrefixListVersion(*ec2.RestoreManagedPrefixListVersionInput) (*ec2.RestoreManagedPrefixListVersionOutput, error) + RestoreManagedPrefixListVersionWithContext(aws.Context, *ec2.RestoreManagedPrefixListVersionInput, ...request.Option) (*ec2.RestoreManagedPrefixListVersionOutput, error) + RestoreManagedPrefixListVersionRequest(*ec2.RestoreManagedPrefixListVersionInput) (*request.Request, *ec2.RestoreManagedPrefixListVersionOutput) + RevokeClientVpnIngress(*ec2.RevokeClientVpnIngressInput) (*ec2.RevokeClientVpnIngressOutput, error) RevokeClientVpnIngressWithContext(aws.Context, *ec2.RevokeClientVpnIngressInput, ...request.Option) (*ec2.RevokeClientVpnIngressOutput, error) RevokeClientVpnIngressRequest(*ec2.RevokeClientVpnIngressInput) (*request.Request, *ec2.RevokeClientVpnIngressOutput) diff --git a/vendor/github.com/aws/aws-sdk-go/service/ecr/api.go b/vendor/github.com/aws/aws-sdk-go/service/ecr/api.go index 761190b6a..462b049cc 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ecr/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ecr/api.go @@ -60,14 +60,12 @@ func (c *ECR) BatchCheckLayerAvailabilityRequest(input *BatchCheckLayerAvailabil // Checks the availability of one or more image layers in a repository. // // When an image is pushed to a repository, each image layer is checked to verify -// if it has been uploaded before. If it is, then the image layer is skipped. +// if it has been uploaded before. If it has been uploaded, then the image layer +// is skipped. // -// When an image is pulled from a repository, each image layer is checked once -// to verify it is available to be pulled. -// -// This operation is used by the Amazon ECR proxy, and it is not intended for -// general use by customers for pulling and pushing images. In most cases, you -// should use the docker CLI to pull, tag, and push images. +// This operation is used by the Amazon ECR proxy and is not generally used +// by customers for pulling and pushing images. In most cases, you should use +// the docker CLI to pull, tag, and push images. // // 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 @@ -347,9 +345,9 @@ func (c *ECR) CompleteLayerUploadRequest(input *CompleteLayerUploadInput) (req * // When an image is pushed, the CompleteLayerUpload API is called once per each // new image layer to verify that the upload has completed. // -// This operation is used by the Amazon ECR proxy, and it is not intended for -// general use by customers for pulling and pushing images. In most cases, you -// should use the docker CLI to pull, tag, and push images. +// This operation is used by the Amazon ECR proxy and is not generally used +// by customers for pulling and pushing images. In most cases, you should use +// the docker CLI to pull, tag, and push images. // // 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 @@ -371,7 +369,7 @@ func (c *ECR) CompleteLayerUploadRequest(input *CompleteLayerUploadInput) (req * // repository and ensure that you are performing operations on the correct registry. // // * UploadNotFoundException -// The upload could not be found, or the specified upload id is not valid for +// The upload could not be found, or the specified upload ID is not valid for // this repository. // // * InvalidLayerException @@ -387,6 +385,9 @@ func (c *ECR) CompleteLayerUploadRequest(input *CompleteLayerUploadInput) (req * // * EmptyUploadException // The specified layer upload does not contain any layer parts. // +// * KmsException +// The operation failed due to a KMS exception. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/CompleteLayerUpload func (c *ECR) CompleteLayerUpload(input *CompleteLayerUploadInput) (*CompleteLayerUploadOutput, error) { req, out := c.CompleteLayerUploadRequest(input) @@ -485,10 +486,12 @@ func (c *ECR) CreateRepositoryRequest(input *CreateRepositoryInput) (req *reques // // * LimitExceededException // The operation did not succeed because it would have exceeded a service limit -// for your account. For more information, see Amazon ECR Default Service Limits -// (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service_limits.html) +// for your account. For more information, see Amazon ECR Service Quotas (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html) // in the Amazon Elastic Container Registry User Guide. // +// * KmsException +// The operation failed due to a KMS exception. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/CreateRepository func (c *ECR) CreateRepository(input *CreateRepositoryInput) (*CreateRepositoryOutput, error) { req, out := c.CreateRepositoryRequest(input) @@ -672,6 +675,9 @@ func (c *ECR) DeleteRepositoryRequest(input *DeleteRepositoryInput) (req *reques // The specified repository contains images. To delete a repository that contains // images, you must force the deletion with the force parameter. // +// * KmsException +// The operation failed due to a KMS exception. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/DeleteRepository func (c *ECR) DeleteRepository(input *DeleteRepositoryInput) (*DeleteRepositoryOutput, error) { req, out := c.DeleteRepositoryRequest(input) @@ -1375,11 +1381,11 @@ func (c *ECR) GetDownloadUrlForLayerRequest(input *GetDownloadUrlForLayerInput) // layer. You can only get URLs for image layers that are referenced in an image. // // When an image is pulled, the GetDownloadUrlForLayer API is called once per -// image layer. +// image layer that is not already cached. // -// This operation is used by the Amazon ECR proxy, and it is not intended for -// general use by customers for pulling and pushing images. In most cases, you -// should use the docker CLI to pull, tag, and push images. +// This operation is used by the Amazon ECR proxy and is not generally used +// by customers for pulling and pushing images. In most cases, you should use +// the docker CLI to pull, tag, and push images. // // 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 @@ -1807,12 +1813,12 @@ func (c *ECR) InitiateLayerUploadRequest(input *InitiateLayerUploadInput) (req * // Notifies Amazon ECR that you intend to upload an image layer. // // When an image is pushed, the InitiateLayerUpload API is called once per image -// layer that has not already been uploaded. Whether an image layer has been -// uploaded before is determined by the BatchCheckLayerAvailability API action. +// layer that has not already been uploaded. Whether or not an image layer has +// been uploaded is determined by the BatchCheckLayerAvailability API action. // -// This operation is used by the Amazon ECR proxy, and it is not intended for -// general use by customers for pulling and pushing images. In most cases, you -// should use the docker CLI to pull, tag, and push images. +// This operation is used by the Amazon ECR proxy and is not generally used +// by customers for pulling and pushing images. In most cases, you should use +// the docker CLI to pull, tag, and push images. // // 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 @@ -1833,6 +1839,9 @@ func (c *ECR) InitiateLayerUploadRequest(input *InitiateLayerUploadInput) (req * // The specified repository could not be found. Check the spelling of the specified // repository and ensure that you are performing operations on the correct registry. // +// * KmsException +// The operation failed due to a KMS exception. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/InitiateLayerUpload func (c *ECR) InitiateLayerUpload(input *InitiateLayerUploadInput) (*InitiateLayerUploadOutput, error) { req, out := c.InitiateLayerUploadRequest(input) @@ -2141,12 +2150,12 @@ func (c *ECR) PutImageRequest(input *PutImageInput) (req *request.Request, outpu // Creates or updates the image manifest and tags associated with an image. // // When an image is pushed and all new image layers have been uploaded, the -// PutImage API is called once to create or update the image manifest and tags -// associated with the image. +// PutImage API is called once to create or update the image manifest and the +// tags associated with the image. // -// This operation is used by the Amazon ECR proxy, and it is not intended for -// general use by customers for pulling and pushing images. In most cases, you -// should use the docker CLI to pull, tag, and push images. +// This operation is used by the Amazon ECR proxy and is not generally used +// by customers for pulling and pushing images. In most cases, you should use +// the docker CLI to pull, tag, and push images. // // 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 @@ -2175,16 +2184,25 @@ func (c *ECR) PutImageRequest(input *PutImageInput) (req *request.Request, outpu // The specified layers could not be found, or the specified layer is not valid // for this repository. // +// * ReferencedImagesNotFoundException +// The manifest list is referencing an image that does not exist. +// // * LimitExceededException // The operation did not succeed because it would have exceeded a service limit -// for your account. For more information, see Amazon ECR Default Service Limits -// (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service_limits.html) +// for your account. For more information, see Amazon ECR Service Quotas (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html) // in the Amazon Elastic Container Registry User Guide. // // * ImageTagAlreadyExistsException // The specified image is tagged with a tag that already exists. The repository // is configured for tag immutability. // +// * ImageDigestDoesNotMatchException +// The specified image digest does not match the digest that Amazon ECR calculated +// for the image. +// +// * KmsException +// The operation failed due to a KMS exception. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/PutImage func (c *ECR) PutImage(input *PutImageInput) (*PutImageOutput, error) { req, out := c.PutImageRequest(input) @@ -2516,7 +2534,7 @@ func (c *ECR) SetRepositoryPolicyRequest(input *SetRepositoryPolicyInput) (req * // SetRepositoryPolicy API operation for Amazon EC2 Container Registry. // // Applies a repository policy to the specified repository to control access -// permissions. For more information, see Amazon ECR Repository Policies (https://docs.aws.amazon.com/AmazonECR/latest/userguide/RepositoryPolicies.html) +// permissions. For more information, see Amazon ECR Repository Policies (https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-policies.html) // in the Amazon Elastic Container Registry User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -2624,6 +2642,14 @@ func (c *ECR) StartImageScanRequest(input *StartImageScanInput) (req *request.Re // The specified parameter is invalid. Review the available parameters for the // API request. // +// * UnsupportedImageTypeException +// The image is of a type that cannot be scanned. +// +// * LimitExceededException +// The operation did not succeed because it would have exceeded a service limit +// for your account. For more information, see Amazon ECR Service Quotas (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html) +// in the Amazon Elastic Container Registry User Guide. +// // * RepositoryNotFoundException // The specified repository could not be found. Check the spelling of the specified // repository and ensure that you are performing operations on the correct registry. @@ -2724,8 +2750,8 @@ func (c *ECR) StartLifecyclePolicyPreviewRequest(input *StartLifecyclePolicyPrev // The lifecycle policy could not be found, and no policy is set to the repository. // // * LifecyclePolicyPreviewInProgressException -// The previous lifecycle policy preview request has not completed. Please try -// again later. +// The previous lifecycle policy preview request has not completed. Wait and +// try again. // // See also, https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/StartLifecyclePolicyPreview func (c *ECR) StartLifecyclePolicyPreview(input *StartLifecyclePolicyPreviewInput) (*StartLifecyclePolicyPreviewOutput, error) { @@ -2994,9 +3020,9 @@ func (c *ECR) UploadLayerPartRequest(input *UploadLayerPartInput) (req *request. // size of each image layer part can be 20971520 bytes (or about 20MB). The // UploadLayerPart API is called once per each new image layer part. // -// This operation is used by the Amazon ECR proxy, and it is not intended for -// general use by customers for pulling and pushing images. In most cases, you -// should use the docker CLI to pull, tag, and push images. +// This operation is used by the Amazon ECR proxy and is not generally used +// by customers for pulling and pushing images. In most cases, you should use +// the docker CLI to pull, tag, and push images. // // 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 @@ -3022,15 +3048,17 @@ func (c *ECR) UploadLayerPartRequest(input *UploadLayerPartInput) (req *request. // repository and ensure that you are performing operations on the correct registry. // // * UploadNotFoundException -// The upload could not be found, or the specified upload id is not valid for +// The upload could not be found, or the specified upload ID is not valid for // this repository. // // * LimitExceededException // The operation did not succeed because it would have exceeded a service limit -// for your account. For more information, see Amazon ECR Default Service Limits -// (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service_limits.html) +// for your account. For more information, see Amazon ECR Service Quotas (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html) // in the Amazon Elastic Container Registry User Guide. // +// * KmsException +// The operation failed due to a KMS exception. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21/UploadLayerPart func (c *ECR) UploadLayerPart(input *UploadLayerPartInput) (*UploadLayerPartOutput, error) { req, out := c.UploadLayerPartRequest(input) @@ -3611,9 +3639,12 @@ func (s *CompleteLayerUploadOutput) SetUploadId(v string) *CompleteLayerUploadOu type CreateRepositoryInput struct { _ struct{} `type:"structure"` - // The image scanning configuration for the repository. This setting determines - // whether images are scanned for known vulnerabilities after being pushed to - // the repository. + // The encryption configuration for the repository. This determines how the + // contents of your repository are encrypted at rest. + EncryptionConfiguration *EncryptionConfiguration `locationName:"encryptionConfiguration" type:"structure"` + + // The image scanning configuration for the repository. This determines whether + // images are scanned for known vulnerabilities after being pushed to the repository. ImageScanningConfiguration *ImageScanningConfiguration `locationName:"imageScanningConfiguration" type:"structure"` // The tag mutability setting for the repository. If this parameter is omitted, @@ -3655,6 +3686,11 @@ func (s *CreateRepositoryInput) Validate() error { if s.RepositoryName != nil && len(*s.RepositoryName) < 2 { invalidParams.Add(request.NewErrParamMinLen("RepositoryName", 2)) } + if s.EncryptionConfiguration != nil { + if err := s.EncryptionConfiguration.Validate(); err != nil { + invalidParams.AddNested("EncryptionConfiguration", err.(request.ErrInvalidParams)) + } + } if invalidParams.Len() > 0 { return invalidParams @@ -3662,6 +3698,12 @@ func (s *CreateRepositoryInput) Validate() error { return nil } +// SetEncryptionConfiguration sets the EncryptionConfiguration field's value. +func (s *CreateRepositoryInput) SetEncryptionConfiguration(v *EncryptionConfiguration) *CreateRepositoryInput { + s.EncryptionConfiguration = v + return s +} + // SetImageScanningConfiguration sets the ImageScanningConfiguration field's value. func (s *CreateRepositoryInput) SetImageScanningConfiguration(v *ImageScanningConfiguration) *CreateRepositoryInput { s.ImageScanningConfiguration = v @@ -4512,6 +4554,87 @@ func (s *EmptyUploadException) RequestID() string { return s.RespMetadata.RequestID } +// The encryption configuration for the repository. This determines how the +// contents of your repository are encrypted at rest. +// +// By default, when no encryption configuration is set or the AES256 encryption +// type is used, Amazon ECR uses server-side encryption with Amazon S3-managed +// encryption keys which encrypts your data at rest using an AES-256 encryption +// algorithm. This does not require any action on your part. +// +// For more control over the encryption of the contents of your repository, +// you can use server-side encryption with customer master keys (CMKs) stored +// in AWS Key Management Service (AWS KMS) to encrypt your images. For more +// information, see Amazon ECR encryption at rest (https://docs.aws.amazon.com/AmazonECR/latest/userguide/encryption-at-rest.html) +// in the Amazon Elastic Container Registry User Guide. +type EncryptionConfiguration struct { + _ struct{} `type:"structure"` + + // The encryption type to use. + // + // If you use the KMS encryption type, the contents of the repository will be + // encrypted using server-side encryption with customer master keys (CMKs) stored + // in AWS KMS. When you use AWS KMS to encrypt your data, you can either use + // the default AWS managed CMK for Amazon ECR, or specify your own CMK, which + // you already created. For more information, see Protecting Data Using Server-Side + // Encryption with CMKs Stored in AWS Key Management Service (SSE-KMS) (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html) + // in the Amazon Simple Storage Service Console Developer Guide.. + // + // If you use the AES256 encryption type, Amazon ECR uses server-side encryption + // with Amazon S3-managed encryption keys which encrypts the images in the repository + // using an AES-256 encryption algorithm. For more information, see Protecting + // Data Using Server-Side Encryption with Amazon S3-Managed Encryption Keys + // (SSE-S3) (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html) + // in the Amazon Simple Storage Service Console Developer Guide.. + // + // EncryptionType is a required field + EncryptionType *string `locationName:"encryptionType" type:"string" required:"true" enum:"EncryptionType"` + + // If you use the KMS encryption type, specify the CMK to use for encryption. + // The alias, key ID, or full ARN of the CMK can be specified. The key must + // exist in the same Region as the repository. If no key is specified, the default + // AWS managed CMK for Amazon ECR will be used. + KmsKey *string `locationName:"kmsKey" min:"1" type:"string"` +} + +// String returns the string representation +func (s EncryptionConfiguration) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s EncryptionConfiguration) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *EncryptionConfiguration) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "EncryptionConfiguration"} + if s.EncryptionType == nil { + invalidParams.Add(request.NewErrParamRequired("EncryptionType")) + } + if s.KmsKey != nil && len(*s.KmsKey) < 1 { + invalidParams.Add(request.NewErrParamMinLen("KmsKey", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetEncryptionType sets the EncryptionType field's value. +func (s *EncryptionConfiguration) SetEncryptionType(v string) *EncryptionConfiguration { + s.EncryptionType = &v + return s +} + +// SetKmsKey sets the KmsKey field's value. +func (s *EncryptionConfiguration) SetKmsKey(v string) *EncryptionConfiguration { + s.KmsKey = &v + return s +} + type GetAuthorizationTokenInput struct { _ struct{} `type:"structure"` @@ -5070,6 +5193,9 @@ type Image struct { // The image manifest associated with the image. ImageManifest *string `locationName:"imageManifest" min:"1" type:"string"` + // The manifest media type of the image. + ImageManifestMediaType *string `locationName:"imageManifestMediaType" type:"string"` + // The AWS account ID associated with the registry containing the image. RegistryId *string `locationName:"registryId" type:"string"` @@ -5099,6 +5225,12 @@ func (s *Image) SetImageManifest(v string) *Image { return s } +// SetImageManifestMediaType sets the ImageManifestMediaType field's value. +func (s *Image) SetImageManifestMediaType(v string) *Image { + s.ImageManifestMediaType = &v + return s +} + // SetRegistryId sets the RegistryId field's value. func (s *Image) SetRegistryId(v string) *Image { s.RegistryId = &v @@ -5173,9 +5305,15 @@ func (s *ImageAlreadyExistsException) RequestID() string { type ImageDetail struct { _ struct{} `type:"structure"` + // The artifact media type of the image. + ArtifactMediaType *string `locationName:"artifactMediaType" type:"string"` + // The sha256 digest of the image manifest. ImageDigest *string `locationName:"imageDigest" type:"string"` + // The media type of the image manifest. + ImageManifestMediaType *string `locationName:"imageManifestMediaType" type:"string"` + // The date and time, expressed in standard JavaScript date format, at which // the current image was pushed to the repository. ImagePushedAt *time.Time `locationName:"imagePushedAt" type:"timestamp"` @@ -5188,6 +5326,9 @@ type ImageDetail struct { // The size, in bytes, of the image in the repository. // + // If the image is a manifest list, this will be the max size of all manifests + // in the list. + // // Beginning with Docker version 1.9, the Docker client compresses image layers // before pushing them to a V2 Docker registry. The output of the docker images // command shows the uncompressed image size, so it may return a larger image @@ -5214,12 +5355,24 @@ func (s ImageDetail) GoString() string { return s.String() } +// SetArtifactMediaType sets the ArtifactMediaType field's value. +func (s *ImageDetail) SetArtifactMediaType(v string) *ImageDetail { + s.ArtifactMediaType = &v + return s +} + // SetImageDigest sets the ImageDigest field's value. func (s *ImageDetail) SetImageDigest(v string) *ImageDetail { s.ImageDigest = &v return s } +// SetImageManifestMediaType sets the ImageManifestMediaType field's value. +func (s *ImageDetail) SetImageManifestMediaType(v string) *ImageDetail { + s.ImageManifestMediaType = &v + return s +} + // SetImagePushedAt sets the ImagePushedAt field's value. func (s *ImageDetail) SetImagePushedAt(v time.Time) *ImageDetail { s.ImagePushedAt = &v @@ -5262,6 +5415,63 @@ func (s *ImageDetail) SetRepositoryName(v string) *ImageDetail { return s } +// The specified image digest does not match the digest that Amazon ECR calculated +// for the image. +type ImageDigestDoesNotMatchException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s ImageDigestDoesNotMatchException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ImageDigestDoesNotMatchException) GoString() string { + return s.String() +} + +func newErrorImageDigestDoesNotMatchException(v protocol.ResponseMetadata) error { + return &ImageDigestDoesNotMatchException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ImageDigestDoesNotMatchException) Code() string { + return "ImageDigestDoesNotMatchException" +} + +// Message returns the exception's message. +func (s *ImageDigestDoesNotMatchException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ImageDigestDoesNotMatchException) OrigErr() error { + return nil +} + +func (s *ImageDigestDoesNotMatchException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ImageDigestDoesNotMatchException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ImageDigestDoesNotMatchException) RequestID() string { + return s.RespMetadata.RequestID +} + // An object representing an Amazon ECR image failure. type ImageFailure struct { _ struct{} `type:"structure"` @@ -6007,6 +6217,65 @@ func (s *InvalidTagParameterException) RequestID() string { return s.RespMetadata.RequestID } +// The operation failed due to a KMS exception. +type KmsException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + // The error code returned by AWS KMS. + KmsError *string `locationName:"kmsError" type:"string"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s KmsException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s KmsException) GoString() string { + return s.String() +} + +func newErrorKmsException(v protocol.ResponseMetadata) error { + return &KmsException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *KmsException) Code() string { + return "KmsException" +} + +// Message returns the exception's message. +func (s *KmsException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *KmsException) OrigErr() error { + return nil +} + +func (s *KmsException) Error() string { + return fmt.Sprintf("%s: %s\n%s", s.Code(), s.Message(), s.String()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *KmsException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *KmsException) RequestID() string { + return s.RespMetadata.RequestID +} + // An object representing an Amazon ECR image layer. type Layer struct { _ struct{} `type:"structure"` @@ -6411,8 +6680,8 @@ func (s *LifecyclePolicyPreviewFilter) SetTagStatus(v string) *LifecyclePolicyPr return s } -// The previous lifecycle policy preview request has not completed. Please try -// again later. +// The previous lifecycle policy preview request has not completed. Wait and +// try again. type LifecyclePolicyPreviewInProgressException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -6634,8 +6903,7 @@ func (s *LifecyclePolicyRuleAction) SetType(v string) *LifecyclePolicyRuleAction } // The operation did not succeed because it would have exceeded a service limit -// for your account. For more information, see Amazon ECR Default Service Limits -// (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service_limits.html) +// for your account. For more information, see Amazon ECR Service Quotas (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html) // in the Amazon Elastic Container Registry User Guide. type LimitExceededException struct { _ struct{} `type:"structure"` @@ -6912,13 +7180,22 @@ func (s *ListTagsForResourceOutput) SetTags(v []*Tag) *ListTagsForResourceOutput type PutImageInput struct { _ struct{} `type:"structure"` + // The image digest of the image manifest corresponding to the image. + ImageDigest *string `locationName:"imageDigest" type:"string"` + // The image manifest corresponding to the image to be uploaded. // // ImageManifest is a required field ImageManifest *string `locationName:"imageManifest" min:"1" type:"string" required:"true"` + // The media type of the image manifest. If you push an image manifest that + // does not contain the mediaType field, you must specify the imageManifestMediaType + // in the request. + ImageManifestMediaType *string `locationName:"imageManifestMediaType" type:"string"` + // The tag to associate with the image. This parameter is required for images - // that use the Docker Image Manifest V2 Schema 2 or OCI formats. + // that use the Docker Image Manifest V2 Schema 2 or Open Container Initiative + // (OCI) formats. ImageTag *string `locationName:"imageTag" min:"1" type:"string"` // The AWS account ID associated with the registry that contains the repository @@ -6967,12 +7244,24 @@ func (s *PutImageInput) Validate() error { return nil } +// SetImageDigest sets the ImageDigest field's value. +func (s *PutImageInput) SetImageDigest(v string) *PutImageInput { + s.ImageDigest = &v + return s +} + // SetImageManifest sets the ImageManifest field's value. func (s *PutImageInput) SetImageManifest(v string) *PutImageInput { s.ImageManifest = &v return s } +// SetImageManifestMediaType sets the ImageManifestMediaType field's value. +func (s *PutImageInput) SetImageManifestMediaType(v string) *PutImageInput { + s.ImageManifestMediaType = &v + return s +} + // SetImageTag sets the ImageTag field's value. func (s *PutImageInput) SetImageTag(v string) *PutImageInput { s.ImageTag = &v @@ -7342,6 +7631,62 @@ func (s *PutLifecyclePolicyOutput) SetRepositoryName(v string) *PutLifecyclePoli return s } +// The manifest list is referencing an image that does not exist. +type ReferencedImagesNotFoundException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s ReferencedImagesNotFoundException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ReferencedImagesNotFoundException) GoString() string { + return s.String() +} + +func newErrorReferencedImagesNotFoundException(v protocol.ResponseMetadata) error { + return &ReferencedImagesNotFoundException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *ReferencedImagesNotFoundException) Code() string { + return "ReferencedImagesNotFoundException" +} + +// Message returns the exception's message. +func (s *ReferencedImagesNotFoundException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *ReferencedImagesNotFoundException) OrigErr() error { + return nil +} + +func (s *ReferencedImagesNotFoundException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *ReferencedImagesNotFoundException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *ReferencedImagesNotFoundException) RequestID() string { + return s.RespMetadata.RequestID +} + // An object representing a repository. type Repository struct { _ struct{} `type:"structure"` @@ -7349,6 +7694,10 @@ type Repository struct { // The date and time, in JavaScript date format, when the repository was created. CreatedAt *time.Time `locationName:"createdAt" type:"timestamp"` + // The encryption configuration for the repository. This determines how the + // contents of your repository are encrypted at rest. + EncryptionConfiguration *EncryptionConfiguration `locationName:"encryptionConfiguration" type:"structure"` + // The image scanning configuration for a repository. ImageScanningConfiguration *ImageScanningConfiguration `locationName:"imageScanningConfiguration" type:"structure"` @@ -7367,8 +7716,8 @@ type Repository struct { // The name of the repository. RepositoryName *string `locationName:"repositoryName" min:"2" type:"string"` - // The URI for the repository. You can use this URI for Docker push or pull - // operations. + // The URI for the repository. You can use this URI for container image push + // and pull operations. RepositoryUri *string `locationName:"repositoryUri" type:"string"` } @@ -7388,6 +7737,12 @@ func (s *Repository) SetCreatedAt(v time.Time) *Repository { return s } +// SetEncryptionConfiguration sets the EncryptionConfiguration field's value. +func (s *Repository) SetEncryptionConfiguration(v *EncryptionConfiguration) *Repository { + s.EncryptionConfiguration = v + return s +} + // SetImageScanningConfiguration sets the ImageScanningConfiguration field's value. func (s *Repository) SetImageScanningConfiguration(v *ImageScanningConfiguration) *Repository { s.ImageScanningConfiguration = v @@ -7778,7 +8133,7 @@ type SetRepositoryPolicyInput struct { Force *bool `locationName:"force" type:"boolean"` // The JSON repository policy text to apply to the repository. For more information, - // see Amazon ECR Repository Policy Examples (https://docs.aws.amazon.com/AmazonECR/latest/userguide/RepositoryPolicyExamples.html) + // see Amazon ECR Repository Policies (https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-policy-examples.html) // in the Amazon Elastic Container Registry User Guide. // // PolicyText is a required field @@ -8287,6 +8642,62 @@ func (s *TooManyTagsException) RequestID() string { return s.RespMetadata.RequestID } +// The image is of a type that cannot be scanned. +type UnsupportedImageTypeException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"message" type:"string"` +} + +// String returns the string representation +func (s UnsupportedImageTypeException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s UnsupportedImageTypeException) GoString() string { + return s.String() +} + +func newErrorUnsupportedImageTypeException(v protocol.ResponseMetadata) error { + return &UnsupportedImageTypeException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *UnsupportedImageTypeException) Code() string { + return "UnsupportedImageTypeException" +} + +// Message returns the exception's message. +func (s *UnsupportedImageTypeException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *UnsupportedImageTypeException) OrigErr() error { + return nil +} + +func (s *UnsupportedImageTypeException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *UnsupportedImageTypeException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *UnsupportedImageTypeException) RequestID() string { + return s.RespMetadata.RequestID +} + type UntagResourceInput struct { _ struct{} `type:"structure"` @@ -8364,12 +8775,14 @@ type UploadLayerPartInput struct { // LayerPartBlob is a required field LayerPartBlob []byte `locationName:"layerPartBlob" type:"blob" required:"true"` - // The integer value of the first byte of the layer part. + // The position of the first byte of the layer part witin the overall image + // layer. // // PartFirstByte is a required field PartFirstByte *int64 `locationName:"partFirstByte" type:"long" required:"true"` - // The integer value of the last byte of the layer part. + // The position of the last byte of the layer part within the overall image + // layer. // // PartLastByte is a required field PartLastByte *int64 `locationName:"partLastByte" type:"long" required:"true"` @@ -8514,7 +8927,7 @@ func (s *UploadLayerPartOutput) SetUploadId(v string) *UploadLayerPartOutput { return s } -// The upload could not be found, or the specified upload id is not valid for +// The upload could not be found, or the specified upload ID is not valid for // this repository. type UploadNotFoundException struct { _ struct{} `type:"structure"` @@ -8572,6 +8985,22 @@ func (s *UploadNotFoundException) RequestID() string { return s.RespMetadata.RequestID } +const ( + // EncryptionTypeAes256 is a EncryptionType enum value + EncryptionTypeAes256 = "AES256" + + // EncryptionTypeKms is a EncryptionType enum value + EncryptionTypeKms = "KMS" +) + +// EncryptionType_Values returns all elements of the EncryptionType enum +func EncryptionType_Values() []string { + return []string{ + EncryptionTypeAes256, + EncryptionTypeKms, + } +} + const ( // FindingSeverityInformational is a FindingSeverity enum value FindingSeverityInformational = "INFORMATIONAL" @@ -8592,11 +9021,30 @@ const ( FindingSeverityUndefined = "UNDEFINED" ) +// FindingSeverity_Values returns all elements of the FindingSeverity enum +func FindingSeverity_Values() []string { + return []string{ + FindingSeverityInformational, + FindingSeverityLow, + FindingSeverityMedium, + FindingSeverityHigh, + FindingSeverityCritical, + FindingSeverityUndefined, + } +} + const ( // ImageActionTypeExpire is a ImageActionType enum value ImageActionTypeExpire = "EXPIRE" ) +// ImageActionType_Values returns all elements of the ImageActionType enum +func ImageActionType_Values() []string { + return []string{ + ImageActionTypeExpire, + } +} + const ( // ImageFailureCodeInvalidImageDigest is a ImageFailureCode enum value ImageFailureCodeInvalidImageDigest = "InvalidImageDigest" @@ -8612,8 +9060,27 @@ const ( // ImageFailureCodeMissingDigestAndTag is a ImageFailureCode enum value ImageFailureCodeMissingDigestAndTag = "MissingDigestAndTag" + + // ImageFailureCodeImageReferencedByManifestList is a ImageFailureCode enum value + ImageFailureCodeImageReferencedByManifestList = "ImageReferencedByManifestList" + + // ImageFailureCodeKmsError is a ImageFailureCode enum value + ImageFailureCodeKmsError = "KmsError" ) +// ImageFailureCode_Values returns all elements of the ImageFailureCode enum +func ImageFailureCode_Values() []string { + return []string{ + ImageFailureCodeInvalidImageDigest, + ImageFailureCodeInvalidImageTag, + ImageFailureCodeImageTagDoesNotMatchDigest, + ImageFailureCodeImageNotFound, + ImageFailureCodeMissingDigestAndTag, + ImageFailureCodeImageReferencedByManifestList, + ImageFailureCodeKmsError, + } +} + const ( // ImageTagMutabilityMutable is a ImageTagMutability enum value ImageTagMutabilityMutable = "MUTABLE" @@ -8622,6 +9089,14 @@ const ( ImageTagMutabilityImmutable = "IMMUTABLE" ) +// ImageTagMutability_Values returns all elements of the ImageTagMutability enum +func ImageTagMutability_Values() []string { + return []string{ + ImageTagMutabilityMutable, + ImageTagMutabilityImmutable, + } +} + const ( // LayerAvailabilityAvailable is a LayerAvailability enum value LayerAvailabilityAvailable = "AVAILABLE" @@ -8630,6 +9105,14 @@ const ( LayerAvailabilityUnavailable = "UNAVAILABLE" ) +// LayerAvailability_Values returns all elements of the LayerAvailability enum +func LayerAvailability_Values() []string { + return []string{ + LayerAvailabilityAvailable, + LayerAvailabilityUnavailable, + } +} + const ( // LayerFailureCodeInvalidLayerDigest is a LayerFailureCode enum value LayerFailureCodeInvalidLayerDigest = "InvalidLayerDigest" @@ -8638,6 +9121,14 @@ const ( LayerFailureCodeMissingLayerDigest = "MissingLayerDigest" ) +// LayerFailureCode_Values returns all elements of the LayerFailureCode enum +func LayerFailureCode_Values() []string { + return []string{ + LayerFailureCodeInvalidLayerDigest, + LayerFailureCodeMissingLayerDigest, + } +} + const ( // LifecyclePolicyPreviewStatusInProgress is a LifecyclePolicyPreviewStatus enum value LifecyclePolicyPreviewStatusInProgress = "IN_PROGRESS" @@ -8652,6 +9143,16 @@ const ( LifecyclePolicyPreviewStatusFailed = "FAILED" ) +// LifecyclePolicyPreviewStatus_Values returns all elements of the LifecyclePolicyPreviewStatus enum +func LifecyclePolicyPreviewStatus_Values() []string { + return []string{ + LifecyclePolicyPreviewStatusInProgress, + LifecyclePolicyPreviewStatusComplete, + LifecyclePolicyPreviewStatusExpired, + LifecyclePolicyPreviewStatusFailed, + } +} + const ( // ScanStatusInProgress is a ScanStatus enum value ScanStatusInProgress = "IN_PROGRESS" @@ -8663,6 +9164,15 @@ const ( ScanStatusFailed = "FAILED" ) +// ScanStatus_Values returns all elements of the ScanStatus enum +func ScanStatus_Values() []string { + return []string{ + ScanStatusInProgress, + ScanStatusComplete, + ScanStatusFailed, + } +} + const ( // TagStatusTagged is a TagStatus enum value TagStatusTagged = "TAGGED" @@ -8673,3 +9183,12 @@ const ( // TagStatusAny is a TagStatus enum value TagStatusAny = "ANY" ) + +// TagStatus_Values returns all elements of the TagStatus enum +func TagStatus_Values() []string { + return []string{ + TagStatusTagged, + TagStatusUntagged, + TagStatusAny, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ecr/doc.go b/vendor/github.com/aws/aws-sdk-go/service/ecr/doc.go index d970974bc..3c3843ae3 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ecr/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ecr/doc.go @@ -3,12 +3,13 @@ // Package ecr provides the client and types for making API // requests to Amazon EC2 Container Registry. // -// Amazon Elastic Container Registry (Amazon ECR) is a managed Docker registry -// service. Customers can use the familiar Docker CLI to push, pull, and manage -// images. Amazon ECR provides a secure, scalable, and reliable registry. Amazon -// ECR supports private Docker repositories with resource-based permissions +// Amazon Elastic Container Registry (Amazon ECR) is a managed container image +// registry service. Customers can use the familiar Docker CLI, or their preferred +// client, to push, pull, and manage images. Amazon ECR provides a secure, scalable, +// and reliable registry for your Docker or Open Container Initiative (OCI) +// images. Amazon ECR supports private repositories with resource-based permissions // using IAM so that specific users or Amazon EC2 instances can access repositories -// and images. Developers can use the Docker CLI to author and manage images. +// and images. // // See https://docs.aws.amazon.com/goto/WebAPI/ecr-2015-09-21 for more information on this service. // diff --git a/vendor/github.com/aws/aws-sdk-go/service/ecr/errors.go b/vendor/github.com/aws/aws-sdk-go/service/ecr/errors.go index 732d865bf..819101326 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ecr/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ecr/errors.go @@ -21,6 +21,13 @@ const ( // the manifest or image tag after the last push. ErrCodeImageAlreadyExistsException = "ImageAlreadyExistsException" + // ErrCodeImageDigestDoesNotMatchException for service response error code + // "ImageDigestDoesNotMatchException". + // + // The specified image digest does not match the digest that Amazon ECR calculated + // for the image. + ErrCodeImageDigestDoesNotMatchException = "ImageDigestDoesNotMatchException" + // ErrCodeImageNotFoundException for service response error code // "ImageNotFoundException". // @@ -63,6 +70,12 @@ const ( // characters. ErrCodeInvalidTagParameterException = "InvalidTagParameterException" + // ErrCodeKmsException for service response error code + // "KmsException". + // + // The operation failed due to a KMS exception. + ErrCodeKmsException = "KmsException" + // ErrCodeLayerAlreadyExistsException for service response error code // "LayerAlreadyExistsException". // @@ -98,8 +111,8 @@ const ( // ErrCodeLifecyclePolicyPreviewInProgressException for service response error code // "LifecyclePolicyPreviewInProgressException". // - // The previous lifecycle policy preview request has not completed. Please try - // again later. + // The previous lifecycle policy preview request has not completed. Wait and + // try again. ErrCodeLifecyclePolicyPreviewInProgressException = "LifecyclePolicyPreviewInProgressException" // ErrCodeLifecyclePolicyPreviewNotFoundException for service response error code @@ -112,11 +125,16 @@ const ( // "LimitExceededException". // // The operation did not succeed because it would have exceeded a service limit - // for your account. For more information, see Amazon ECR Default Service Limits - // (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service_limits.html) + // for your account. For more information, see Amazon ECR Service Quotas (https://docs.aws.amazon.com/AmazonECR/latest/userguide/service-quotas.html) // in the Amazon Elastic Container Registry User Guide. ErrCodeLimitExceededException = "LimitExceededException" + // ErrCodeReferencedImagesNotFoundException for service response error code + // "ReferencedImagesNotFoundException". + // + // The manifest list is referencing an image that does not exist. + ErrCodeReferencedImagesNotFoundException = "ReferencedImagesNotFoundException" + // ErrCodeRepositoryAlreadyExistsException for service response error code // "RepositoryAlreadyExistsException". // @@ -164,10 +182,16 @@ const ( // of tags that can be applied to a repository is 50. ErrCodeTooManyTagsException = "TooManyTagsException" + // ErrCodeUnsupportedImageTypeException for service response error code + // "UnsupportedImageTypeException". + // + // The image is of a type that cannot be scanned. + ErrCodeUnsupportedImageTypeException = "UnsupportedImageTypeException" + // ErrCodeUploadNotFoundException for service response error code // "UploadNotFoundException". // - // The upload could not be found, or the specified upload id is not valid for + // The upload could not be found, or the specified upload ID is not valid for // this repository. ErrCodeUploadNotFoundException = "UploadNotFoundException" ) @@ -175,12 +199,14 @@ const ( var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "EmptyUploadException": newErrorEmptyUploadException, "ImageAlreadyExistsException": newErrorImageAlreadyExistsException, + "ImageDigestDoesNotMatchException": newErrorImageDigestDoesNotMatchException, "ImageNotFoundException": newErrorImageNotFoundException, "ImageTagAlreadyExistsException": newErrorImageTagAlreadyExistsException, "InvalidLayerException": newErrorInvalidLayerException, "InvalidLayerPartException": newErrorInvalidLayerPartException, "InvalidParameterException": newErrorInvalidParameterException, "InvalidTagParameterException": newErrorInvalidTagParameterException, + "KmsException": newErrorKmsException, "LayerAlreadyExistsException": newErrorLayerAlreadyExistsException, "LayerInaccessibleException": newErrorLayerInaccessibleException, "LayerPartTooSmallException": newErrorLayerPartTooSmallException, @@ -189,6 +215,7 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "LifecyclePolicyPreviewInProgressException": newErrorLifecyclePolicyPreviewInProgressException, "LifecyclePolicyPreviewNotFoundException": newErrorLifecyclePolicyPreviewNotFoundException, "LimitExceededException": newErrorLimitExceededException, + "ReferencedImagesNotFoundException": newErrorReferencedImagesNotFoundException, "RepositoryAlreadyExistsException": newErrorRepositoryAlreadyExistsException, "RepositoryNotEmptyException": newErrorRepositoryNotEmptyException, "RepositoryNotFoundException": newErrorRepositoryNotFoundException, @@ -196,5 +223,6 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "ScanNotFoundException": newErrorScanNotFoundException, "ServerException": newErrorServerException, "TooManyTagsException": newErrorTooManyTagsException, + "UnsupportedImageTypeException": newErrorUnsupportedImageTypeException, "UploadNotFoundException": newErrorUploadNotFoundException, } diff --git a/vendor/github.com/aws/aws-sdk-go/service/iam/api.go b/vendor/github.com/aws/aws-sdk-go/service/iam/api.go index eb606e835..7c3a5dd0d 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/iam/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/iam/api.go @@ -82,7 +82,8 @@ func (c *IAM) AddClientIDToOpenIDConnectProviderRequest(input *AddClientIDToOpen // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -156,10 +157,12 @@ func (c *IAM) AddRoleToInstanceProfileRequest(input *AddRoleToInstanceProfileInp // AddRoleToInstanceProfile API operation for AWS Identity and Access Management. // // Adds the specified IAM role to the specified instance profile. An instance -// profile can contain only one role, and this limit cannot be increased. You -// can remove the existing role and then add a different role to an instance -// profile. You must then wait for the change to appear across all of AWS because -// of eventual consistency (https://en.wikipedia.org/wiki/Eventual_consistency). +// profile can contain only one role. (The number and size of IAM resources +// in an AWS account are limited. For more information, see IAM and STS Quotas +// (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) +// in the IAM User Guide.) You can remove the existing role and then add a different +// role to an instance profile. You must then wait for the change to appear +// across all of AWS because of eventual consistency (https://en.wikipedia.org/wiki/Eventual_consistency). // To force the change, you must disassociate the instance profile (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DisassociateIamInstanceProfile.html) // and then associate the instance profile (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AssociateIamInstanceProfile.html), // or you can stop your instance and then restart it. @@ -189,7 +192,8 @@ func (c *IAM) AddRoleToInstanceProfileRequest(input *AddRoleToInstanceProfileInp // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" // The request was rejected because only the service that depends on the service-linked @@ -284,7 +288,8 @@ func (c *IAM) AddUserToGroupRequest(input *AddUserToGroupInput) (req *request.Re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -380,7 +385,8 @@ func (c *IAM) AttachGroupPolicyRequest(input *AttachGroupPolicyInput) (req *requ // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -488,7 +494,8 @@ func (c *IAM) AttachRolePolicyRequest(input *AttachRolePolicyInput) (req *reques // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -598,7 +605,8 @@ func (c *IAM) AttachUserPolicyRequest(input *AttachUserPolicyInput) (req *reques // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -704,7 +712,8 @@ func (c *IAM) ChangePasswordRequest(input *ChangePasswordInput) (req *request.Re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeEntityTemporarilyUnmodifiableException "EntityTemporarilyUnmodifiable" // The request was rejected because it referenced an entity that is temporarily @@ -795,8 +804,8 @@ func (c *IAM) CreateAccessKeyRequest(input *CreateAccessKeyInput) (req *request. // to manage AWS account root user credentials. This is true even if the AWS // account has no associated users. // -// For information about limits on the number of keys you can create, see Limitations -// on IAM Entities (https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) +// The number and size of IAM resources in an AWS account are limited. For more +// information, see IAM and STS Quotas (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) // in the IAM User Guide. // // To ensure the security of your AWS account, the secret access key is accessible @@ -819,7 +828,8 @@ func (c *IAM) CreateAccessKeyRequest(input *CreateAccessKeyInput) (req *request. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -910,7 +920,8 @@ func (c *IAM) CreateAccountAliasRequest(input *CreateAccountAliasInput) (req *re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -984,8 +995,8 @@ func (c *IAM) CreateGroupRequest(input *CreateGroupInput) (req *request.Request, // // Creates a new group. // -// For information about the number of groups you can create, see Limitations -// on IAM Entities (https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) +// The number and size of IAM resources in an AWS account are limited. For more +// information, see IAM and STS Quotas (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -998,7 +1009,8 @@ func (c *IAM) CreateGroupRequest(input *CreateGroupInput) (req *request.Request, // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" // The request was rejected because it attempted to create a resource that already @@ -1081,8 +1093,8 @@ func (c *IAM) CreateInstanceProfileRequest(input *CreateInstanceProfileInput) (r // Creates a new instance profile. For information about instance profiles, // go to About Instance Profiles (https://docs.aws.amazon.com/IAM/latest/UserGuide/AboutInstanceProfiles.html). // -// For information about the number of instance profiles you can create, see -// Limitations on IAM Entities (https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) +// The number and size of IAM resources in an AWS account are limited. For more +// information, see IAM and STS Quotas (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -1099,7 +1111,8 @@ func (c *IAM) CreateInstanceProfileRequest(input *CreateInstanceProfileInput) (r // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -1198,7 +1211,8 @@ func (c *IAM) CreateLoginProfileRequest(input *CreateLoginProfileInput) (req *re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -1312,7 +1326,8 @@ func (c *IAM) CreateOpenIDConnectProviderRequest(input *CreateOpenIDConnectProvi // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -1409,7 +1424,8 @@ func (c *IAM) CreatePolicyRequest(input *CreatePolicyInput) (req *request.Reques // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" // The request was rejected because it attempted to create a resource that already @@ -1524,7 +1540,8 @@ func (c *IAM) CreatePolicyVersionRequest(input *CreatePolicyVersionInput) (req * // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -1598,8 +1615,8 @@ func (c *IAM) CreateRoleRequest(input *CreateRoleInput) (req *request.Request, o // // Creates a new role for your AWS account. For more information about roles, // go to IAM Roles (https://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html). -// For information about limitations on role names and the number of roles you -// can create, go to Limitations on IAM Entities (https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) +// The number and size of IAM resources in an AWS account are limited. For more +// information, see IAM and STS Quotas (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -1612,7 +1629,8 @@ func (c *IAM) CreateRoleRequest(input *CreateRoleInput) (req *request.Request, o // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -1742,7 +1760,8 @@ func (c *IAM) CreateSAMLProviderRequest(input *CreateSAMLProviderInput) (req *re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -1840,7 +1859,8 @@ func (c *IAM) CreateServiceLinkedRoleRequest(input *CreateServiceLinkedRoleInput // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeNoSuchEntityException "NoSuchEntity" // The request was rejected because it referenced a resource entity that does @@ -1941,7 +1961,8 @@ func (c *IAM) CreateServiceSpecificCredentialRequest(input *CreateServiceSpecifi // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeNoSuchEntityException "NoSuchEntity" // The request was rejected because it referenced a resource entity that does @@ -2018,8 +2039,8 @@ func (c *IAM) CreateUserRequest(input *CreateUserInput) (req *request.Request, o // // Creates a new IAM user for your AWS account. // -// For information about limitations on the number of IAM users you can create, -// see Limitations on IAM Entities (https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) +// The number and size of IAM resources in an AWS account are limited. For more +// information, see IAM and STS Quotas (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -2032,7 +2053,8 @@ func (c *IAM) CreateUserRequest(input *CreateUserInput) (req *request.Request, o // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" // The request was rejected because it attempted to create a resource that already @@ -2127,8 +2149,8 @@ func (c *IAM) CreateVirtualMFADeviceRequest(input *CreateVirtualMFADeviceInput) // go to Using a Virtual MFA Device (https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_VirtualMFA.html) // in the IAM User Guide. // -// For information about limits on the number of MFA devices you can create, -// see Limitations on Entities (https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) +// The number and size of IAM resources in an AWS account are limited. For more +// information, see IAM and STS Quotas (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) // in the IAM User Guide. // // The seed information contained in the QR code and the Base32 string should @@ -2147,7 +2169,8 @@ func (c *IAM) CreateVirtualMFADeviceRequest(input *CreateVirtualMFADeviceInput) // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" // The request was rejected because it attempted to create a resource that already @@ -2251,7 +2274,8 @@ func (c *IAM) DeactivateMFADeviceRequest(input *DeactivateMFADeviceInput) (req * // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -2346,7 +2370,8 @@ func (c *IAM) DeleteAccessKeyRequest(input *DeleteAccessKeyInput) (req *request. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -2437,7 +2462,8 @@ func (c *IAM) DeleteAccountAliasRequest(input *DeleteAccountAliasInput) (req *re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -2526,7 +2552,8 @@ func (c *IAM) DeleteAccountPasswordPolicyRequest(input *DeleteAccountPasswordPol // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -2620,7 +2647,8 @@ func (c *IAM) DeleteGroupRequest(input *DeleteGroupInput) (req *request.Request, // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -2715,7 +2743,8 @@ func (c *IAM) DeleteGroupPolicyRequest(input *DeleteGroupPolicyInput) (req *requ // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -2817,7 +2846,8 @@ func (c *IAM) DeleteInstanceProfileRequest(input *DeleteInstanceProfileInput) (r // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -2918,7 +2948,8 @@ func (c *IAM) DeleteLoginProfileRequest(input *DeleteLoginProfileInput) (req *re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -3125,7 +3156,8 @@ func (c *IAM) DeletePolicyRequest(input *DeletePolicyInput) (req *request.Reques // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -3230,7 +3262,8 @@ func (c *IAM) DeletePolicyVersionRequest(input *DeletePolicyVersionInput) (req * // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -3337,7 +3370,8 @@ func (c *IAM) DeleteRoleRequest(input *DeleteRoleInput) (req *request.Request, o // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" // The request was rejected because only the service that depends on the service-linked @@ -3538,7 +3572,8 @@ func (c *IAM) DeleteRolePolicyRequest(input *DeleteRolePolicyInput) (req *reques // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" // The request was rejected because only the service that depends on the service-linked @@ -3640,7 +3675,8 @@ func (c *IAM) DeleteSAMLProviderRequest(input *DeleteSAMLProviderInput) (req *re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeNoSuchEntityException "NoSuchEntity" // The request was rejected because it referenced a resource entity that does @@ -3839,7 +3875,8 @@ func (c *IAM) DeleteServerCertificateRequest(input *DeleteServerCertificateInput // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -3946,7 +3983,8 @@ func (c *IAM) DeleteServiceLinkedRoleRequest(input *DeleteServiceLinkedRoleInput // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -4122,7 +4160,8 @@ func (c *IAM) DeleteSigningCertificateRequest(input *DeleteSigningCertificateInp // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -4229,7 +4268,8 @@ func (c *IAM) DeleteUserRequest(input *DeleteUserInput) (req *request.Request, o // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeNoSuchEntityException "NoSuchEntity" // The request was rejected because it referenced a resource entity that does @@ -4426,7 +4466,8 @@ func (c *IAM) DeleteUserPolicyRequest(input *DeleteUserPolicyInput) (req *reques // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -4522,7 +4563,8 @@ func (c *IAM) DeleteVirtualMFADeviceRequest(input *DeleteVirtualMFADeviceInput) // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -4616,7 +4658,8 @@ func (c *IAM) DetachGroupPolicyRequest(input *DetachGroupPolicyInput) (req *requ // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -4714,7 +4757,8 @@ func (c *IAM) DetachRolePolicyRequest(input *DetachRolePolicyInput) (req *reques // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -4818,7 +4862,8 @@ func (c *IAM) DetachUserPolicyRequest(input *DetachUserPolicyInput) (req *reques // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -4923,7 +4968,8 @@ func (c *IAM) EnableMFADeviceRequest(input *EnableMFADeviceInput) (req *request. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeNoSuchEntityException "NoSuchEntity" // The request was rejected because it referenced a resource entity that does @@ -5013,7 +5059,8 @@ func (c *IAM) GenerateCredentialReportRequest(input *GenerateCredentialReportInp // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -5326,8 +5373,8 @@ func (c *IAM) GenerateServiceLastAccessedDetailsRequest(input *GenerateServiceLa // see Evaluating Policies (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-basics) // in the IAM User Guide. // -// For more information about service last accessed data, see Reducing Policy -// Scope by Viewing User Activity (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html) +// For more information about service and action last accessed data, see Reducing +// Permissions Using Service Last Accessed Data (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -5726,8 +5773,8 @@ func (c *IAM) GetAccountSummaryRequest(input *GetAccountSummaryInput) (req *requ // // Retrieves information about IAM entity usage and IAM quotas in the AWS account. // -// For information about limitations on IAM entities, see Limitations on IAM -// Entities (https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html) +// The number and size of IAM resources in an AWS account are limited. For more +// information, see IAM and STS Quotas (https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html) // in the IAM User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -7410,6 +7457,15 @@ func (c *IAM) GetServiceLastAccessedDetailsRequest(input *GetServiceLastAccessed // // By default, the list is sorted by service namespace. // +// If you specified ACTION_LEVEL granularity when you generated the report, +// this operation returns service and action last accessed data. This includes +// the most recent access attempt for each tracked action within a service. +// Otherwise, this operation returns only service data. +// +// For more information about service and action last accessed data, see Reducing +// Permissions Using Service Last Accessed Data (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html) +// in the IAM User 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. @@ -11715,7 +11771,8 @@ func (c *IAM) PutGroupPolicyRequest(input *PutGroupPolicyInput) (req *request.Re // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" // The request was rejected because the policy document was malformed. The error @@ -11941,7 +11998,8 @@ func (c *IAM) PutRolePolicyRequest(input *PutRolePolicyInput) (req *request.Requ // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" // The request was rejected because the policy document was malformed. The error @@ -12159,7 +12217,8 @@ func (c *IAM) PutUserPolicyRequest(input *PutUserPolicyInput) (req *request.Requ // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" // The request was rejected because the policy document was malformed. The error @@ -12359,7 +12418,8 @@ func (c *IAM) RemoveRoleFromInstanceProfileRequest(input *RemoveRoleFromInstance // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" // The request was rejected because only the service that depends on the service-linked @@ -12454,7 +12514,8 @@ func (c *IAM) RemoveUserFromGroupRequest(input *RemoveUserFromGroupInput) (req * // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -12635,7 +12696,8 @@ func (c *IAM) ResyncMFADeviceRequest(input *ResyncMFADeviceInput) (req *request. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -12737,7 +12799,8 @@ func (c *IAM) SetDefaultPolicyVersionRequest(input *SetDefaultPolicyVersionInput // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -13292,7 +13355,8 @@ func (c *IAM) TagRoleRequest(input *TagRoleInput) (req *request.Request, output // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -13422,7 +13486,8 @@ func (c *IAM) TagUserRequest(input *TagUserInput) (req *request.Request, output // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeInvalidInputException "InvalidInput" // The request was rejected because an invalid or out-of-range value was supplied @@ -13715,7 +13780,8 @@ func (c *IAM) UpdateAccessKeyRequest(input *UpdateAccessKeyInput) (req *request. // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -13819,7 +13885,8 @@ func (c *IAM) UpdateAccountPasswordPolicyRequest(input *UpdateAccountPasswordPol // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -13915,7 +13982,8 @@ func (c *IAM) UpdateAssumeRolePolicyRequest(input *UpdateAssumeRolePolicyInput) // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeUnmodifiableEntityException "UnmodifiableEntity" // The request was rejected because only the service that depends on the service-linked @@ -14025,7 +14093,8 @@ func (c *IAM) UpdateGroupRequest(input *UpdateGroupInput) (req *request.Request, // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -14128,7 +14197,8 @@ func (c *IAM) UpdateLoginProfileRequest(input *UpdateLoginProfileInput) (req *re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -14509,7 +14579,8 @@ func (c *IAM) UpdateSAMLProviderRequest(input *UpdateSAMLProviderInput) (req *re // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -14711,7 +14782,8 @@ func (c *IAM) UpdateServerCertificateRequest(input *UpdateServerCertificateInput // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -14892,7 +14964,8 @@ func (c *IAM) UpdateSigningCertificateRequest(input *UpdateSigningCertificateInp // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeServiceFailureException "ServiceFailure" // The request processing has failed because of an unknown error, exception @@ -14992,7 +15065,8 @@ func (c *IAM) UpdateUserRequest(input *UpdateUserInput) (req *request.Request, o // // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" // The request was rejected because it attempted to create a resource that already @@ -15097,7 +15171,8 @@ func (c *IAM) UploadSSHPublicKeyRequest(input *UploadSSHPublicKeyInput) (req *re // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeNoSuchEntityException "NoSuchEntity" // The request was rejected because it referenced a resource entity that does @@ -15218,7 +15293,8 @@ func (c *IAM) UploadServerCertificateRequest(input *UploadServerCertificateInput // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" // The request was rejected because it attempted to create a resource that already @@ -15331,7 +15407,8 @@ func (c *IAM) UploadSigningCertificateRequest(input *UploadSigningCertificateInp // Returned Error Codes: // * ErrCodeLimitExceededException "LimitExceeded" // The request was rejected because it attempted to create resources beyond -// the current AWS account limits. The error message describes the limit exceeded. +// the current AWS account limitations. The error message describes the limit +// exceeded. // // * ErrCodeEntityAlreadyExistsException "EntityAlreadyExists" // The request was rejected because it attempted to create a resource that already @@ -20346,6 +20423,14 @@ type GenerateServiceLastAccessedDetailsInput struct { // // Arn is a required field Arn *string `min:"20" type:"string" required:"true"` + + // The level of detail that you want to generate. You can specify whether you + // want to generate information about the last attempt to access services or + // actions. If you specify service-level granularity, this operation generates + // only service data. If you specify action-level granularity, it generates + // service and action data. If you don't include this optional parameter, the + // operation generates service data. + Granularity *string `type:"string" enum:"AccessAdvisorUsageGranularityType"` } // String returns the string representation @@ -20380,6 +20465,12 @@ func (s *GenerateServiceLastAccessedDetailsInput) SetArn(v string) *GenerateServ return s } +// SetGranularity sets the Granularity field's value. +func (s *GenerateServiceLastAccessedDetailsInput) SetGranularity(v string) *GenerateServiceLastAccessedDetailsInput { + s.Granularity = &v + return s +} + type GenerateServiceLastAccessedDetailsOutput struct { _ struct{} `type:"structure"` @@ -22358,6 +22449,11 @@ type GetServiceLastAccessedDetailsOutput struct { // JobStatus is a required field JobStatus *string `type:"string" required:"true" enum:"JobStatusType"` + // The type of job. Service jobs return information about when each service + // was last accessed. Action jobs also include information about when tracked + // actions within the service were last accessed. + JobType *string `type:"string" enum:"AccessAdvisorUsageGranularityType"` + // When IsTruncated is true, this element is present and contains the value // to use for the Marker parameter in a subsequent pagination request. Marker *string `type:"string"` @@ -22409,6 +22505,12 @@ func (s *GetServiceLastAccessedDetailsOutput) SetJobStatus(v string) *GetService return s } +// SetJobType sets the JobType field's value. +func (s *GetServiceLastAccessedDetailsOutput) SetJobType(v string) *GetServiceLastAccessedDetailsOutput { + s.JobType = &v + return s +} + // SetMarker sets the Marker field's value. func (s *GetServiceLastAccessedDetailsOutput) SetMarker(v string) *GetServiceLastAccessedDetailsOutput { s.Marker = &v @@ -29462,6 +29564,13 @@ type ServiceLastAccessed struct { // the reporting period (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#service-last-accessed-reporting-period). LastAuthenticatedEntity *string `min:"20" type:"string"` + // The Region from which the authenticated entity (user or role) last attempted + // to access the service. AWS does not report unauthenticated requests. + // + // This field is null if no IAM entities attempted to access the service within + // the reporting period (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#service-last-accessed-reporting-period). + LastAuthenticatedRegion *string `type:"string"` + // The name of the service in which access was attempted. // // ServiceName is a required field @@ -29486,6 +29595,16 @@ type ServiceLastAccessed struct { // This field is null if no principals attempted to access the service within // the reporting period (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#service-last-accessed-reporting-period). TotalAuthenticatedEntities *int64 `type:"integer"` + + // An object that contains details about the most recent attempt to access a + // tracked action within the service. + // + // This field is null if there no tracked actions or if the principal did not + // use the tracked actions within the reporting period (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#service-last-accessed-reporting-period). + // This field is also null if the report was generated at the service level + // and not the action level. For more information, see the Granularity field + // in GenerateServiceLastAccessedDetails. + TrackedActionsLastAccessed []*TrackedActionLastAccessed `type:"list"` } // String returns the string representation @@ -29510,6 +29629,12 @@ func (s *ServiceLastAccessed) SetLastAuthenticatedEntity(v string) *ServiceLastA return s } +// SetLastAuthenticatedRegion sets the LastAuthenticatedRegion field's value. +func (s *ServiceLastAccessed) SetLastAuthenticatedRegion(v string) *ServiceLastAccessed { + s.LastAuthenticatedRegion = &v + return s +} + // SetServiceName sets the ServiceName field's value. func (s *ServiceLastAccessed) SetServiceName(v string) *ServiceLastAccessed { s.ServiceName = &v @@ -29528,6 +29653,12 @@ func (s *ServiceLastAccessed) SetTotalAuthenticatedEntities(v int64) *ServiceLas return s } +// SetTrackedActionsLastAccessed sets the TrackedActionsLastAccessed field's value. +func (s *ServiceLastAccessed) SetTrackedActionsLastAccessed(v []*TrackedActionLastAccessed) *ServiceLastAccessed { + s.TrackedActionsLastAccessed = v + return s +} + // Contains the details of a service-specific credential. type ServiceSpecificCredential struct { _ struct{} `type:"structure"` @@ -30313,7 +30444,7 @@ type SimulatePrincipalPolicyInput struct { // one permissions boundary when you pass a policy to this operation. An IAM // entity can only have one permissions boundary in effect at a time. For example, // if a permissions boundary is attached to an entity and you pass in a different - // permissions boundary policy using this parameter, then the new permission + // permissions boundary policy using this parameter, then the new permissions // boundary policy is used for the simulation. For more information about permissions // boundaries, see Permissions Boundaries for IAM Entities (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html) // in the IAM User Guide. The policy input is specified as a string containing @@ -30857,6 +30988,75 @@ func (s TagUserOutput) GoString() string { return s.String() } +// Contains details about the most recent attempt to access an action within +// the service. +// +// This data type is used as a response element in the GetServiceLastAccessedDetails +// operation. +type TrackedActionLastAccessed struct { + _ struct{} `type:"structure"` + + // The name of the tracked action to which access was attempted. Tracked actions + // are actions that report activity to IAM. + ActionName *string `type:"string"` + + // The Amazon Resource Name (ARN). ARNs are unique identifiers for AWS resources. + // + // For more information about ARNs, go to Amazon Resource Names (ARNs) and AWS + // Service Namespaces (https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) + // in the AWS General Reference. + LastAccessedEntity *string `min:"20" type:"string"` + + // The Region from which the authenticated entity (user or role) last attempted + // to access the tracked action. AWS does not report unauthenticated requests. + // + // This field is null if no IAM entities attempted to access the service within + // the reporting period (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#service-last-accessed-reporting-period). + LastAccessedRegion *string `type:"string"` + + // The date and time, in ISO 8601 date-time format (http://www.iso.org/iso/iso8601), + // when an authenticated entity most recently attempted to access the tracked + // service. AWS does not report unauthenticated requests. + // + // This field is null if no IAM entities attempted to access the service within + // the reporting period (https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html#service-last-accessed-reporting-period). + LastAccessedTime *time.Time `type:"timestamp"` +} + +// String returns the string representation +func (s TrackedActionLastAccessed) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s TrackedActionLastAccessed) GoString() string { + return s.String() +} + +// SetActionName sets the ActionName field's value. +func (s *TrackedActionLastAccessed) SetActionName(v string) *TrackedActionLastAccessed { + s.ActionName = &v + return s +} + +// SetLastAccessedEntity sets the LastAccessedEntity field's value. +func (s *TrackedActionLastAccessed) SetLastAccessedEntity(v string) *TrackedActionLastAccessed { + s.LastAccessedEntity = &v + return s +} + +// SetLastAccessedRegion sets the LastAccessedRegion field's value. +func (s *TrackedActionLastAccessed) SetLastAccessedRegion(v string) *TrackedActionLastAccessed { + s.LastAccessedRegion = &v + return s +} + +// SetLastAccessedTime sets the LastAccessedTime field's value. +func (s *TrackedActionLastAccessed) SetLastAccessedTime(v time.Time) *TrackedActionLastAccessed { + s.LastAccessedTime = &v + return s +} + type UntagRoleInput struct { _ struct{} `type:"structure"` @@ -33066,6 +33266,22 @@ func (s *VirtualMFADevice) SetUser(v *User) *VirtualMFADevice { return s } +const ( + // AccessAdvisorUsageGranularityTypeServiceLevel is a AccessAdvisorUsageGranularityType enum value + AccessAdvisorUsageGranularityTypeServiceLevel = "SERVICE_LEVEL" + + // AccessAdvisorUsageGranularityTypeActionLevel is a AccessAdvisorUsageGranularityType enum value + AccessAdvisorUsageGranularityTypeActionLevel = "ACTION_LEVEL" +) + +// AccessAdvisorUsageGranularityType_Values returns all elements of the AccessAdvisorUsageGranularityType enum +func AccessAdvisorUsageGranularityType_Values() []string { + return []string{ + AccessAdvisorUsageGranularityTypeServiceLevel, + AccessAdvisorUsageGranularityTypeActionLevel, + } +} + const ( // AssignmentStatusTypeAssigned is a AssignmentStatusType enum value AssignmentStatusTypeAssigned = "Assigned" @@ -33077,6 +33293,15 @@ const ( AssignmentStatusTypeAny = "Any" ) +// AssignmentStatusType_Values returns all elements of the AssignmentStatusType enum +func AssignmentStatusType_Values() []string { + return []string{ + AssignmentStatusTypeAssigned, + AssignmentStatusTypeUnassigned, + AssignmentStatusTypeAny, + } +} + const ( // ContextKeyTypeEnumString is a ContextKeyTypeEnum enum value ContextKeyTypeEnumString = "string" @@ -33115,6 +33340,24 @@ const ( ContextKeyTypeEnumDateList = "dateList" ) +// ContextKeyTypeEnum_Values returns all elements of the ContextKeyTypeEnum enum +func ContextKeyTypeEnum_Values() []string { + return []string{ + ContextKeyTypeEnumString, + ContextKeyTypeEnumStringList, + ContextKeyTypeEnumNumeric, + ContextKeyTypeEnumNumericList, + ContextKeyTypeEnumBoolean, + ContextKeyTypeEnumBooleanList, + ContextKeyTypeEnumIp, + ContextKeyTypeEnumIpList, + ContextKeyTypeEnumBinary, + ContextKeyTypeEnumBinaryList, + ContextKeyTypeEnumDate, + ContextKeyTypeEnumDateList, + } +} + const ( // DeletionTaskStatusTypeSucceeded is a DeletionTaskStatusType enum value DeletionTaskStatusTypeSucceeded = "SUCCEEDED" @@ -33129,6 +33372,16 @@ const ( DeletionTaskStatusTypeNotStarted = "NOT_STARTED" ) +// DeletionTaskStatusType_Values returns all elements of the DeletionTaskStatusType enum +func DeletionTaskStatusType_Values() []string { + return []string{ + DeletionTaskStatusTypeSucceeded, + DeletionTaskStatusTypeInProgress, + DeletionTaskStatusTypeFailed, + DeletionTaskStatusTypeNotStarted, + } +} + const ( // EncodingTypeSsh is a EncodingType enum value EncodingTypeSsh = "SSH" @@ -33137,6 +33390,14 @@ const ( EncodingTypePem = "PEM" ) +// EncodingType_Values returns all elements of the EncodingType enum +func EncodingType_Values() []string { + return []string{ + EncodingTypeSsh, + EncodingTypePem, + } +} + const ( // EntityTypeUser is a EntityType enum value EntityTypeUser = "User" @@ -33154,6 +33415,17 @@ const ( EntityTypeAwsmanagedPolicy = "AWSManagedPolicy" ) +// EntityType_Values returns all elements of the EntityType enum +func EntityType_Values() []string { + return []string{ + EntityTypeUser, + EntityTypeRole, + EntityTypeGroup, + EntityTypeLocalManagedPolicy, + EntityTypeAwsmanagedPolicy, + } +} + const ( // GlobalEndpointTokenVersionV1token is a GlobalEndpointTokenVersion enum value GlobalEndpointTokenVersionV1token = "v1Token" @@ -33162,6 +33434,14 @@ const ( GlobalEndpointTokenVersionV2token = "v2Token" ) +// GlobalEndpointTokenVersion_Values returns all elements of the GlobalEndpointTokenVersion enum +func GlobalEndpointTokenVersion_Values() []string { + return []string{ + GlobalEndpointTokenVersionV1token, + GlobalEndpointTokenVersionV2token, + } +} + const ( // JobStatusTypeInProgress is a JobStatusType enum value JobStatusTypeInProgress = "IN_PROGRESS" @@ -33173,11 +33453,27 @@ const ( JobStatusTypeFailed = "FAILED" ) +// JobStatusType_Values returns all elements of the JobStatusType enum +func JobStatusType_Values() []string { + return []string{ + JobStatusTypeInProgress, + JobStatusTypeCompleted, + JobStatusTypeFailed, + } +} + const ( // PermissionsBoundaryAttachmentTypePermissionsBoundaryPolicy is a PermissionsBoundaryAttachmentType enum value PermissionsBoundaryAttachmentTypePermissionsBoundaryPolicy = "PermissionsBoundaryPolicy" ) +// PermissionsBoundaryAttachmentType_Values returns all elements of the PermissionsBoundaryAttachmentType enum +func PermissionsBoundaryAttachmentType_Values() []string { + return []string{ + PermissionsBoundaryAttachmentTypePermissionsBoundaryPolicy, + } +} + const ( // PolicyEvaluationDecisionTypeAllowed is a PolicyEvaluationDecisionType enum value PolicyEvaluationDecisionTypeAllowed = "allowed" @@ -33189,6 +33485,15 @@ const ( PolicyEvaluationDecisionTypeImplicitDeny = "implicitDeny" ) +// PolicyEvaluationDecisionType_Values returns all elements of the PolicyEvaluationDecisionType enum +func PolicyEvaluationDecisionType_Values() []string { + return []string{ + PolicyEvaluationDecisionTypeAllowed, + PolicyEvaluationDecisionTypeExplicitDeny, + PolicyEvaluationDecisionTypeImplicitDeny, + } +} + const ( // PolicyOwnerEntityTypeUser is a PolicyOwnerEntityType enum value PolicyOwnerEntityTypeUser = "USER" @@ -33200,6 +33505,15 @@ const ( PolicyOwnerEntityTypeGroup = "GROUP" ) +// PolicyOwnerEntityType_Values returns all elements of the PolicyOwnerEntityType enum +func PolicyOwnerEntityType_Values() []string { + return []string{ + PolicyOwnerEntityTypeUser, + PolicyOwnerEntityTypeRole, + PolicyOwnerEntityTypeGroup, + } +} + const ( // PolicyScopeTypeAll is a PolicyScopeType enum value PolicyScopeTypeAll = "All" @@ -33211,6 +33525,15 @@ const ( PolicyScopeTypeLocal = "Local" ) +// PolicyScopeType_Values returns all elements of the PolicyScopeType enum +func PolicyScopeType_Values() []string { + return []string{ + PolicyScopeTypeAll, + PolicyScopeTypeAws, + PolicyScopeTypeLocal, + } +} + const ( // PolicySourceTypeUser is a PolicySourceType enum value PolicySourceTypeUser = "user" @@ -33234,6 +33557,19 @@ const ( PolicySourceTypeNone = "none" ) +// PolicySourceType_Values returns all elements of the PolicySourceType enum +func PolicySourceType_Values() []string { + return []string{ + PolicySourceTypeUser, + PolicySourceTypeGroup, + PolicySourceTypeRole, + PolicySourceTypeAwsManaged, + PolicySourceTypeUserManaged, + PolicySourceTypeResource, + PolicySourceTypeNone, + } +} + const ( // PolicyTypeInline is a PolicyType enum value PolicyTypeInline = "INLINE" @@ -33242,6 +33578,14 @@ const ( PolicyTypeManaged = "MANAGED" ) +// PolicyType_Values returns all elements of the PolicyType enum +func PolicyType_Values() []string { + return []string{ + PolicyTypeInline, + PolicyTypeManaged, + } +} + // The policy usage type that indicates whether the policy is used as a permissions // policy or as the permissions boundary for an entity. // @@ -33256,11 +33600,26 @@ const ( PolicyUsageTypePermissionsBoundary = "PermissionsBoundary" ) +// PolicyUsageType_Values returns all elements of the PolicyUsageType enum +func PolicyUsageType_Values() []string { + return []string{ + PolicyUsageTypePermissionsPolicy, + PolicyUsageTypePermissionsBoundary, + } +} + const ( // ReportFormatTypeTextCsv is a ReportFormatType enum value ReportFormatTypeTextCsv = "text/csv" ) +// ReportFormatType_Values returns all elements of the ReportFormatType enum +func ReportFormatType_Values() []string { + return []string{ + ReportFormatTypeTextCsv, + } +} + const ( // ReportStateTypeStarted is a ReportStateType enum value ReportStateTypeStarted = "STARTED" @@ -33272,6 +33631,15 @@ const ( ReportStateTypeComplete = "COMPLETE" ) +// ReportStateType_Values returns all elements of the ReportStateType enum +func ReportStateType_Values() []string { + return []string{ + ReportStateTypeStarted, + ReportStateTypeInprogress, + ReportStateTypeComplete, + } +} + const ( // SortKeyTypeServiceNamespaceAscending is a SortKeyType enum value SortKeyTypeServiceNamespaceAscending = "SERVICE_NAMESPACE_ASCENDING" @@ -33286,6 +33654,16 @@ const ( SortKeyTypeLastAuthenticatedTimeDescending = "LAST_AUTHENTICATED_TIME_DESCENDING" ) +// SortKeyType_Values returns all elements of the SortKeyType enum +func SortKeyType_Values() []string { + return []string{ + SortKeyTypeServiceNamespaceAscending, + SortKeyTypeServiceNamespaceDescending, + SortKeyTypeLastAuthenticatedTimeAscending, + SortKeyTypeLastAuthenticatedTimeDescending, + } +} + const ( // StatusTypeActive is a StatusType enum value StatusTypeActive = "Active" @@ -33294,6 +33672,14 @@ const ( StatusTypeInactive = "Inactive" ) +// StatusType_Values returns all elements of the StatusType enum +func StatusType_Values() []string { + return []string{ + StatusTypeActive, + StatusTypeInactive, + } +} + const ( // SummaryKeyTypeUsers is a SummaryKeyType enum value SummaryKeyTypeUsers = "Users" @@ -33373,3 +33759,35 @@ const ( // SummaryKeyTypeGlobalEndpointTokenVersion is a SummaryKeyType enum value SummaryKeyTypeGlobalEndpointTokenVersion = "GlobalEndpointTokenVersion" ) + +// SummaryKeyType_Values returns all elements of the SummaryKeyType enum +func SummaryKeyType_Values() []string { + return []string{ + SummaryKeyTypeUsers, + SummaryKeyTypeUsersQuota, + SummaryKeyTypeGroups, + SummaryKeyTypeGroupsQuota, + SummaryKeyTypeServerCertificates, + SummaryKeyTypeServerCertificatesQuota, + SummaryKeyTypeUserPolicySizeQuota, + SummaryKeyTypeGroupPolicySizeQuota, + SummaryKeyTypeGroupsPerUserQuota, + SummaryKeyTypeSigningCertificatesPerUserQuota, + SummaryKeyTypeAccessKeysPerUserQuota, + SummaryKeyTypeMfadevices, + SummaryKeyTypeMfadevicesInUse, + SummaryKeyTypeAccountMfaenabled, + SummaryKeyTypeAccountAccessKeysPresent, + SummaryKeyTypeAccountSigningCertificatesPresent, + SummaryKeyTypeAttachedPoliciesPerGroupQuota, + SummaryKeyTypeAttachedPoliciesPerRoleQuota, + SummaryKeyTypeAttachedPoliciesPerUserQuota, + SummaryKeyTypePolicies, + SummaryKeyTypePoliciesQuota, + SummaryKeyTypePolicySizeQuota, + SummaryKeyTypePolicyVersionsInUse, + SummaryKeyTypePolicyVersionsInUseQuota, + SummaryKeyTypeVersionsPerPolicyQuota, + SummaryKeyTypeGlobalEndpointTokenVersion, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/iam/doc.go b/vendor/github.com/aws/aws-sdk-go/service/iam/doc.go index 0d709cd27..13f89fa19 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/iam/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/iam/doc.go @@ -3,59 +3,12 @@ // Package iam provides the client and types for making API // requests to AWS Identity and Access Management. // -// AWS Identity and Access Management (IAM) is a web service that you can use -// to manage users and user permissions under your AWS account. This guide provides -// descriptions of IAM actions that you can call programmatically. For general -// information about IAM, see AWS Identity and Access Management (IAM) (http://aws.amazon.com/iam/). -// For the user guide for IAM, see Using IAM (https://docs.aws.amazon.com/IAM/latest/UserGuide/). -// -// AWS provides SDKs that consist of libraries and sample code for various programming -// languages and platforms (Java, Ruby, .NET, iOS, Android, etc.). The SDKs -// provide a convenient way to create programmatic access to IAM and AWS. For -// example, the SDKs take care of tasks such as cryptographically signing requests -// (see below), managing errors, and retrying requests automatically. For information -// about the AWS SDKs, including how to download and install them, see the Tools -// for Amazon Web Services (http://aws.amazon.com/tools/) page. -// -// We recommend that you use the AWS SDKs to make programmatic API calls to -// IAM. However, you can also use the IAM Query API to make direct calls to -// the IAM web service. To learn more about the IAM Query API, see Making Query -// Requests (https://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html) -// in the Using IAM guide. IAM supports GET and POST requests for all actions. -// That is, the API does not require you to use GET for some actions and POST -// for others. However, GET requests are subject to the limitation size of a -// URL. Therefore, for operations that require larger sizes, use a POST request. -// -// Signing Requests -// -// Requests must be signed using an access key ID and a secret access key. We -// strongly recommend that you do not use your AWS account access key ID and -// secret access key for everyday work with IAM. You can use the access key -// ID and secret access key for an IAM user or you can use the AWS Security -// Token Service to generate temporary security credentials and use those to -// sign requests. -// -// To sign requests, we recommend that you use Signature Version 4 (https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html). -// If you have an existing application that uses Signature Version 2, you do -// not have to update it to use Signature Version 4. However, some operations -// now require Signature Version 4. The documentation for operations that require -// version 4 indicate this requirement. -// -// Additional Resources -// -// For more information, see the following: -// -// * AWS Security Credentials (https://docs.aws.amazon.com/general/latest/gr/aws-security-credentials.html). -// This topic provides general information about the types of credentials -// used for accessing AWS. -// -// * IAM Best Practices (https://docs.aws.amazon.com/IAM/latest/UserGuide/IAMBestPractices.html). -// This topic presents a list of suggestions for using the IAM service to -// help secure your AWS resources. -// -// * Signing AWS API Requests (https://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html). -// This set of topics walk you through the process of signing a request using -// an access key ID and secret access key. +// AWS Identity and Access Management (IAM) is a web service for securely controlling +// access to AWS services. With IAM, you can centrally manage users, security +// credentials such as access keys, and permissions that control which AWS resources +// users and applications can access. For more information about IAM, see AWS +// Identity and Access Management (IAM) (http://aws.amazon.com/iam/) and the +// AWS Identity and Access Management User Guide (https://docs.aws.amazon.com/IAM/latest/UserGuide/). // // See https://docs.aws.amazon.com/goto/WebAPI/iam-2010-05-08 for more information on this service. // diff --git a/vendor/github.com/aws/aws-sdk-go/service/iam/errors.go b/vendor/github.com/aws/aws-sdk-go/service/iam/errors.go index 30a85b3b4..74afac25e 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/iam/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/iam/errors.go @@ -117,7 +117,8 @@ const ( // "LimitExceeded". // // The request was rejected because it attempted to create resources beyond - // the current AWS account limits. The error message describes the limit exceeded. + // the current AWS account limitations. The error message describes the limit + // exceeded. ErrCodeLimitExceededException = "LimitExceeded" // ErrCodeMalformedCertificateException for service response error code 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 52e87308f..2ccad45a7 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 @@ -14,6 +14,7 @@ import ( "github.com/aws/aws-sdk-go/aws/awsutil" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/private/checksum" "github.com/aws/aws-sdk-go/private/protocol" "github.com/aws/aws-sdk-go/private/protocol/eventstream" "github.com/aws/aws-sdk-go/private/protocol/eventstream/eventstreamapi" @@ -74,23 +75,23 @@ func (c *S3) AbortMultipartUploadRequest(input *AbortMultipartUploadInput) (req // times in order to completely free all storage consumed by all parts. // // To verify that all parts have been removed, so you don't get charged for -// the part storage, you should call the ListParts operation and ensure that -// the parts list is empty. +// the part storage, you should call the ListParts (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListParts.html) +// operation and ensure that the parts list is empty. // // For information about permissions required to use the multipart upload API, // see Multipart Upload API and Permissions (https://docs.aws.amazon.com/AmazonS3/latest/dev/mpuAndPermissions.html). // // The following operations are related to AbortMultipartUpload: // -// * CreateMultipartUpload +// * CreateMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateMultipartUpload.html) // -// * UploadPart +// * UploadPart (https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPart.html) // -// * CompleteMultipartUpload +// * CompleteMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html) // -// * ListParts +// * ListParts (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListParts.html) // -// * ListMultipartUploads +// * ListMultipartUploads (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListMultipartUploads.html) // // 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 @@ -172,14 +173,15 @@ func (c *S3) CompleteMultipartUploadRequest(input *CompleteMultipartUploadInput) // Completes a multipart upload by assembling previously uploaded parts. // // You first initiate the multipart upload and then upload all parts using the -// UploadPart operation. After successfully uploading all relevant parts of -// an upload, you call this operation to complete the upload. Upon receiving -// this request, Amazon S3 concatenates all the parts in ascending order by -// part number to create a new object. In the Complete Multipart Upload request, -// you must provide the parts list. You must ensure that the parts list is complete. -// This operation concatenates the parts that you provide in the list. For each -// part in the list, you must provide the part number and the ETag value, returned -// after that part was uploaded. +// UploadPart (https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPart.html) +// operation. After successfully uploading all relevant parts of an upload, +// you call this operation to complete the upload. Upon receiving this request, +// Amazon S3 concatenates all the parts in ascending order by part number to +// create a new object. In the Complete Multipart Upload request, you must provide +// the parts list. You must ensure that the parts list is complete. This operation +// concatenates the parts that you provide in the list. For each part in the +// list, you must provide the part number and the ETag value, returned after +// that part was uploaded. // // Processing of a Complete Multipart Upload request could take several minutes // to complete. After Amazon S3 begins processing the request, it sends an HTTP @@ -199,7 +201,7 @@ func (c *S3) CompleteMultipartUploadRequest(input *CompleteMultipartUploadInput) // For information about permissions required to use the multipart upload API, // see Multipart Upload API and Permissions (https://docs.aws.amazon.com/AmazonS3/latest/dev/mpuAndPermissions.html). // -// GetBucketLifecycle has the following special errors: +// CompleteMultipartUpload has the following special errors: // // * Error code: EntityTooSmall Description: Your proposed upload is smaller // than the minimum allowed object size. Each part must be at least 5 MB @@ -217,17 +219,17 @@ func (c *S3) CompleteMultipartUploadRequest(input *CompleteMultipartUploadInput) // does not exist. The upload ID might be invalid, or the multipart upload // might have been aborted or completed. 404 Not Found // -// The following operations are related to DeleteBucketMetricsConfiguration: +// The following operations are related to CompleteMultipartUpload: // -// * CreateMultipartUpload +// * CreateMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateMultipartUpload.html) // -// * UploadPart +// * UploadPart (https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPart.html) // -// * AbortMultipartUpload +// * AbortMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_AbortMultipartUpload.html) // -// * ListParts +// * ListParts (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListParts.html) // -// * ListMultipartUploads +// * ListMultipartUploads (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListMultipartUploads.html) // // 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 @@ -305,20 +307,9 @@ func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *request.Request, ou // // You can store individual objects of up to 5 TB in Amazon S3. You create a // copy of your object up to 5 GB in size in a single atomic operation using -// this API. However, for copying an object greater than 5 GB, you must use -// the multipart upload Upload Part - Copy API. For more information, see Copy -// Object Using the REST Multipart Upload API (https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjctsUsingRESTMPUapi.html). -// -// When copying an object, you can preserve all metadata (default) or specify -// new metadata. However, the ACL is not preserved and is set to private for -// the user making the request. To override the default ACL setting, specify -// a new ACL when generating a copy request. For more information, see Using -// ACLs (https://docs.aws.amazon.com/AmazonS3/latest/dev/S3_ACLs_UsingACLs.html). -// -// Amazon S3 transfer acceleration does not support cross-region copies. If -// you request a cross-region copy using a transfer acceleration endpoint, you -// get a 400 Bad Request error. For more information about transfer acceleration, -// see Transfer Acceleration (https://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html). +// this API. However, to copy an object greater than 5 GB, you must use the +// multipart upload Upload Part - Copy API. For more information, see Copy Object +// Using the REST Multipart Upload API (https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjctsUsingRESTMPUapi.html). // // All copy requests must be authenticated. Additionally, you must have read // access to the source object and write access to the destination bucket. For @@ -326,28 +317,6 @@ func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *request.Request, ou // Both the Region that you want to copy the object from and the Region that // you want to copy the object to must be enabled for your account. // -// To only copy an object under certain conditions, such as whether the Etag -// matches or whether the object was modified before or after a specified date, -// use the request parameters x-amz-copy-source-if-match, x-amz-copy-source-if-none-match, -// x-amz-copy-source-if-unmodified-since, or x-amz-copy-source-if-modified-since. -// -// All headers with the x-amz- prefix, including x-amz-copy-source, must be -// signed. -// -// You can use this operation to change the storage class of an object that -// is already stored in Amazon S3 using the StorageClass parameter. For more -// information, see Storage Classes (https://docs.aws.amazon.com/AmazonS3/latest/dev/storage-class-intro.html). -// -// The source object that you are copying can be encrypted or unencrypted. If -// the source object is encrypted, it can be encrypted by server-side encryption -// using AWS managed encryption keys or by using a customer-provided encryption -// key. When copying an object, you can request that Amazon S3 encrypt the target -// object by using either the AWS managed encryption keys or by using your own -// encryption key. You can do this regardless of the form of server-side encryption -// that was used to encrypt the source, or even if the source object was not -// encrypted. For more information about server-side encryption, see Using Server-Side -// Encryption (https://docs.aws.amazon.com/AmazonS3/latest/dev/serv-side-encryption.html). -// // A copy request might return an error when Amazon S3 receives the copy request // or while Amazon S3 is copying the files. If the error occurs before the copy // operation starts, you receive a standard Amazon S3 error. If the error occurs @@ -363,31 +332,104 @@ func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *request.Request, ou // it were not, it would not contain the content-length, and you would need // to read the entire body. // -// Consider the following when using request headers: +// The copy request charge is based on the storage class and Region that you +// specify for the destination object. For pricing information, see Amazon S3 +// pricing (https://aws.amazon.com/s3/pricing/). // -// * Consideration 1 – If both the x-amz-copy-source-if-match and x-amz-copy-source-if-unmodified-since -// headers are present in the request and evaluate as follows, Amazon S3 -// returns 200 OK and copies the data: x-amz-copy-source-if-match condition -// evaluates to true x-amz-copy-source-if-unmodified-since condition evaluates -// to false +// Amazon S3 transfer acceleration does not support cross-Region copies. If +// you request a cross-Region copy using a transfer acceleration endpoint, you +// get a 400 Bad Request error. For more information, see Transfer Acceleration +// (https://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html). // -// * Consideration 2 – If both of the x-amz-copy-source-if-none-match and -// x-amz-copy-source-if-modified-since headers are present in the request -// and evaluate as follows, Amazon S3 returns the 412 Precondition Failed -// response code: x-amz-copy-source-if-none-match condition evaluates to -// false x-amz-copy-source-if-modified-since condition evaluates to true +// Metadata // -// The copy request charge is based on the storage class and Region you specify -// for the destination object. For pricing information, see Amazon S3 Pricing -// (https://aws.amazon.com/s3/pricing/). +// When copying an object, you can preserve all metadata (default) or specify +// new metadata. However, the ACL is not preserved and is set to private for +// the user making the request. To override the default ACL setting, specify +// a new ACL when generating a copy request. For more information, see Using +// ACLs (https://docs.aws.amazon.com/AmazonS3/latest/dev/S3_ACLs_UsingACLs.html). // -// Following are other considerations when using CopyObject: +// To specify whether you want the object metadata copied from the source object +// or replaced with metadata provided in the request, you can optionally add +// the x-amz-metadata-directive header. When you grant permissions, you can +// use the s3:x-amz-metadata-directive condition key to enforce certain metadata +// behavior when objects are uploaded. For more information, see Specifying +// Conditions in a Policy (https://docs.aws.amazon.com/AmazonS3/latest/dev/amazon-s3-policy-keys.html) +// in the Amazon S3 Developer Guide. For a complete list of Amazon S3-specific +// condition keys, see Actions, Resources, and Condition Keys for Amazon S3 +// (https://docs.aws.amazon.com/AmazonS3/latest/dev/list_amazons3.html). +// +// x-amz-copy-source-if Headers +// +// To only copy an object under certain conditions, such as whether the Etag +// matches or whether the object was modified before or after a specified date, +// use the following request parameters: +// +// * x-amz-copy-source-if-match +// +// * x-amz-copy-source-if-none-match +// +// * x-amz-copy-source-if-unmodified-since +// +// * x-amz-copy-source-if-modified-since +// +// If both the x-amz-copy-source-if-match and x-amz-copy-source-if-unmodified-since +// headers are present in the request and evaluate as follows, Amazon S3 returns +// 200 OK and copies the data: +// +// * x-amz-copy-source-if-match condition evaluates to true +// +// * x-amz-copy-source-if-unmodified-since condition evaluates to false +// +// If both the x-amz-copy-source-if-none-match and x-amz-copy-source-if-modified-since +// headers are present in the request and evaluate as follows, Amazon S3 returns +// the 412 Precondition Failed response code: +// +// * x-amz-copy-source-if-none-match condition evaluates to false +// +// * x-amz-copy-source-if-modified-since condition evaluates to true +// +// All headers with the x-amz- prefix, including x-amz-copy-source, must be +// signed. +// +// Encryption +// +// The source object that you are copying can be encrypted or unencrypted. The +// source object can be encrypted with server-side encryption using AWS managed +// encryption keys (SSE-S3 or SSE-KMS) or by using a customer-provided encryption +// key. With server-side encryption, Amazon S3 encrypts your data as it writes +// it to disks in its data centers and decrypts the data when you access it. +// +// You can optionally use the appropriate encryption-related headers to request +// server-side encryption for the target object. You have the option to provide +// your own encryption key or use SSE-S3 or SSE-KMS, regardless of the form +// of server-side encryption that was used to encrypt the source object. You +// can even request encryption if the source object was not encrypted. For more +// information about server-side encryption, see Using Server-Side Encryption +// (https://docs.aws.amazon.com/AmazonS3/latest/dev/serv-side-encryption.html). +// +// Access Control List (ACL)-Specific Request Headers +// +// When copying an object, you can optionally use headers to grant ACL-based +// permissions. By default, all objects are private. Only the owner has full +// access control. When adding a new object, you can grant permissions to individual +// AWS accounts or to predefined groups defined by Amazon S3. These permissions +// are then added to the ACL on the object. For more information, see Access +// Control List (ACL) Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html) +// and Managing ACLs Using the REST API (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-using-rest-api.html). +// +// Storage Class Options +// +// You can use the CopyObject operation to change the storage class of an object +// that is already stored in Amazon S3 using the StorageClass parameter. For +// more information, see Storage Classes (https://docs.aws.amazon.com/AmazonS3/latest/dev/storage-class-intro.html) +// in the Amazon S3 Service Developer Guide. // // Versioning // // By default, x-amz-copy-source identifies the current version of an object -// to copy. (If the current version is a delete marker, Amazon S3 behaves as -// if the object was deleted.) To copy a different version, use the versionId +// to copy. If the current version is a delete marker, Amazon S3 behaves as +// if the object was deleted. To copy a different version, use the versionId // subresource. // // If you enable versioning on the target bucket, Amazon S3 generates a unique @@ -400,94 +442,13 @@ func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *request.Request, ou // // If the source object's storage class is GLACIER, you must restore a copy // of this object before you can use it as a source object for the copy operation. -// For more information, see . -// -// Access Permissions -// -// When copying an object, you can optionally specify the accounts or groups -// that should be granted specific permissions on the new object. There are -// two ways to grant the permissions using the request headers: -// -// * Specify a canned ACL with the x-amz-acl request header. For more information, -// see Canned ACL (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#CannedACL). -// -// * Specify access permissions explicitly with the x-amz-grant-read, x-amz-grant-read-acp, -// x-amz-grant-write-acp, and x-amz-grant-full-control headers. These parameters -// map to the set of permissions that Amazon S3 supports in an ACL. For more -// information, see Access Control List (ACL) Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html). -// -// You can use either a canned ACL or specify access permissions explicitly. -// You cannot do both. -// -// Server-Side- Encryption-Specific Request Headers -// -// To encrypt the target object, you must provide the appropriate encryption-related -// request headers. The one you use depends on whether you want to use AWS managed -// encryption keys or provide your own encryption key. -// -// * To encrypt the target object using server-side encryption with an AWS -// managed encryption key, provide the following request headers, as appropriate. -// x-amz-server-side​-encryption x-amz-server-side-encryption-aws-kms-key-id -// x-amz-server-side-encryption-context If you specify x-amz-server-side-encryption:aws:kms, -// but don't provide x-amz-server-side-encryption-aws-kms-key-id, Amazon -// S3 uses the AWS managed CMK in AWS KMS to protect the data. If you want -// to use a customer managed AWS KMS CMK, you must provide the x-amz-server-side-encryption-aws-kms-key-id -// of the symmetric customer managed CMK. Amazon S3 only supports symmetric -// CMKs and not asymmetric CMKs. For more information, see Using Symmetric -// and Asymmetric Keys (https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html) -// in the AWS Key Management Service Developer Guide. All GET and PUT requests -// for an object protected by AWS KMS fail if you don't make them with SSL -// or by using SigV4. For more information about server-side encryption with -// CMKs stored in AWS KMS (SSE-KMS), see Protecting Data Using Server-Side -// Encryption with CMKs stored in KMS (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html). -// -// * To encrypt the target object using server-side encryption with an encryption -// key that you provide, use the following headers. x-amz-server-side​-encryption​-customer-algorithm -// x-amz-server-side​-encryption​-customer-key x-amz-server-side​-encryption​-customer-key-MD5 -// -// * If the source object is encrypted using server-side encryption with -// customer-provided encryption keys, you must use the following headers. -// x-amz-copy-source​-server-side​-encryption​-customer-algorithm x-amz-copy-source​-server-side​-encryption​-customer-key -// x-amz-copy-source-​server-side​-encryption​-customer-key-MD5 For -// more information about server-side encryption with CMKs stored in AWS -// KMS (SSE-KMS), see Protecting Data Using Server-Side Encryption with CMKs -// stored in Amazon KMS (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html). -// -// Access-Control-List (ACL)-Specific Request Headers -// -// You also can use the following access control–related headers with this -// operation. By default, all objects are private. Only the owner has full access -// control. When adding a new object, you can grant permissions to individual -// AWS accounts or to predefined groups defined by Amazon S3. These permissions -// are then added to the access control list (ACL) on the object. For more information, -// see Using ACLs (https://docs.aws.amazon.com/AmazonS3/latest/dev/S3_ACLs_UsingACLs.html). -// With this operation, you can grant access permissions using one of the following -// two methods: -// -// * Specify a canned ACL (x-amz-acl) — Amazon S3 supports a set of predefined -// ACLs, known as canned ACLs. Each canned ACL has a predefined set of grantees -// and permissions. For more information, see Canned ACL (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#CannedACL). -// -// * Specify access permissions explicitly — To explicitly grant access -// permissions to specific AWS accounts or groups, use the following headers. -// Each header maps to specific permissions that Amazon S3 supports in an -// ACL. For more information, see Access Control List (ACL) Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html). -// In the header, you specify a list of grantees who get the specific permission. -// To grant permissions explicitly, use: x-amz-grant-read x-amz-grant-write -// x-amz-grant-read-acp x-amz-grant-write-acp x-amz-grant-full-control You -// specify each grantee as a type=value pair, where the type is one of the -// following: emailAddress – if the value specified is the email address -// of an AWS account id – if the value specified is the canonical user -// ID of an AWS account uri – if you are granting permissions to a predefined -// group For example, the following x-amz-grant-read header grants the AWS -// accounts identified by email addresses permissions to read object data -// and its metadata: x-amz-grant-read: emailAddress="xyz@amazon.com", emailAddress="abc@amazon.com" +// For more information, see RestoreObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_RestoreObject.html). // // The following operations are related to CopyObject: // -// * PutObject +// * PutObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html) // -// * GetObject +// * GetObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html) // // For more information, see Copying Objects (https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjectsExamples.html). // @@ -581,8 +542,8 @@ func (c *S3) CreateBucketRequest(input *CreateBucketInput) (req *request.Request // can optionally specify a Region in the request body. You might choose a Region // to optimize latency, minimize costs, or address regulatory requirements. // For example, if you reside in Europe, you will probably find it advantageous -// to create buckets in the EU (Ireland) Region. For more information, see How -// to Select a Region for Your Buckets (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html#access-bucket-intro). +// to create buckets in the Europe (Ireland) Region. For more information, see +// How to Select a Region for Your Buckets (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html#access-bucket-intro). // // If you send your create bucket request to the s3.amazonaws.com endpoint, // the request goes to the us-east-1 Region. Accordingly, the signature calculations @@ -608,21 +569,28 @@ func (c *S3) CreateBucketRequest(input *CreateBucketInput) (req *request.Request // in an ACL. For more information, see Access Control List (ACL) Overview // (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html). You // specify each grantee as a type=value pair, where the type is one of the -// following: emailAddress – if the value specified is the email address -// of an AWS account id – if the value specified is the canonical user -// ID of an AWS account uri – if you are granting permissions to a predefined -// group For example, the following x-amz-grant-read header grants the AWS -// accounts identified by email addresses permissions to read object data -// and its metadata: x-amz-grant-read: emailAddress="xyz@amazon.com", emailAddress="abc@amazon.com" +// following: id – if the value specified is the canonical user ID of an +// AWS account uri – if you are granting permissions to a predefined group +// emailAddress – if the value specified is the email address of an AWS +// account Using email addresses to specify a grantee is only supported in +// the following AWS Regions: US East (N. Virginia) US West (N. California) +// US West (Oregon) Asia Pacific (Singapore) Asia Pacific (Sydney) Asia Pacific +// (Tokyo) Europe (Ireland) South America (São Paulo) For a list of all +// the Amazon S3 supported Regions and endpoints, see Regions and Endpoints +// (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) in +// the AWS General Reference. For example, the following x-amz-grant-read +// header grants the AWS accounts identified by account IDs permissions to +// read object data and its metadata: x-amz-grant-read: id="11112222333", +// id="444455556666" // // You can use either a canned ACL or specify access permissions explicitly. // You cannot do both. // // The following operations are related to CreateBucket: // -// * PutObject +// * PutObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html) // -// * DeleteBucket +// * DeleteBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucket.html) // // 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 @@ -712,8 +680,9 @@ func (c *S3) CreateMultipartUploadRequest(input *CreateMultipartUploadInput) (re // This operation initiates a multipart upload and returns an upload ID. This // upload ID is used to associate all of the parts in the specific multipart // upload. You specify this upload ID in each of your subsequent upload part -// requests (see UploadPart). You also include this upload ID in the final request -// to either complete or abort the multipart upload request. +// requests (see UploadPart (https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPart.html)). +// You also include this upload ID in the final request to either complete or +// abort the multipart upload request. // // For more information about multipart uploads, see Multipart Upload Overview // (https://docs.aws.amazon.com/AmazonS3/latest/dev/mpuoverview.html). @@ -746,9 +715,10 @@ func (c *S3) CreateMultipartUploadRequest(input *CreateMultipartUploadInput) (re // and decrypts it when you access it. You can provide your own encryption key, // or use AWS Key Management Service (AWS KMS) customer master keys (CMKs) or // Amazon S3-managed encryption keys. If you choose to provide your own encryption -// key, the request headers you provide in UploadPart) and UploadPartCopy) requests -// must match the headers you used in the request to initiate the upload by -// using CreateMultipartUpload. +// key, the request headers you provide in UploadPart (AmazonS3/latest/API/API_UploadPart.html) +// and UploadPartCopy (https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPartCopy.html) +// requests must match the headers you used in the request to initiate the upload +// by using CreateMultipartUpload. // // To perform a multipart upload with encryption using an AWS KMS CMK, the requester // must have permission to the kms:Encrypt, kms:Decrypt, kms:ReEncrypt*, kms:GenerateDataKey*, @@ -792,7 +762,7 @@ func (c *S3) CreateMultipartUploadRequest(input *CreateMultipartUploadInput) (re // * Use encryption keys managed by Amazon S3 or customer master keys (CMKs) // stored in AWS Key Management Service (AWS KMS) – If you want AWS to // manage the keys used to encrypt data, specify the following headers in -// the request. x-amz-server-side​-encryption x-amz-server-side-encryption-aws-kms-key-id +// the request. x-amz-server-side-encryption x-amz-server-side-encryption-aws-kms-key-id // x-amz-server-side-encryption-context If you specify x-amz-server-side-encryption:aws:kms, // but don't provide x-amz-server-side-encryption-aws-kms-key-id, Amazon // S3 uses the AWS managed CMK in AWS KMS to protect the data. All GET and @@ -803,11 +773,10 @@ func (c *S3) CreateMultipartUploadRequest(input *CreateMultipartUploadInput) (re // // * Use customer-provided encryption keys – If you want to manage your // own encryption keys, provide all the following headers in the request. -// x-amz-server-side​-encryption​-customer-algorithm x-amz-server-side​-encryption​-customer-key -// x-amz-server-side​-encryption​-customer-key-MD5 For more information -// about server-side encryption with CMKs stored in AWS KMS (SSE-KMS), see -// Protecting Data Using Server-Side Encryption with CMKs stored in AWS KMS -// (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html). +// x-amz-server-side-encryption-customer-algorithm x-amz-server-side-encryption-customer-key +// x-amz-server-side-encryption-customer-key-MD5 For more information about +// server-side encryption with CMKs stored in AWS KMS (SSE-KMS), see Protecting +// Data Using Server-Side Encryption with CMKs stored in AWS KMS (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html). // // Access-Control-List (ACL)-Specific Request Headers // @@ -832,24 +801,31 @@ func (c *S3) CreateMultipartUploadRequest(input *CreateMultipartUploadInput) (re // To grant permissions explicitly, use: x-amz-grant-read x-amz-grant-write // x-amz-grant-read-acp x-amz-grant-write-acp x-amz-grant-full-control You // specify each grantee as a type=value pair, where the type is one of the -// following: emailAddress – if the value specified is the email address -// of an AWS account id – if the value specified is the canonical user -// ID of an AWS account uri – if you are granting permissions to a predefined -// group For example, the following x-amz-grant-read header grants the AWS -// accounts identified by email addresses permissions to read object data -// and its metadata: x-amz-grant-read: emailAddress="xyz@amazon.com", emailAddress="abc@amazon.com" +// following: id – if the value specified is the canonical user ID of an +// AWS account uri – if you are granting permissions to a predefined group +// emailAddress – if the value specified is the email address of an AWS +// account Using email addresses to specify a grantee is only supported in +// the following AWS Regions: US East (N. Virginia) US West (N. California) +// US West (Oregon) Asia Pacific (Singapore) Asia Pacific (Sydney) Asia Pacific +// (Tokyo) Europe (Ireland) South America (São Paulo) For a list of all +// the Amazon S3 supported Regions and endpoints, see Regions and Endpoints +// (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) in +// the AWS General Reference. For example, the following x-amz-grant-read +// header grants the AWS accounts identified by account IDs permissions to +// read object data and its metadata: x-amz-grant-read: id="11112222333", +// id="444455556666" // // The following operations are related to CreateMultipartUpload: // -// * UploadPart +// * UploadPart (https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPart.html) // -// * CompleteMultipartUpload +// * CompleteMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html) // -// * AbortMultipartUpload +// * AbortMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_AbortMultipartUpload.html) // -// * ListParts +// * ListParts (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListParts.html) // -// * ListMultipartUploads +// * ListMultipartUploads (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListMultipartUploads.html) // // 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 @@ -929,9 +905,9 @@ func (c *S3) DeleteBucketRequest(input *DeleteBucketInput) (req *request.Request // // Related Resources // -// * +// * CreateBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html) // -// * +// * DeleteObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObject.html) // // 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 @@ -1012,7 +988,7 @@ func (c *S3) DeleteBucketAnalyticsConfigurationRequest(input *DeleteBucketAnalyt // To use this operation, you must have permissions to perform the s3:PutAnalyticsConfiguration // action. The bucket owner has this permission by default. The bucket owner // can grant this permission to others. For more information about permissions, -// see Permissions Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev//using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) +// see Permissions Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) // and Managing Access Permissions to Your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html). // // For information about the Amazon S3 analytics feature, see Amazon S3 Analytics @@ -1020,11 +996,11 @@ func (c *S3) DeleteBucketAnalyticsConfigurationRequest(input *DeleteBucketAnalyt // // The following operations are related to DeleteBucketAnalyticsConfiguration: // -// * +// * GetBucketAnalyticsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketAnalyticsConfiguration.html) // -// * +// * ListBucketAnalyticsConfigurations (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListBucketAnalyticsConfigurations.html) // -// * +// * PutBucketAnalyticsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketAnalyticsConfiguration.html) // // 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 @@ -1110,9 +1086,9 @@ func (c *S3) DeleteBucketCorsRequest(input *DeleteBucketCorsInput) (req *request // // Related Resources: // -// * +// * PutBucketCors (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketCors.html) // -// * RESTOPTIONSobject +// * RESTOPTIONSobject (https://docs.aws.amazon.com/AmazonS3/latest/API/RESTOPTIONSobject.html) // // 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 @@ -1189,21 +1165,21 @@ func (c *S3) DeleteBucketEncryptionRequest(input *DeleteBucketEncryptionInput) ( // // This implementation of the DELETE operation removes default encryption from // the bucket. For information about the Amazon S3 default encryption feature, -// see Amazon S3 Default Bucket Encryption (https://docs.aws.amazon.com/AmazonS3/latest/dev//bucket-encryption.html) +// see Amazon S3 Default Bucket Encryption (https://docs.aws.amazon.com/AmazonS3/latest/dev/bucket-encryption.html) // in the Amazon Simple Storage Service Developer Guide. // // To use this operation, you must have permissions to perform the s3:PutEncryptionConfiguration // action. The bucket owner has this permission by default. The bucket owner // can grant this permission to others. For more information about permissions, -// see Permissions Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev//using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) -// and Managing Access Permissions to your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev//s3-access-control.html) +// see Permissions Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) +// and Managing Access Permissions to your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) // in the Amazon Simple Storage Service Developer Guide. // // Related Resources // -// * PutBucketEncryption +// * PutBucketEncryption (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketEncryption.html) // -// * GetBucketEncryption +// * GetBucketEncryption (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketEncryption.html) // // 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 @@ -1292,11 +1268,11 @@ func (c *S3) DeleteBucketInventoryConfigurationRequest(input *DeleteBucketInvent // // Operations related to DeleteBucketInventoryConfiguration include: // -// * GetBucketInventoryConfiguration +// * GetBucketInventoryConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketInventoryConfiguration.html) // -// * PutBucketInventoryConfiguration +// * PutBucketInventoryConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketInventoryConfiguration.html) // -// * ListBucketInventoryConfigurations +// * ListBucketInventoryConfigurations (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListBucketInventoryConfigurations.html) // // 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 @@ -1389,9 +1365,9 @@ func (c *S3) DeleteBucketLifecycleRequest(input *DeleteBucketLifecycleInput) (re // // Related actions include: // -// * PutBucketLifecycleConfiguration +// * PutBucketLifecycleConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLifecycleConfiguration.html) // -// * GetBucketLifecycleConfiguration +// * GetBucketLifecycleConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketLifecycleConfiguration.html) // // 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 @@ -1481,11 +1457,11 @@ func (c *S3) DeleteBucketMetricsConfigurationRequest(input *DeleteBucketMetricsC // // The following operations are related to DeleteBucketMetricsConfiguration: // -// * GetBucketMetricsConfiguration +// * GetBucketMetricsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketMetricsConfiguration.html) // -// * PutBucketMetricsConfiguration +// * PutBucketMetricsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketMetricsConfiguration.html) // -// * ListBucketMetricsConfigurations +// * ListBucketMetricsConfigurations (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListBucketMetricsConfigurations.html) // // * Monitoring Metrics with Amazon CloudWatch (https://docs.aws.amazon.com/AmazonS3/latest/dev/cloudwatch-monitoring.html) // @@ -1582,9 +1558,9 @@ func (c *S3) DeleteBucketPolicyRequest(input *DeleteBucketPolicyInput) (req *req // // The following operations are related to DeleteBucketPolicy // -// * CreateBucket +// * CreateBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html) // -// * DeleteObject +// * DeleteObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObject.html) // // 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 @@ -1675,9 +1651,9 @@ func (c *S3) DeleteBucketReplicationRequest(input *DeleteBucketReplicationInput) // // The following operations are related to DeleteBucketReplication: // -// * PutBucketReplication +// * PutBucketReplication (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketReplication.html) // -// * GetBucketReplication +// * GetBucketReplication (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketReplication.html) // // 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 @@ -1760,9 +1736,9 @@ func (c *S3) DeleteBucketTaggingRequest(input *DeleteBucketTaggingInput) (req *r // // The following operations are related to DeleteBucketTagging: // -// * GetBucketTagging +// * GetBucketTagging (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketTagging.html) // -// * PutBucketTagging +// * PutBucketTagging (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketTagging.html) // // 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 @@ -1854,9 +1830,9 @@ func (c *S3) DeleteBucketWebsiteRequest(input *DeleteBucketWebsiteInput) (req *r // // The following operations are related to DeleteBucketWebsite: // -// * GetBucketWebsite +// * GetBucketWebsite (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketWebsite.html) // -// * PutBucketWebsite +// * PutBucketWebsite (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketWebsite.html) // // 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 @@ -1948,14 +1924,15 @@ func (c *S3) DeleteObjectRequest(input *DeleteObjectInput) (req *request.Request // To see sample requests that use versioning, see Sample Request (https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectDELETE.html#ExampleVersionObjectDelete). // // You can delete objects by explicitly calling the DELETE Object API or configure -// its lifecycle (PutBucketLifecycle) to enable Amazon S3 to remove them for -// you. If you want to block users or accounts from removing or deleting objects -// from your bucket, you must deny them the s3:DeleteObject, s3:DeleteObjectVersion, -// and s3:PutLifeCycleConfiguration actions. +// its lifecycle (PutBucketLifecycle (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLifecycle.html)) +// to enable Amazon S3 to remove them for you. If you want to block users or +// accounts from removing or deleting objects from your bucket, you must deny +// them the s3:DeleteObject, s3:DeleteObjectVersion, and s3:PutLifeCycleConfiguration +// actions. // // The following operation is related to DeleteObject: // -// * PutObject +// * PutObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html) // // 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 @@ -2041,9 +2018,9 @@ func (c *S3) DeleteObjectTaggingRequest(input *DeleteObjectTaggingInput) (req *r // // The following operations are related to DeleteBucketMetricsConfiguration: // -// * PutObjectTagging +// * PutObjectTagging (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObjectTagging.html) // -// * GetObjectTagging +// * GetObjectTagging (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObjectTagging.html) // // 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 @@ -2112,6 +2089,10 @@ func (c *S3) DeleteObjectsRequest(input *DeleteObjectsInput) (req *request.Reque output = &DeleteObjectsOutput{} req = c.newRequest(op, input, output) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -2150,15 +2131,15 @@ func (c *S3) DeleteObjectsRequest(input *DeleteObjectsInput) (req *request.Reque // // The following operations are related to DeleteObjects: // -// * CreateMultipartUpload +// * CreateMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateMultipartUpload.html) // -// * UploadPart +// * UploadPart (https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPart.html) // -// * CompleteMultipartUpload +// * CompleteMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html) // -// * ListParts +// * ListParts (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListParts.html) // -// * AbortMultipartUpload +// * AbortMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_AbortMultipartUpload.html) // // 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 @@ -2239,15 +2220,15 @@ func (c *S3) DeletePublicAccessBlockRequest(input *DeletePublicAccessBlockInput) // Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) // and Managing Access Permissions to Your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html). // -// The following operations are related to DeleteBucketMetricsConfiguration: +// The following operations are related to DeletePublicAccessBlock: // // * Using Amazon S3 Block Public Access (https://docs.aws.amazon.com/AmazonS3/latest/dev/access-control-block-public-access.html) // -// * GetPublicAccessBlock +// * GetPublicAccessBlock (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetPublicAccessBlock.html) // -// * PutPublicAccessBlock +// * PutPublicAccessBlock (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutPublicAccessBlock.html) // -// * GetBucketPolicyStatus +// * GetBucketPolicyStatus (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketPolicyStatus.html) // // 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 @@ -2329,24 +2310,25 @@ func (c *S3) GetBucketAccelerateConfigurationRequest(input *GetBucketAccelerateC // To use this operation, you must have permission to perform the s3:GetAccelerateConfiguration // action. The bucket owner has this permission by default. The bucket owner // can grant this permission to others. For more information about permissions, -// see Permissions Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev//using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) -// and Managing Access Permissions to your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev//s3-access-control.html) +// see Permissions Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) +// and Managing Access Permissions to your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) // in the Amazon Simple Storage Service Developer Guide. // // You set the Transfer Acceleration state of an existing bucket to Enabled -// or Suspended by using the PutBucketAccelerateConfiguration operation. +// or Suspended by using the PutBucketAccelerateConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketAccelerateConfiguration.html) +// operation. // // A GET accelerate request does not return a state value for a bucket that // has no transfer acceleration state. A bucket has no Transfer Acceleration // state if a state has never been set on the bucket. // // For more information about transfer acceleration, see Transfer Acceleration -// (https://docs.aws.amazon.com/AmazonS3/latest/dev//transfer-acceleration.html) +// (https://docs.aws.amazon.com/AmazonS3/latest/dev/transfer-acceleration.html) // in the Amazon Simple Storage Service Developer Guide. // // Related Resources // -// * PutBucketAccelerateConfiguration +// * PutBucketAccelerateConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketAccelerateConfiguration.html) // // 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 @@ -2428,7 +2410,7 @@ func (c *S3) GetBucketAclRequest(input *GetBucketAclInput) (req *request.Request // // Related Resources // -// * +// * ListObjects (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjects.html) // // 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 @@ -2518,11 +2500,11 @@ func (c *S3) GetBucketAnalyticsConfigurationRequest(input *GetBucketAnalyticsCon // // Related Resources // -// * +// * DeleteBucketAnalyticsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketAnalyticsConfiguration.html) // -// * +// * ListBucketAnalyticsConfigurations (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListBucketAnalyticsConfigurations.html) // -// * +// * PutBucketAnalyticsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketAnalyticsConfiguration.html) // // 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 @@ -2607,9 +2589,9 @@ func (c *S3) GetBucketCorsRequest(input *GetBucketCorsInput) (req *request.Reque // // The following operations are related to GetBucketCors: // -// * PutBucketCors +// * PutBucketCors (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketCors.html) // -// * DeleteBucketCors +// * DeleteBucketCors (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketCors.html) // // 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 @@ -2695,9 +2677,9 @@ func (c *S3) GetBucketEncryptionRequest(input *GetBucketEncryptionInput) (req *r // // The following operations are related to GetBucketEncryption: // -// * PutBucketEncryption +// * PutBucketEncryption (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketEncryption.html) // -// * DeleteBucketEncryption +// * DeleteBucketEncryption (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketEncryption.html) // // 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 @@ -2785,11 +2767,11 @@ func (c *S3) GetBucketInventoryConfigurationRequest(input *GetBucketInventoryCon // // The following operations are related to GetBucketInventoryConfiguration: // -// * DeleteBucketInventoryConfiguration +// * DeleteBucketInventoryConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketInventoryConfiguration.html) // -// * ListBucketInventoryConfigurations +// * ListBucketInventoryConfigurations (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListBucketInventoryConfigurations.html) // -// * PutBucketInventoryConfiguration +// * PutBucketInventoryConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketInventoryConfiguration.html) // // 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 @@ -2869,7 +2851,7 @@ func (c *S3) GetBucketLifecycleRequest(input *GetBucketLifecycleInput) (req *req // GetBucketLifecycle API operation for Amazon Simple Storage Service. // // -// For an updated version of this API, see GetBucketLifecycleConfiguration. +// For an updated version of this API, see GetBucketLifecycleConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketLifecycleConfiguration.html). // If you configured a bucket lifecycle using the filter element, you should // see the updated version of this topic. This topic is provided for backward // compatibility. @@ -2891,11 +2873,11 @@ func (c *S3) GetBucketLifecycleRequest(input *GetBucketLifecycleInput) (req *req // // The following operations are related to GetBucketLifecycle: // -// * GetBucketLifecycleConfiguration +// * GetBucketLifecycleConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketLifecycleConfiguration.html) // -// * PutBucketLifecycle +// * PutBucketLifecycle (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLifecycle.html) // -// * DeleteBucketLifecycle +// * DeleteBucketLifecycle (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketLifecycle.html) // // 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 @@ -2980,7 +2962,7 @@ func (c *S3) GetBucketLifecycleConfigurationRequest(input *GetBucketLifecycleCon // the new filter element that you can use to specify a filter to select a subset // of objects to which the rule applies. If you are still using previous version // of the lifecycle configuration, it works. For the earlier API description, -// see GetBucketLifecycle. +// see GetBucketLifecycle (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketLifecycle.html). // // Returns the lifecycle configuration information set on the bucket. For information // about lifecycle configuration, see Object Lifecycle Management (https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lifecycle-mgmt.html). @@ -2997,13 +2979,13 @@ func (c *S3) GetBucketLifecycleConfigurationRequest(input *GetBucketLifecycleCon // configuration does not exist. HTTP Status Code: 404 Not Found SOAP Fault // Code Prefix: Client // -// The following operations are related to DeleteBucketMetricsConfiguration: +// The following operations are related to GetBucketLifecycleConfiguration: // -// * GetBucketLifecycle +// * GetBucketLifecycle (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketLifecycle.html) // -// * PutBucketLifecycle +// * PutBucketLifecycle (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLifecycle.html) // -// * DeleteBucketLifecycle +// * DeleteBucketLifecycle (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketLifecycle.html) // // 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 @@ -3079,15 +3061,15 @@ func (c *S3) GetBucketLocationRequest(input *GetBucketLocationInput) (req *reque // // Returns the Region the bucket resides in. You set the bucket's Region using // the LocationConstraint request parameter in a CreateBucket request. For more -// information, see CreateBucket. +// information, see CreateBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html). // // To use this implementation of the operation, you must be the bucket owner. // // The following operations are related to GetBucketLocation: // -// * GetObject +// * GetObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html) // -// * CreateBucket +// * CreateBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html) // // 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 @@ -3166,9 +3148,9 @@ func (c *S3) GetBucketLoggingRequest(input *GetBucketLoggingInput) (req *request // // The following operations are related to GetBucketLogging: // -// * CreateBucket +// * CreateBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html) // -// * PutBucketLogging +// * PutBucketLogging (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLogging.html) // // 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 @@ -3256,11 +3238,11 @@ func (c *S3) GetBucketMetricsConfigurationRequest(input *GetBucketMetricsConfigu // // The following operations are related to GetBucketMetricsConfiguration: // -// * PutBucketMetricsConfiguration +// * PutBucketMetricsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketMetricsConfiguration.html) // -// * DeleteBucketMetricsConfiguration +// * DeleteBucketMetricsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketMetricsConfiguration.html) // -// * ListBucketMetricsConfigurations +// * ListBucketMetricsConfigurations (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListBucketMetricsConfigurations.html) // // * Monitoring Metrics with Amazon CloudWatch (https://docs.aws.amazon.com/AmazonS3/latest/dev/cloudwatch-monitoring.html) // @@ -3341,7 +3323,7 @@ func (c *S3) GetBucketNotificationRequest(input *GetBucketNotificationConfigurat // GetBucketNotification API operation for Amazon Simple Storage Service. // -// No longer used, see GetBucketNotificationConfiguration. +// No longer used, see GetBucketNotificationConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketNotificationConfiguration.html). // // 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 @@ -3435,7 +3417,7 @@ func (c *S3) GetBucketNotificationConfigurationRequest(input *GetBucketNotificat // // The following operation is related to GetBucketNotification: // -// * PutBucketNotification +// * PutBucketNotification (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketNotification.html) // // 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 @@ -3528,7 +3510,7 @@ func (c *S3) GetBucketPolicyRequest(input *GetBucketPolicyInput) (req *request.R // // The following operation is related to GetBucketPolicy: // -// * GetObject +// * GetObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html) // // 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 @@ -3614,11 +3596,11 @@ func (c *S3) GetBucketPolicyStatusRequest(input *GetBucketPolicyStatusInput) (re // // * Using Amazon S3 Block Public Access (https://docs.aws.amazon.com/AmazonS3/latest/dev/access-control-block-public-access.html) // -// * GetPublicAccessBlock +// * GetPublicAccessBlock (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetPublicAccessBlock.html) // -// * PutPublicAccessBlock +// * PutPublicAccessBlock (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutPublicAccessBlock.html) // -// * DeletePublicAccessBlock +// * DeletePublicAccessBlock (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeletePublicAccessBlock.html) // // 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 @@ -3709,13 +3691,14 @@ func (c *S3) GetBucketReplicationRequest(input *GetBucketReplicationInput) (req // also include the DeleteMarkerReplication and Priority elements. The response // also returns those elements. // -// For information about GetBucketReplication errors, see ReplicationErrorCodeList +// For information about GetBucketReplication errors, see List of replication-related +// error codes (https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html#ReplicationErrorCodeList) // // The following operations are related to GetBucketReplication: // -// * PutBucketReplication +// * PutBucketReplication (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketReplication.html) // -// * DeleteBucketReplication +// * DeleteBucketReplication (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketReplication.html) // // 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 @@ -3795,7 +3778,7 @@ func (c *S3) GetBucketRequestPaymentRequest(input *GetBucketRequestPaymentInput) // // The following operations are related to GetBucketRequestPayment: // -// * ListObjects +// * ListObjects (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjects.html) // // 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 @@ -3882,9 +3865,9 @@ func (c *S3) GetBucketTaggingRequest(input *GetBucketTaggingInput) (req *request // // The following operations are related to GetBucketTagging: // -// * PutBucketTagging +// * PutBucketTagging (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketTagging.html) // -// * DeleteBucketTagging +// * DeleteBucketTagging (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketTagging.html) // // 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 @@ -3968,11 +3951,11 @@ func (c *S3) GetBucketVersioningRequest(input *GetBucketVersioningInput) (req *r // // The following operations are related to GetBucketVersioning: // -// * GetObject +// * GetObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html) // -// * PutObject +// * PutObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html) // -// * DeleteObject +// * DeleteObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObject.html) // // 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 @@ -4058,9 +4041,9 @@ func (c *S3) GetBucketWebsiteRequest(input *GetBucketWebsiteInput) (req *request // // The following operations are related to DeleteBucketWebsite: // -// * DeleteBucketWebsite +// * DeleteBucketWebsite (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketWebsite.html) // -// * PutBucketWebsite +// * PutBucketWebsite (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketWebsite.html) // // 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 @@ -4154,13 +4137,14 @@ func (c *S3) GetObjectRequest(input *GetObjectInput) (req *request.Request, outp // // To distribute large files to many people, you can save bandwidth costs by // using BitTorrent. For more information, see Amazon S3 Torrent (https://docs.aws.amazon.com/AmazonS3/latest/dev/S3Torrent.html). -// For more information about returning the ACL of an object, see GetObjectAcl. +// For more information about returning the ACL of an object, see GetObjectAcl +// (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObjectAcl.html). // // If the object you are retrieving is stored in the GLACIER or DEEP_ARCHIVE // storage classes, before you can retrieve the object you must first restore -// a copy using . Otherwise, this operation returns an InvalidObjectStateError -// error. For information about restoring archived objects, see Restoring Archived -// Objects (https://docs.aws.amazon.com/AmazonS3/latest/dev/restoring-objects.html). +// a copy using RestoreObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_RestoreObject.html). +// Otherwise, this operation returns an InvalidObjectStateError error. For information +// about restoring archived objects, see Restoring Archived Objects (https://docs.aws.amazon.com/AmazonS3/latest/dev/restoring-objects.html). // // Encryption request headers, like x-amz-server-side-encryption, should not // be sent for GET requests if your object uses server-side encryption with @@ -4172,11 +4156,11 @@ func (c *S3) GetObjectRequest(input *GetObjectInput) (req *request.Request, outp // encryption keys (SSE-C) when you store the object in Amazon S3, then when // you GET the object, you must use the following headers: // -// * x-amz-server-side​-encryption​-customer-algorithm +// * x-amz-server-side-encryption-customer-algorithm // -// * x-amz-server-side​-encryption​-customer-key +// * x-amz-server-side-encryption-customer-key // -// * x-amz-server-side​-encryption​-customer-key-MD5 +// * x-amz-server-side-encryption-customer-key-MD5 // // For more information about SSE-C, see Server-Side Encryption (Using Customer-Provided // Encryption Keys) (https://docs.aws.amazon.com/AmazonS3/latest/dev/ServerSideEncryptionCustomerKeys.html). @@ -4184,6 +4168,7 @@ func (c *S3) GetObjectRequest(input *GetObjectInput) (req *request.Request, outp // Assuming you have permission to read object tags (permission for the s3:GetObjectVersionTagging // action), the response also returns the x-amz-tagging-count header that provides // the count of number of tags associated with the object. You can use GetObjectTagging +// (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObjectTagging.html) // to retrieve the tag set associated with an object. // // Permissions @@ -4208,7 +4193,7 @@ func (c *S3) GetObjectRequest(input *GetObjectInput) (req *request.Request, outp // as if the object was deleted and includes x-amz-delete-marker: true in the // response. // -// For more information about versioning, see PutBucketVersioning. +// For more information about versioning, see PutBucketVersioning (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketVersioning.html). // // Overriding Response Header Values // @@ -4255,9 +4240,9 @@ func (c *S3) GetObjectRequest(input *GetObjectInput) (req *request.Request, outp // // The following operations are related to GetObject: // -// * ListBuckets +// * ListBuckets (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListBuckets.html) // -// * GetObjectAcl +// * GetObjectAcl (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObjectAcl.html) // // 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 @@ -4346,11 +4331,11 @@ func (c *S3) GetObjectAclRequest(input *GetObjectAclInput) (req *request.Request // // The following operations are related to GetObjectAcl: // -// * GetObject +// * GetObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html) // -// * DeleteObject +// * DeleteObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObject.html) // -// * PutObject +// * PutObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html) // // 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 @@ -4674,7 +4659,7 @@ func (c *S3) GetObjectTaggingRequest(input *GetObjectTaggingInput) (req *request // // The following operation is related to GetObjectTagging: // -// * PutObjectTagging +// * PutObjectTagging (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObjectTagging.html) // // 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 @@ -4760,7 +4745,7 @@ func (c *S3) GetObjectTorrentRequest(input *GetObjectTorrentInput) (req *request // // The following operation is related to GetObjectTorrent: // -// * GetObject +// * GetObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html) // // 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 @@ -4853,11 +4838,11 @@ func (c *S3) GetPublicAccessBlockRequest(input *GetPublicAccessBlockInput) (req // // * Using Amazon S3 Block Public Access (https://docs.aws.amazon.com/AmazonS3/latest/dev/access-control-block-public-access.html) // -// * PutPublicAccessBlock +// * PutPublicAccessBlock (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutPublicAccessBlock.html) // -// * GetPublicAccessBlock +// * GetPublicAccessBlock (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetPublicAccessBlock.html) // -// * DeletePublicAccessBlock +// * DeletePublicAccessBlock (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeletePublicAccessBlock.html) // // 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 @@ -5032,11 +5017,11 @@ func (c *S3) HeadObjectRequest(input *HeadObjectInput) (req *request.Request, ou // encryption keys (SSE-C) when you store the object in Amazon S3, then when // you retrieve the metadata from the object, you must use the following headers: // -// * x-amz-server-side​-encryption​-customer-algorithm +// * x-amz-server-side-encryption-customer-algorithm // -// * x-amz-server-side​-encryption​-customer-key +// * x-amz-server-side-encryption-customer-key // -// * x-amz-server-side​-encryption​-customer-key-MD5 +// * x-amz-server-side-encryption-customer-key-MD5 // // For more information about SSE-C, see Server-Side Encryption (Using Customer-Provided // Encryption Keys) (https://docs.aws.amazon.com/AmazonS3/latest/dev/ServerSideEncryptionCustomerKeys.html). @@ -5079,7 +5064,7 @@ func (c *S3) HeadObjectRequest(input *HeadObjectInput) (req *request.Request, ou // // The following operation is related to HeadObject: // -// * GetObject +// * GetObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html) // // See http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html#RESTErrorResponses // for more information on returned errors. @@ -5178,11 +5163,11 @@ func (c *S3) ListBucketAnalyticsConfigurationsRequest(input *ListBucketAnalytics // // The following operations are related to ListBucketAnalyticsConfigurations: // -// * GetBucketAnalyticsConfiguration +// * GetBucketAnalyticsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketAnalyticsConfiguration.html) // -// * DeleteBucketAnalyticsConfiguration +// * DeleteBucketAnalyticsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketAnalyticsConfiguration.html) // -// * PutBucketAnalyticsConfiguration +// * PutBucketAnalyticsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketAnalyticsConfiguration.html) // // 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 @@ -5278,11 +5263,11 @@ func (c *S3) ListBucketInventoryConfigurationsRequest(input *ListBucketInventory // // The following operations are related to ListBucketInventoryConfigurations: // -// * GetBucketInventoryConfiguration +// * GetBucketInventoryConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketInventoryConfiguration.html) // -// * DeleteBucketInventoryConfiguration +// * DeleteBucketInventoryConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketInventoryConfiguration.html) // -// * PutBucketInventoryConfiguration +// * PutBucketInventoryConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketInventoryConfiguration.html) // // 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 @@ -5379,11 +5364,11 @@ func (c *S3) ListBucketMetricsConfigurationsRequest(input *ListBucketMetricsConf // // The following operations are related to ListBucketMetricsConfigurations: // -// * PutBucketMetricsConfiguration +// * PutBucketMetricsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketMetricsConfiguration.html) // -// * GetBucketMetricsConfiguration +// * GetBucketMetricsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketMetricsConfiguration.html) // -// * DeleteBucketMetricsConfiguration +// * DeleteBucketMetricsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketMetricsConfiguration.html) // // 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 @@ -5562,15 +5547,15 @@ func (c *S3) ListMultipartUploadsRequest(input *ListMultipartUploadsInput) (req // // The following operations are related to ListMultipartUploads: // -// * CreateMultipartUpload +// * CreateMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateMultipartUpload.html) // -// * UploadPart +// * UploadPart (https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPart.html) // -// * CompleteMultipartUpload +// * CompleteMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html) // -// * ListParts +// * ListParts (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListParts.html) // -// * AbortMultipartUpload +// * AbortMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_AbortMultipartUpload.html) // // 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 @@ -5713,13 +5698,13 @@ func (c *S3) ListObjectVersionsRequest(input *ListObjectVersionsInput) (req *req // // The following operations are related to ListObjectVersions: // -// * ListObjectsV2 +// * ListObjectsV2 (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html) // -// * GetObject +// * GetObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html) // -// * PutObject +// * PutObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html) // -// * DeleteObject +// * DeleteObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObject.html) // // 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 @@ -5857,21 +5842,22 @@ func (c *S3) ListObjectsRequest(input *ListObjectsInput) (req *request.Request, // to design your application to parse the contents of the response and handle // it appropriately. // -// This API has been revised. We recommend that you use the newer version, ListObjectsV2, +// This API has been revised. We recommend that you use the newer version, ListObjectsV2 +// (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html), // when developing applications. For backward compatibility, Amazon S3 continues // to support ListObjects. // // The following operations are related to ListObjects: // -// * ListObjectsV2 +// * ListObjectsV2 (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html) // -// * GetObject +// * GetObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html) // -// * PutObject +// * PutObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html) // -// * CreateBucket +// * CreateBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html) // -// * ListBuckets +// * ListBuckets (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListBuckets.html) // // 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 @@ -6025,17 +6011,18 @@ func (c *S3) ListObjectsV2Request(input *ListObjectsV2Input) (req *request.Reque // // This section describes the latest revision of the API. We recommend that // you use this revised API for application development. For backward compatibility, -// Amazon S3 continues to support the prior version of this API, ListObjects. +// Amazon S3 continues to support the prior version of this API, ListObjects +// (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjects.html). // -// To get a list of your buckets, see ListBuckets. +// To get a list of your buckets, see ListBuckets (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListBuckets.html). // // The following operations are related to ListObjectsV2: // -// * GetObject +// * GetObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html) // -// * PutObject +// * PutObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html) // -// * CreateBucket +// * CreateBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html) // // 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 @@ -6174,14 +6161,14 @@ func (c *S3) ListPartsRequest(input *ListPartsInput) (req *request.Request, outp // // Lists the parts that have been uploaded for a specific multipart upload. // This operation must include the upload ID, which you obtain by sending the -// initiate multipart upload request (see CreateMultipartUpload). This request -// returns a maximum of 1,000 uploaded parts. The default number of parts returned -// is 1,000 parts. You can restrict the number of parts returned by specifying -// the max-parts request parameter. If your multipart upload consists of more -// than 1,000 parts, the response returns an IsTruncated field with the value -// of true, and a NextPartNumberMarker element. In subsequent ListParts requests -// you can include the part-number-marker query string parameter and set its -// value to the NextPartNumberMarker field value from the previous response. +// initiate multipart upload request (see CreateMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateMultipartUpload.html)). +// This request returns a maximum of 1,000 uploaded parts. The default number +// of parts returned is 1,000 parts. You can restrict the number of parts returned +// by specifying the max-parts request parameter. If your multipart upload consists +// of more than 1,000 parts, the response returns an IsTruncated field with +// the value of true, and a NextPartNumberMarker element. In subsequent ListParts +// requests you can include the part-number-marker query string parameter and +// set its value to the NextPartNumberMarker field value from the previous response. // // For more information on multipart uploads, see Uploading Objects Using Multipart // Upload (https://docs.aws.amazon.com/AmazonS3/latest/dev/uploadobjusingmpu.html). @@ -6191,15 +6178,15 @@ func (c *S3) ListPartsRequest(input *ListPartsInput) (req *request.Request, outp // // The following operations are related to ListParts: // -// * CreateMultipartUpload +// * CreateMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateMultipartUpload.html) // -// * UploadPart +// * UploadPart (https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPart.html) // -// * CompleteMultipartUpload +// * CompleteMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html) // -// * AbortMultipartUpload +// * AbortMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_AbortMultipartUpload.html) // -// * ListMultipartUploads +// * ListMultipartUploads (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListMultipartUploads.html) // // 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 @@ -6343,8 +6330,8 @@ func (c *S3) PutBucketAccelerateConfigurationRequest(input *PutBucketAccelerateC // // * Suspended – Disables accelerated data transfers to the bucket. // -// The GetBucketAccelerateConfiguration operation returns the transfer acceleration -// state of a bucket. +// The GetBucketAccelerateConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketAccelerateConfiguration.html) +// operation returns the transfer acceleration state of a bucket. // // After setting the Transfer Acceleration state of a bucket to Enabled, it // might take up to thirty minutes before the data transfer rates to the bucket @@ -6358,9 +6345,9 @@ func (c *S3) PutBucketAccelerateConfigurationRequest(input *PutBucketAccelerateC // // The following operations are related to PutBucketAccelerateConfiguration: // -// * GetBucketAccelerateConfiguration +// * GetBucketAccelerateConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketAccelerateConfiguration.html) // -// * CreateBucket +// * CreateBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html) // // 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 @@ -6430,6 +6417,10 @@ func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *request.Request output = &PutBucketAclOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -6473,14 +6464,20 @@ func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *request.Request // Amazon S3 supports in an ACL. For more information, see Access Control // List (ACL) Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html). // You specify each grantee as a type=value pair, where the type is one of -// the following: emailAddress – if the value specified is the email address -// of an AWS account id – if the value specified is the canonical user -// ID of an AWS account uri – if you are granting permissions to a predefined -// group For example, the following x-amz-grant-write header grants create, -// overwrite, and delete objects permission to LogDelivery group predefined -// by Amazon S3 and two AWS accounts identified by their email addresses. -// x-amz-grant-write: uri="http://acs.amazonaws.com/groups/s3/LogDelivery", -// emailAddress="xyz@amazon.com", emailAddress="abc@amazon.com" +// the following: id – if the value specified is the canonical user ID +// of an AWS account uri – if you are granting permissions to a predefined +// group emailAddress – if the value specified is the email address of +// an AWS account Using email addresses to specify a grantee is only supported +// in the following AWS Regions: US East (N. Virginia) US West (N. California) +// US West (Oregon) Asia Pacific (Singapore) Asia Pacific (Sydney) Asia Pacific +// (Tokyo) Europe (Ireland) South America (São Paulo) For a list of all +// the Amazon S3 supported Regions and endpoints, see Regions and Endpoints +// (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) in +// the AWS General Reference. For example, the following x-amz-grant-write +// header grants create, overwrite, and delete objects permission to LogDelivery +// group predefined by Amazon S3 and two AWS accounts identified by their +// email addresses. x-amz-grant-write: uri="http://acs.amazonaws.com/groups/s3/LogDelivery", +// id="111122223333", id="555566667777" // // You can use either a canned ACL or specify access permissions explicitly. // You cannot do both. @@ -6490,11 +6487,6 @@ func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *request.Request // You can specify the person (grantee) to whom you're assigning access rights // (using request elements) in the following ways: // -// * By Email address: <>Grantees@email.com<>lt;/Grantee> -// The grantee is resolved to the CanonicalUser and, in a response to a GET -// Object acl request, appears as the CanonicalUser. -// // * By the person's ID: <>ID<><>GranteesEmail<> // DisplayName is optional and ignored in the request @@ -6502,13 +6494,24 @@ func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *request.Request // * By URI: <>http://acs.amazonaws.com/groups/global/AuthenticatedUsers<> // +// * By Email address: <>Grantees@email.com<>lt;/Grantee> +// The grantee is resolved to the CanonicalUser and, in a response to a GET +// Object acl request, appears as the CanonicalUser. Using email addresses +// to specify a grantee is only supported in the following AWS Regions: US +// East (N. Virginia) US West (N. California) US West (Oregon) Asia Pacific +// (Singapore) Asia Pacific (Sydney) Asia Pacific (Tokyo) Europe (Ireland) +// South America (São Paulo) For a list of all the Amazon S3 supported Regions +// and endpoints, see Regions and Endpoints (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) +// in the AWS General Reference. +// // Related Resources // -// * CreateBucket +// * CreateBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html) // -// * DeleteBucket +// * DeleteBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucket.html) // -// * GetObjectAcl +// * GetObjectAcl (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObjectAcl.html) // // 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 @@ -6623,11 +6626,11 @@ func (c *S3) PutBucketAnalyticsConfigurationRequest(input *PutBucketAnalyticsCon // // Related Resources // -// * +// * GetBucketAnalyticsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketAnalyticsConfiguration.html) // -// * +// * DeleteBucketAnalyticsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketAnalyticsConfiguration.html) // -// * +// * ListBucketAnalyticsConfigurations (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListBucketAnalyticsConfigurations.html) // // 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 @@ -6697,6 +6700,10 @@ func (c *S3) PutBucketCorsRequest(input *PutBucketCorsInput) (req *request.Reque output = &PutBucketCorsOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -6740,11 +6747,11 @@ func (c *S3) PutBucketCorsRequest(input *PutBucketCorsInput) (req *request.Reque // // Related Resources // -// * GetBucketCors +// * GetBucketCors (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketCors.html) // -// * DeleteBucketCors +// * DeleteBucketCors (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketCors.html) // -// * RESTOPTIONSobject +// * RESTOPTIONSobject (https://docs.aws.amazon.com/AmazonS3/latest/API/RESTOPTIONSobject.html) // // 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 @@ -6814,6 +6821,10 @@ func (c *S3) PutBucketEncryptionRequest(input *PutBucketEncryptionInput) (req *r output = &PutBucketEncryptionOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -6824,7 +6835,8 @@ func (c *S3) PutBucketEncryptionRequest(input *PutBucketEncryptionInput) (req *r // // This implementation of the PUT operation sets default encryption for a bucket // using server-side encryption with Amazon S3-managed keys SSE-S3 or AWS KMS -// customer master keys (CMKs) (SSE-KMS). +// customer master keys (CMKs) (SSE-KMS). For information about the Amazon S3 +// default encryption feature, see Amazon S3 Default Bucket Encryption (https://docs.aws.amazon.com/AmazonS3/latest/dev/bucket-encryption.html). // // This operation requires AWS Signature Version 4. For more information, see // Authenticating Requests (AWS Signature Version 4) (sig-v4-authenticating-requests.html). @@ -6838,9 +6850,9 @@ func (c *S3) PutBucketEncryptionRequest(input *PutBucketEncryptionInput) (req *r // // Related Resources // -// * GetBucketEncryption +// * GetBucketEncryption (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketEncryption.html) // -// * DeleteBucketEncryption +// * DeleteBucketEncryption (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketEncryption.html) // // 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 @@ -6929,19 +6941,19 @@ func (c *S3) PutBucketInventoryConfigurationRequest(input *PutBucketInventoryCon // bucket where you want the inventory to be stored, and whether to generate // the inventory daily or weekly. You can also configure what object metadata // to include and whether to inventory all object versions or only current versions. -// For more information, see Amazon S3 Inventory (https://docs.aws.amazon.com/AmazonS3/latest/dev//storage-inventory.html) +// For more information, see Amazon S3 Inventory (https://docs.aws.amazon.com/AmazonS3/latest/dev/storage-inventory.html) // in the Amazon Simple Storage Service Developer Guide. // // You must create a bucket policy on the destination bucket to grant permissions // to Amazon S3 to write objects to the bucket in the defined location. For // an example policy, see Granting Permissions for Amazon S3 Inventory and Storage -// Class Analysis. (https://docs.aws.amazon.com/AmazonS3/latest/dev/example-bucket-policies.html#example-bucket-policies-use-case-9) +// Class Analysis (https://docs.aws.amazon.com/AmazonS3/latest/dev/example-bucket-policies.html#example-bucket-policies-use-case-9). // // To use this operation, you must have permissions to perform the s3:PutInventoryConfiguration // action. The bucket owner has this permission by default and can grant this // permission to others. For more information about permissions, see Permissions -// Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev//using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) -// and Managing Access Permissions to Your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev//s3-access-control.html) +// Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) +// and Managing Access Permissions to Your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) // in the Amazon Simple Storage Service Developer Guide. // // Special Errors @@ -6954,15 +6966,15 @@ func (c *S3) PutBucketInventoryConfigurationRequest(input *PutBucketInventoryCon // // * HTTP 403 Forbidden Error Code: AccessDenied Cause: You are not the owner // of the specified bucket, or you do not have the s3:PutInventoryConfiguration -// bucket permission to set the configuration on the bucket +// bucket permission to set the configuration on the bucket. // // Related Resources // -// * GetBucketInventoryConfiguration +// * GetBucketInventoryConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketInventoryConfiguration.html) // -// * DeleteBucketInventoryConfiguration +// * DeleteBucketInventoryConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketInventoryConfiguration.html) // -// * ListBucketInventoryConfigurations +// * ListBucketInventoryConfigurations (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListBucketInventoryConfigurations.html) // // 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 @@ -7037,19 +7049,23 @@ func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *req output = &PutBucketLifecycleOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } // PutBucketLifecycle API operation for Amazon Simple Storage Service. // // -// For an updated version of this API, see PutBucketLifecycleConfiguration. +// For an updated version of this API, see PutBucketLifecycleConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLifecycleConfiguration.html). // This version has been deprecated. Existing lifecycle configurations will // work. For new lifecycle configurations, use the updated API. // // Creates a new lifecycle configuration for the bucket or replaces an existing // lifecycle configuration. For information about lifecycle configuration, see -// Object Lifecycle Management (https://docs.aws.amazon.com/AmazonS3/latest/dev//object-lifecycle-mgmt.html) +// Object Lifecycle Management (https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lifecycle-mgmt.html) // in the Amazon Simple Storage Service Developer Guide. // // By default, all Amazon S3 resources, including buckets, objects, and related @@ -7071,26 +7087,26 @@ func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *req // * s3:PutLifecycleConfiguration // // For more information about permissions, see Managing Access Permissions to -// your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev//s3-access-control.html) +// your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) // in the Amazon Simple Storage Service Developer Guide. // // For more examples of transitioning objects to storage classes such as STANDARD_IA -// or ONEZONE_IA, see Examples of Lifecycle Configuration (https://docs.aws.amazon.com/AmazonS3/latest/dev//intro-lifecycle-rules.html#lifecycle-configuration-examples). +// or ONEZONE_IA, see Examples of Lifecycle Configuration (https://docs.aws.amazon.com/AmazonS3/latest/dev/intro-lifecycle-rules.html#lifecycle-configuration-examples). // // Related Resources // -// * GetBucketLifecycle(Deprecated) +// * GetBucketLifecycle (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketLifecycle.html)(Deprecated) // -// * GetBucketLifecycleConfiguration +// * GetBucketLifecycleConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketLifecycleConfiguration.html) // -// * +// * RestoreObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_RestoreObject.html) // // * By default, a resource owner—in this case, a bucket owner, which is // the AWS account that created the bucket—can perform any of the operations. // A resource owner can also grant others permission to perform the operation. // For more information, see the following topics in the Amazon Simple Storage -// Service Developer Guide: Specifying Permissions in a Policy (https://docs.aws.amazon.com/AmazonS3/latest/dev//using-with-s3-actions.html) -// Managing Access Permissions to your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev//s3-access-control.html) +// Service Developer Guide: Specifying Permissions in a Policy (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html) +// Managing Access Permissions to your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) // // 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 @@ -7164,6 +7180,10 @@ func (c *S3) PutBucketLifecycleConfigurationRequest(input *PutBucketLifecycleCon output = &PutBucketLifecycleConfigurationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -7178,7 +7198,7 @@ func (c *S3) PutBucketLifecycleConfigurationRequest(input *PutBucketLifecycleCon // Accordingly, this section describes the latest API. The previous version // of the API supported filtering based only on an object key name prefix, which // is supported for backward compatibility. For the related API description, -// see PutBucketLifecycle. +// see PutBucketLifecycle (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLifecycle.html). // // Rules // @@ -7229,9 +7249,9 @@ func (c *S3) PutBucketLifecycleConfigurationRequest(input *PutBucketLifecycleCon // // * Examples of Lifecycle Configuration (https://docs.aws.amazon.com/AmazonS3/latest/dev/lifecycle-configuration-examples.html) // -// * GetBucketLifecycleConfiguration +// * GetBucketLifecycleConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketLifecycleConfiguration.html) // -// * DeleteBucketLifecycle +// * DeleteBucketLifecycle (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketLifecycle.html) // // 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 @@ -7301,6 +7321,10 @@ func (c *S3) PutBucketLoggingRequest(input *PutBucketLoggingInput) (req *request output = &PutBucketLoggingOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -7340,18 +7364,19 @@ func (c *S3) PutBucketLoggingRequest(input *PutBucketLoggingInput) (req *request // For more information about server access logging, see Server Access Logging // (https://docs.aws.amazon.com/AmazonS3/latest/dev/ServerLogs.html). // -// For more information about creating a bucket, see CreateBucket. For more -// information about returning the logging status of a bucket, see GetBucketLogging. +// For more information about creating a bucket, see CreateBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html). +// For more information about returning the logging status of a bucket, see +// GetBucketLogging (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketLogging.html). // // The following operations are related to PutBucketLogging: // -// * PutObject +// * PutObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html) // -// * DeleteBucket +// * DeleteBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucket.html) // -// * CreateBucket +// * CreateBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html) // -// * GetBucketLogging +// * GetBucketLogging (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketLogging.html) // // 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 @@ -7443,11 +7468,11 @@ func (c *S3) PutBucketMetricsConfigurationRequest(input *PutBucketMetricsConfigu // // The following operations are related to PutBucketMetricsConfiguration: // -// * DeleteBucketMetricsConfiguration +// * DeleteBucketMetricsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketMetricsConfiguration.html) // -// * PutBucketMetricsConfiguration +// * PutBucketMetricsConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketMetricsConfiguration.html) // -// * ListBucketMetricsConfigurations +// * ListBucketMetricsConfigurations (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListBucketMetricsConfigurations.html) // // GetBucketLifecycle has the following special error: // @@ -7528,12 +7553,17 @@ func (c *S3) PutBucketNotificationRequest(input *PutBucketNotificationInput) (re output = &PutBucketNotificationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } // PutBucketNotification API operation for Amazon Simple Storage Service. // -// No longer used, see the PutBucketNotificationConfiguration operation. +// No longer used, see the PutBucketNotificationConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketNotificationConfiguration.html) +// operation. // // 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 @@ -7660,7 +7690,7 @@ func (c *S3) PutBucketNotificationConfigurationRequest(input *PutBucketNotificat // // The following operation is related to PutBucketNotificationConfiguration: // -// * GetBucketNotificationConfiguration +// * GetBucketNotificationConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketNotificationConfiguration.html) // // 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 @@ -7730,6 +7760,10 @@ func (c *S3) PutBucketPolicyRequest(input *PutBucketPolicyInput) (req *request.R output = &PutBucketPolicyOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -7754,9 +7788,9 @@ func (c *S3) PutBucketPolicyRequest(input *PutBucketPolicyInput) (req *request.R // // The following operations are related to PutBucketPolicy: // -// * CreateBucket +// * CreateBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html) // -// * DeleteBucket +// * DeleteBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucket.html) // // 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 @@ -7826,6 +7860,10 @@ func (c *S3) PutBucketReplicationRequest(input *PutBucketReplicationInput) (req output = &PutBucketReplicationOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -7856,6 +7894,13 @@ func (c *S3) PutBucketReplicationRequest(input *PutBucketReplicationInput) (req // When you add the Filter element in the configuration, you must also add the // following elements: DeleteMarkerReplication, Status, and Priority. // +// The latest version of the replication configuration XML is V2. XML V2 replication +// configurations are those that contain the Filter element for rules, and rules +// that specify S3 Replication Time Control (S3 RTC). In XML V2 replication +// configurations, Amazon S3 doesn't replicate delete markers. Therefore, you +// must set the DeleteMarkerReplication element to Disabled. For backward compatibility, +// Amazon S3 continues to support the XML V1 replication configuration. +// // For information about enabling versioning on a bucket, see Using Versioning // (https://docs.aws.amazon.com/AmazonS3/latest/dev/Versioning.html). // @@ -7874,13 +7919,14 @@ func (c *S3) PutBucketReplicationRequest(input *PutBucketReplicationInput) (req // replication configuration, see Replicating Objects Created with SSE Using // CMKs stored in AWS KMS (https://docs.aws.amazon.com/AmazonS3/latest/dev/replication-config-for-kms-objects.html). // -// For information on PutBucketReplication errors, see ReplicationErrorCodeList +// For information on PutBucketReplication errors, see List of replication-related +// error codes (https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html#ReplicationErrorCodeList) // // The following operations are related to PutBucketReplication: // -// * GetBucketReplication +// * GetBucketReplication (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketReplication.html) // -// * DeleteBucketReplication +// * DeleteBucketReplication (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketReplication.html) // // 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 @@ -7950,6 +7996,10 @@ func (c *S3) PutBucketRequestPaymentRequest(input *PutBucketRequestPaymentInput) output = &PutBucketRequestPaymentOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -7963,9 +8013,9 @@ func (c *S3) PutBucketRequestPaymentRequest(input *PutBucketRequestPaymentInput) // // The following operations are related to PutBucketRequestPayment: // -// * CreateBucket +// * CreateBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html) // -// * GetBucketRequestPayment +// * GetBucketRequestPayment (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketRequestPayment.html) // // 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 @@ -8035,6 +8085,10 @@ func (c *S3) PutBucketTaggingRequest(input *PutBucketTaggingInput) (req *request output = &PutBucketTaggingOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -8065,8 +8119,8 @@ func (c *S3) PutBucketTaggingRequest(input *PutBucketTaggingInput) (req *request // * Error code: InvalidTagError Description: The tag provided was not a // valid tag. This error can occur if the tag did not pass input validation. // For information about tag restrictions, see User-Defined Tag Restrictions -// (https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2//allocation-tag-restrictions.html) -// and AWS-Generated Cost Allocation Tag Restrictions (https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2//aws-tag-restrictions.html). +// (https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/allocation-tag-restrictions.html) +// and AWS-Generated Cost Allocation Tag Restrictions (https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/aws-tag-restrictions.html). // // * Error code: MalformedXMLError Description: The XML provided does not // match the schema. @@ -8079,9 +8133,9 @@ func (c *S3) PutBucketTaggingRequest(input *PutBucketTaggingInput) (req *request // // The following operations are related to PutBucketTagging: // -// * GetBucketTagging +// * GetBucketTagging (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketTagging.html) // -// * DeleteBucketTagging +// * DeleteBucketTagging (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketTagging.html) // // 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 @@ -8151,6 +8205,10 @@ func (c *S3) PutBucketVersioningRequest(input *PutBucketVersioningInput) (req *r output = &PutBucketVersioningOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -8168,7 +8226,8 @@ func (c *S3) PutBucketVersioningRequest(input *PutBucketVersioningInput) (req *r // added to the bucket receive the version ID null. // // If the versioning state has never been set on a bucket, it has no versioning -// state; a GetBucketVersioning request does not return a versioning state value. +// state; a GetBucketVersioning (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketVersioning.html) +// request does not return a versioning state value. // // If the bucket owner enables MFA Delete in the bucket versioning configuration, // the bucket owner must include the x-amz-mfa request header and the Status @@ -8185,11 +8244,11 @@ func (c *S3) PutBucketVersioningRequest(input *PutBucketVersioningInput) (req *r // // Related Resources // -// * CreateBucket +// * CreateBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html) // -// * DeleteBucket +// * DeleteBucket (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucket.html) // -// * GetBucketVersioning +// * GetBucketVersioning (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketVersioning.html) // // 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 @@ -8259,6 +8318,10 @@ func (c *S3) PutBucketWebsiteRequest(input *PutBucketWebsiteInput) (req *request output = &PutBucketWebsiteOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -8326,6 +8389,11 @@ func (c *S3) PutBucketWebsiteRequest(input *PutBucketWebsiteInput) (req *request // // * HttpRedirectCode // +// Amazon S3 has a limitation of 50 routing rules per website configuration. +// If you require more than 50 routing rules, you can use object redirect. For +// more information, see Configuring an Object Redirect (https://docs.aws.amazon.com/AmazonS3/latest/dev/how-to-page-redirect.html) +// in the Amazon Simple Storage Service 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. @@ -8415,12 +8483,12 @@ func (c *S3) PutObjectRequest(input *PutObjectInput) (req *request.Request, outp // you can calculate the MD5 while putting an object to Amazon S3 and compare // the returned ETag to the calculated MD5 value. // -// To configure your application to send the request headers before sending -// the request body, use the 100-continue HTTP status code. For PUT operations, -// this helps you avoid sending the message body if the message is rejected -// based on the headers (for example, because authentication fails or a redirect -// occurs). For more information on the 100-continue HTTP status code, see Section -// 8.2.3 of http://www.ietf.org/rfc/rfc2616.txt (http://www.ietf.org/rfc/rfc2616.txt). +// The Content-MD5 header is required for any request to upload an object with +// a retention period configured using Amazon S3 Object Lock. For more information +// about Amazon S3 Object Lock, see Amazon S3 Object Lock Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lock-overview.html) +// in the Amazon Simple Storage Service Developer Guide. +// +// Server-side Encryption // // You can optionally request server-side encryption. With server-side encryption, // Amazon S3 encrypts your data as it writes it to disks in its data centers @@ -8428,149 +8496,41 @@ func (c *S3) PutObjectRequest(input *PutObjectInput) (req *request.Request, outp // your own encryption key or use AWS managed encryption keys. For more information, // see Using Server-Side Encryption (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html). // -// Access Permissions +// Access Control List (ACL)-Specific Request Headers // -// You can optionally specify the accounts or groups that should be granted -// specific permissions on the new object. There are two ways to grant the permissions -// using the request headers: -// -// * Specify a canned ACL with the x-amz-acl request header. For more information, -// see Canned ACL (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#CannedACL). -// -// * Specify access permissions explicitly with the x-amz-grant-read, x-amz-grant-read-acp, -// x-amz-grant-write-acp, and x-amz-grant-full-control headers. These parameters -// map to the set of permissions that Amazon S3 supports in an ACL. For more -// information, see Access Control List (ACL) Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html). -// -// You can use either a canned ACL or specify access permissions explicitly. -// You cannot do both. -// -// Server-Side- Encryption-Specific Request Headers -// -// You can optionally tell Amazon S3 to encrypt data at rest using server-side -// encryption. Server-side encryption is for data encryption at rest. Amazon -// S3 encrypts your data as it writes it to disks in its data centers and decrypts -// it when you access it. The option you use depends on whether you want to -// use AWS managed encryption keys or provide your own encryption key. -// -// * Use encryption keys managed by Amazon S3 or customer master keys (CMKs) -// stored in AWS Key Management Service (AWS KMS) – If you want AWS to -// manage the keys used to encrypt data, specify the following headers in -// the request. x-amz-server-side​-encryption x-amz-server-side-encryption-aws-kms-key-id -// x-amz-server-side-encryption-context If you specify x-amz-server-side-encryption:aws:kms, -// but don't provide x-amz-server-side-encryption-aws-kms-key-id, Amazon -// S3 uses the AWS managed CMK in AWS KMS to protect the data. If you want -// to use a customer managed AWS KMS CMK, you must provide the x-amz-server-side-encryption-aws-kms-key-id -// of the symmetric customer managed CMK. Amazon S3 only supports symmetric -// CMKs and not asymmetric CMKs. For more information, see Using Symmetric -// and Asymmetric Keys (https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html) -// in the AWS Key Management Service Developer Guide. All GET and PUT requests -// for an object protected by AWS KMS fail if you don't make them with SSL -// or by using SigV4. For more information about server-side encryption with -// CMKs stored in AWS KMS (SSE-KMS), see Protecting Data Using Server-Side -// Encryption with CMKs stored in AWS (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html). -// -// * Use customer-provided encryption keys – If you want to manage your -// own encryption keys, provide all the following headers in the request. -// x-amz-server-side​-encryption​-customer-algorithm x-amz-server-side​-encryption​-customer-key -// x-amz-server-side​-encryption​-customer-key-MD5 For more information -// about server-side encryption with CMKs stored in KMS (SSE-KMS), see Protecting -// Data Using Server-Side Encryption with CMKs stored in AWS (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html). -// -// Access-Control-List (ACL)-Specific Request Headers -// -// You also can use the following access control–related headers with this -// operation. By default, all objects are private. Only the owner has full access -// control. When adding a new object, you can grant permissions to individual -// AWS accounts or to predefined groups defined by Amazon S3. These permissions -// are then added to the Access Control List (ACL) on the object. For more information, -// see Using ACLs (https://docs.aws.amazon.com/AmazonS3/latest/dev/S3_ACLs_UsingACLs.html). -// With this operation, you can grant access permissions using one of the following -// two methods: -// -// * Specify a canned ACL (x-amz-acl) — Amazon S3 supports a set of predefined -// ACLs, known as canned ACLs. Each canned ACL has a predefined set of grantees -// and permissions. For more information, see Canned ACL (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#CannedACL). -// -// * Specify access permissions explicitly — To explicitly grant access -// permissions to specific AWS accounts or groups, use the following headers. -// Each header maps to specific permissions that Amazon S3 supports in an -// ACL. For more information, see Access Control List (ACL) Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html). -// In the header, you specify a list of grantees who get the specific permission. -// To grant permissions explicitly use: x-amz-grant-read x-amz-grant-write -// x-amz-grant-read-acp x-amz-grant-write-acp x-amz-grant-full-control You -// specify each grantee as a type=value pair, where the type is one of the -// following: emailAddress – if the value specified is the email address -// of an AWS account Using email addresses to specify a grantee is only supported -// in the following AWS Regions: US East (N. Virginia) US West (N. California) -// US West (Oregon) Asia Pacific (Singapore) Asia Pacific (Sydney) Asia Pacific -// (Tokyo) EU (Ireland) South America (São Paulo) For a list of all the -// Amazon S3 supported Regions and endpoints, see Regions and Endpoints (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) -// in the AWS General Reference id – if the value specified is the canonical -// user ID of an AWS account uri – if you are granting permissions to a -// predefined group For example, the following x-amz-grant-read header grants -// the AWS accounts identified by email addresses permissions to read object -// data and its metadata: x-amz-grant-read: emailAddress="xyz@amazon.com", -// emailAddress="abc@amazon.com" -// -// Server-Side- Encryption-Specific Request Headers -// -// You can optionally tell Amazon S3 to encrypt data at rest using server-side -// encryption. Server-side encryption is for data encryption at rest. Amazon -// S3 encrypts your data as it writes it to disks in its data centers and decrypts -// it when you access it. The option you use depends on whether you want to -// use AWS-managed encryption keys or provide your own encryption key. -// -// * Use encryption keys managed by Amazon S3 or customer master keys (CMKs) -// stored in AWS Key Management Service (AWS KMS) – If you want AWS to -// manage the keys used to encrypt data, specify the following headers in -// the request. x-amz-server-side​-encryption x-amz-server-side-encryption-aws-kms-key-id -// x-amz-server-side-encryption-context If you specify x-amz-server-side-encryption:aws:kms, -// but don't provide x-amz-server-side-encryption-aws-kms-key-id, Amazon -// S3 uses the AWS managed CMK in AWS KMS to protect the data. If you want -// to use a customer managed AWS KMS CMK, you must provide the x-amz-server-side-encryption-aws-kms-key-id -// of the symmetric customer managed CMK. Amazon S3 only supports symmetric -// CMKs and not asymmetric CMKs. For more information, see Using Symmetric -// and Asymmetric Keys (https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html) -// in the AWS Key Management Service Developer Guide. All GET and PUT requests -// for an object protected by AWS KMS fail if you don't make them with SSL -// or by using SigV4. For more information about server-side encryption with -// CMKs stored in AWS KMS (SSE-KMS), see Protecting Data Using Server-Side -// Encryption with CMKs stored in AWS KMS (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html). -// -// * Use customer-provided encryption keys – If you want to manage your -// own encryption keys, provide all the following headers in the request. -// If you use this feature, the ETag value that Amazon S3 returns in the -// response is not the MD5 of the object. x-amz-server-side​-encryption​-customer-algorithm -// x-amz-server-side​-encryption​-customer-key x-amz-server-side​-encryption​-customer-key-MD5 -// For more information about server-side encryption with CMKs stored in -// AWS KMS (SSE-KMS), see Protecting Data Using Server-Side Encryption with -// CMKs stored in AWS KMS (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingKMSEncryption.html). +// You can use headers to grant ACL- based permissions. By default, all objects +// are private. Only the owner has full access control. When adding a new object, +// you can grant permissions to individual AWS accounts or to predefined groups +// defined by Amazon S3. These permissions are then added to the ACL on the +// object. For more information, see Access Control List (ACL) Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html) +// and Managing ACLs Using the REST API (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-using-rest-api.html). // // Storage Class Options // -// By default, Amazon S3 uses the Standard storage class to store newly created -// objects. The Standard storage class provides high durability and high availability. -// You can specify other storage classes depending on the performance needs. +// By default, Amazon S3 uses the STANDARD storage class to store newly created +// objects. The STANDARD storage class provides high durability and high availability. +// Depending on performance needs, you can specify a different storage class. // For more information, see Storage Classes (https://docs.aws.amazon.com/AmazonS3/latest/dev/storage-class-intro.html) -// in the Amazon Simple Storage Service Developer Guide. +// in the Amazon S3 Service Developer Guide. // // Versioning // // If you enable versioning for a bucket, Amazon S3 automatically generates // a unique version ID for the object being stored. Amazon S3 returns this ID -// in the response using the x-amz-version-id response header. If versioning -// is suspended, Amazon S3 always uses null as the version ID for the object -// stored. For more information about returning the versioning state of a bucket, -// see GetBucketVersioning. If you enable versioning for a bucket, when Amazon -// S3 receives multiple write requests for the same object simultaneously, it -// stores all of the objects. +// in the response. When you enable versioning for a bucket, if Amazon S3 receives +// multiple write requests for the same object simultaneously, it stores all +// of the objects. +// +// For more information about versioning, see Adding Objects to Versioning Enabled +// Buckets (https://docs.aws.amazon.com/AmazonS3/latest/dev/AddingObjectstoVersioningEnabledBuckets.html). +// For information about returning the versioning state of a bucket, see GetBucketVersioning +// (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketVersioning.html). // // Related Resources // -// * CopyObject +// * CopyObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CopyObject.html) // -// * DeleteObject +// * DeleteObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObject.html) // // 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 @@ -8639,19 +8599,27 @@ func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request output = &PutObjectAclOutput{} req = c.newRequest(op, input, output) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } // PutObjectAcl API operation for Amazon Simple Storage Service. // // Uses the acl subresource to set the access control list (ACL) permissions -// for an object that already exists in a bucket. You must have WRITE_ACP permission -// to set the ACL of an object. +// for an object that already exists in an S3 bucket. You must have WRITE_ACP +// permission to set the ACL of an object. For more information, see What permissions +// can I grant? (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#permissions) +// in the Amazon Simple Storage Service Developer Guide. // // Depending on your application needs, you can choose to set the ACL on an // object using either the request body or the headers. For example, if you // have an existing application that updates a bucket ACL using the request -// body, you can continue to use that approach. +// body, you can continue to use that approach. For more information, see Access +// Control List (ACL) Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html) +// in the Amazon S3 Developer Guide. // // Access Permissions // @@ -8673,12 +8641,19 @@ func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request // S3 supports in an ACL. For more information, see Access Control List (ACL) // Overview (https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html). // You specify each grantee as a type=value pair, where the type is one of -// the following: emailAddress – if the value specified is the email address -// of an AWS account id – if the value specified is the canonical user -// ID of an AWS account uri – if you are granting permissions to a predefined -// group For example, the following x-amz-grant-read header grants list objects -// permission to the two AWS accounts identified by their email addresses. -// x-amz-grant-read: emailAddress="xyz@amazon.com", emailAddress="abc@amazon.com" +// the following: id – if the value specified is the canonical user ID +// of an AWS account uri – if you are granting permissions to a predefined +// group emailAddress – if the value specified is the email address of +// an AWS account Using email addresses to specify a grantee is only supported +// in the following AWS Regions: US East (N. Virginia) US West (N. California) +// US West (Oregon) Asia Pacific (Singapore) Asia Pacific (Sydney) Asia Pacific +// (Tokyo) Europe (Ireland) South America (São Paulo) For a list of all +// the Amazon S3 supported Regions and endpoints, see Regions and Endpoints +// (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) in +// the AWS General Reference. For example, the following x-amz-grant-read +// header grants list objects permission to the two AWS accounts identified +// by their email addresses. x-amz-grant-read: emailAddress="xyz@amazon.com", +// emailAddress="abc@amazon.com" // // You can use either a canned ACL or specify access permissions explicitly. // You cannot do both. @@ -8688,11 +8663,6 @@ func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request // You can specify the person (grantee) to whom you're assigning access rights // (using request elements) in the following ways: // -// * By Email address: <>Grantees@email.com<>lt;/Grantee> -// The grantee is resolved to the CanonicalUser and, in a response to a GET -// Object acl request, appears as the CanonicalUser. -// // * By the person's ID: <>ID<><>GranteesEmail<> // DisplayName is optional and ignored in the request. @@ -8700,6 +8670,17 @@ func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request // * By URI: <>http://acs.amazonaws.com/groups/global/AuthenticatedUsers<> // +// * By Email address: <>Grantees@email.com<>lt;/Grantee> +// The grantee is resolved to the CanonicalUser and, in a response to a GET +// Object acl request, appears as the CanonicalUser. Using email addresses +// to specify a grantee is only supported in the following AWS Regions: US +// East (N. Virginia) US West (N. California) US West (Oregon) Asia Pacific +// (Singapore) Asia Pacific (Sydney) Asia Pacific (Tokyo) Europe (Ireland) +// South America (São Paulo) For a list of all the Amazon S3 supported Regions +// and endpoints, see Regions and Endpoints (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) +// in the AWS General Reference. +// // Versioning // // The ACL of an object is set at the object version level. By default, PUT @@ -8708,9 +8689,9 @@ func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request // // Related Resources // -// * CopyObject +// * CopyObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CopyObject.html) // -// * GetObject +// * GetObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html) // // 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 @@ -8784,6 +8765,10 @@ func (c *S3) PutObjectLegalHoldRequest(input *PutObjectLegalHoldInput) (req *req output = &PutObjectLegalHoldOutput{} req = c.newRequest(op, input, output) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -8862,6 +8847,10 @@ func (c *S3) PutObjectLockConfigurationRequest(input *PutObjectLockConfiguration output = &PutObjectLockConfigurationOutput{} req = c.newRequest(op, input, output) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -8945,6 +8934,10 @@ func (c *S3) PutObjectRetentionRequest(input *PutObjectRetentionInput) (req *req output = &PutObjectRetentionOutput{} req = c.newRequest(op, input, output) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -9023,17 +9016,21 @@ func (c *S3) PutObjectTaggingRequest(input *PutObjectTaggingInput) (req *request output = &PutObjectTaggingOutput{} req = c.newRequest(op, input, output) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } // PutObjectTagging API operation for Amazon Simple Storage Service. // -// Sets the supplied tag-set to an object that already exists in a bucket +// Sets the supplied tag-set to an object that already exists in a bucket. // // A tag is a key-value pair. You can associate tags with an object by sending // a PUT request against the tagging subresource that is associated with the // object. You can retrieve tags by sending a GET request. For more information, -// see GetObjectTagging. +// see GetObjectTagging (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObjectTagging.html). // // For tagging-related restrictions related to characters and encodings, see // Tag Restrictions (https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/allocation-tag-restrictions.html). @@ -9065,7 +9062,7 @@ func (c *S3) PutObjectTaggingRequest(input *PutObjectTaggingInput) (req *request // // Related Resources // -// * GetObjectTagging +// * GetObjectTagging (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObjectTagging.html) // // 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 @@ -9135,6 +9132,10 @@ func (c *S3) PutPublicAccessBlockRequest(input *PutPublicAccessBlockInput) (req output = &PutPublicAccessBlockOutput{} req = c.newRequest(op, input, output) req.Handlers.Unmarshal.Swap(restxml.UnmarshalHandler.Name, protocol.UnmarshalDiscardBodyHandler) + req.Handlers.Build.PushBackNamed(request.NamedHandler{ + Name: "contentMd5Handler", + Fn: checksum.AddBodyContentMD5Handler, + }) return } @@ -9157,11 +9158,11 @@ func (c *S3) PutPublicAccessBlockRequest(input *PutPublicAccessBlockInput) (req // // Related Resources // -// * GetPublicAccessBlock +// * GetPublicAccessBlock (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetPublicAccessBlock.html) // -// * DeletePublicAccessBlock +// * DeletePublicAccessBlock (https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeletePublicAccessBlock.html) // -// * GetBucketPolicyStatus +// * GetBucketPolicyStatus (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketPolicyStatus.html) // // * Using Amazon S3 Block Public Access (https://docs.aws.amazon.com/AmazonS3/latest/dev/access-control-block-public-access.html) // @@ -9246,9 +9247,9 @@ func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Reque // * restore an archive - Restore an archived object // // To use this operation, you must have permissions to perform the s3:RestoreObject -// and s3:GetObject actions. The bucket owner has this permission by default -// and can grant this permission to others. For more information about permissions, -// see Permissions Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) +// action. The bucket owner has this permission by default and can grant this +// permission to others. For more information about permissions, see Permissions +// Related to Bucket Subresource Operations (https://docs.aws.amazon.com/AmazonS3/latest/dev/using-with-s3-actions.html#using-with-s3-actions-related-to-bucket-subresources) // and Managing Access Permissions to Your Amazon S3 Resources (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) // in the Amazon Simple Storage Service Developer Guide. // @@ -9273,7 +9274,8 @@ func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Reque // (https://docs.aws.amazon.com/AmazonS3/latest/dev/querying-glacier-archives.html) // in the Amazon Simple Storage Service Developer Guide. For more information // about the S3 structure in the request body, see the following: PutObject -// Managing Access with ACLs (https://docs.aws.amazon.com/AmazonS3/latest/dev/S3_ACLs_UsingACLs.html) +// (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html) Managing +// Access with ACLs (https://docs.aws.amazon.com/AmazonS3/latest/dev/S3_ACLs_UsingACLs.html) // in the Amazon Simple Storage Service Developer Guide Protecting Data Using // Server-Side Encryption (https://docs.aws.amazon.com/AmazonS3/latest/dev/serv-side-encryption.html) // in the Amazon Simple Storage Service Developer Guide @@ -9290,8 +9292,8 @@ func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Reque // the query.) You cannot mix ordinal positions with header column names. // SELECT s.Id, s.FirstName, s.SSN FROM S3Object s // -// For more information about using SQL with Glacier Select restore, see SQL -// Reference for Amazon S3 Select and Glacier Select (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-glacier-select-sql-reference.html) +// For more information about using SQL with S3 Glacier Select restore, see +// SQL Reference for Amazon S3 Select and S3 Glacier Select (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-glacier-select-sql-reference.html) // in the Amazon Simple Storage Service Developer Guide. // // When making a select request, you can also do the following: @@ -9344,12 +9346,12 @@ func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Reque // retrievals and provisioned capacity are not available for the DEEP_ARCHIVE // storage class. // -// * Standard - Standard retrievals allow you to access any of your archived +// * Standard - S3 Standard retrievals allow you to access any of your archived // objects within several hours. This is the default option for the GLACIER // and DEEP_ARCHIVE retrieval requests that do not specify the retrieval -// option. Standard retrievals typically complete within 3-5 hours from the -// GLACIER storage class and typically complete within 12 hours from the -// DEEP_ARCHIVE storage class. +// option. S3 Standard retrievals typically complete within 3-5 hours from +// the GLACIER storage class and typically complete within 12 hours from +// the DEEP_ARCHIVE storage class. // // * Bulk - Bulk retrievals are Amazon S3 Glacier’s lowest-cost retrieval // option, enabling you to retrieve large amounts, even petabytes, of data @@ -9389,7 +9391,8 @@ func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Reque // specify in a restore request. For example, if you restore an object copy // for 10 days, but the object is scheduled to expire in 3 days, Amazon S3 deletes // the object in 3 days. For more information about lifecycle configuration, -// see PutBucketLifecycleConfiguration and Object Lifecycle Management (https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lifecycle-mgmt.html) +// see PutBucketLifecycleConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLifecycleConfiguration.html) +// and Object Lifecycle Management (https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lifecycle-mgmt.html) // in Amazon Simple Storage Service Developer Guide. // // Responses @@ -9408,19 +9411,19 @@ func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Reque // (This error does not apply to SELECT type requests.) HTTP Status Code: // 409 Conflict SOAP Fault Code Prefix: Client // -// * Code: GlacierExpeditedRetrievalNotAvailable Cause: Glacier expedited +// * Code: GlacierExpeditedRetrievalNotAvailable Cause: S3 Glacier expedited // retrievals are currently not available. Try again later. (Returned if // there is insufficient capacity to process the Expedited request. This -// error applies only to Expedited retrievals and not to Standard or Bulk +// error applies only to Expedited retrievals and not to S3 Standard or Bulk // retrievals.) HTTP Status Code: 503 SOAP Fault Code Prefix: N/A // // Related Resources // -// * PutBucketLifecycleConfiguration +// * PutBucketLifecycleConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLifecycleConfiguration.html) // -// * GetBucketNotificationConfiguration +// * GetBucketNotificationConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketNotificationConfiguration.html) // -// * SQL Reference for Amazon S3 Select and Glacier Select (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-glacier-select-sql-reference.html) +// * SQL Reference for Amazon S3 Select and S3 Glacier Select (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-glacier-select-sql-reference.html) // in the Amazon Simple Storage Service Developer Guide // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -9496,7 +9499,7 @@ func (c *S3) SelectObjectContentRequest(input *SelectObjectContentInput) (req *r output = &SelectObjectContentOutput{} req = c.newRequest(op, input, output) - es := newSelectObjectContentEventStream() + es := NewSelectObjectContentEventStream() req.Handlers.Unmarshal.PushBack(es.setStreamCloser) output.EventStream = es @@ -9522,7 +9525,7 @@ func (c *S3) SelectObjectContentRequest(input *SelectObjectContentInput) (req *r // in the Amazon Simple Storage Service Developer Guide. // // For more information about using SQL with Amazon S3 Select, see SQL Reference -// for Amazon S3 Select and Glacier Select (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-glacier-select-sql-reference.html) +// for Amazon S3 Select and S3 Glacier Select (https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-glacier-select-sql-reference.html) // in the Amazon Simple Storage Service Developer Guide. // // Permissions @@ -9550,8 +9553,8 @@ func (c *S3) SelectObjectContentRequest(input *SelectObjectContentInput) (req *r // * Server-side encryption - Amazon S3 Select supports querying objects // that are protected with server-side encryption. For objects that are encrypted // with customer-provided encryption keys (SSE-C), you must use HTTPS, and -// you must use the headers that are documented in the GetObject. For more -// information about SSE-C, see Server-Side Encryption (Using Customer-Provided +// you must use the headers that are documented in the GetObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html). +// For more information about SSE-C, see Server-Side Encryption (Using Customer-Provided // Encryption Keys) (https://docs.aws.amazon.com/AmazonS3/latest/dev/ServerSideEncryptionCustomerKeys.html) // in the Amazon Simple Storage Service Developer Guide. For objects that // are encrypted with Amazon S3 managed encryption keys (SSE-S3) and customer @@ -9565,16 +9568,18 @@ func (c *S3) SelectObjectContentRequest(input *SelectObjectContentInput) (req *r // // Given the response size is unknown, Amazon S3 Select streams the response // as a series of messages and includes a Transfer-Encoding header with chunked -// as its value in the response. For more information, see RESTSelectObjectAppendix . +// as its value in the response. For more information, see Appendix: SelectObjectContent +// Response (https://docs.aws.amazon.com/AmazonS3/latest/API/RESTSelectObjectAppendix.html) . // // GetObject Support // // The SelectObjectContent operation does not support the following GetObject -// functionality. For more information, see GetObject. +// functionality. For more information, see GetObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html). // -// * Range: While you can specify a scan range for a Amazon S3 Select request, -// see SelectObjectContentRequest$ScanRange in the request parameters below, -// you cannot specify the range of bytes of an object to return. +// * Range: Although you can specify a scan range for an Amazon S3 Select +// request (see SelectObjectContentRequest - ScanRange (https://docs.aws.amazon.com/AmazonS3/latest/API/API_SelectObjectContent.html#AmazonS3-SelectObjectContent-request-ScanRange) +// in the request parameters), you cannot specify the range of bytes of an +// object to return. // // * GLACIER, DEEP_ARCHIVE and REDUCED_REDUNDANCY storage classes: You cannot // specify the GLACIER, DEEP_ARCHIVE, or REDUCED_REDUNDANCY storage classes. @@ -9583,16 +9588,16 @@ func (c *S3) SelectObjectContentRequest(input *SelectObjectContentInput) (req *r // // Special Errors // -// For a list of special errors for this operation and for general information -// about Amazon S3 errors and a list of error codes, see ErrorResponses +// For a list of special errors for this operation, see List of SELECT Object +// Content Error Codes (https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html#SelectObjectContentErrorCodeList) // // Related Resources // -// * GetObject +// * GetObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html) // -// * GetBucketLifecycleConfiguration +// * GetBucketLifecycleConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetBucketLifecycleConfiguration.html) // -// * PutBucketLifecycleConfiguration +// * PutBucketLifecycleConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLifecycleConfiguration.html) // // 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 @@ -9622,7 +9627,13 @@ func (c *S3) SelectObjectContentWithContext(ctx aws.Context, input *SelectObject return out, req.Send() } +var _ awserr.Error + // SelectObjectContentEventStream provides the event stream handling for the SelectObjectContent. +// +// For testing and mocking the event stream this type should be initialized via +// the NewSelectObjectContentEventStream constructor function. Using the functional options +// to pass in nested mock behavior. type SelectObjectContentEventStream struct { // Reader is the EventStream reader for the SelectObjectContentEventStream @@ -9645,11 +9656,31 @@ type SelectObjectContentEventStream struct { err *eventstreamapi.OnceError } -func newSelectObjectContentEventStream() *SelectObjectContentEventStream { - return &SelectObjectContentEventStream{ +// NewSelectObjectContentEventStream initializes an SelectObjectContentEventStream. +// This function should only be used for testing and mocking the SelectObjectContentEventStream +// stream within your application. +// +// The Reader member must be set before reading events from the stream. +// +// The StreamCloser member should be set to the underlying io.Closer, +// (e.g. http.Response.Body), that will be closed when the stream Close method +// is called. +// +// es := NewSelectObjectContentEventStream(func(o *SelectObjectContentEventStream{ +// es.Reader = myMockStreamReader +// es.StreamCloser = myMockStreamCloser +// }) +func NewSelectObjectContentEventStream(opts ...func(*SelectObjectContentEventStream)) *SelectObjectContentEventStream { + es := &SelectObjectContentEventStream{ done: make(chan struct{}), err: eventstreamapi.NewOnceError(), } + + for _, fn := range opts { + fn(es) + } + + return es } func (es *SelectObjectContentEventStream) setStreamCloser(r *request.Request) { @@ -9696,6 +9727,7 @@ func (es *SelectObjectContentEventStream) waitStreamPartClose() { // * ProgressEvent // * RecordsEvent // * StatsEvent +// * SelectObjectContentEventStreamUnknownEvent func (es *SelectObjectContentEventStream) Events() <-chan SelectObjectContentEventStreamEvent { return es.Reader.Events() } @@ -9812,12 +9844,13 @@ func (c *S3) UploadPartRequest(input *UploadPartInput) (req *request.Request, ou // In this operation, you provide part data in your request. However, you have // an option to specify your existing Amazon S3 object as a data source for // the part you are uploading. To upload a part from an existing object, you -// use the UploadPartCopy operation. +// use the UploadPartCopy (https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPartCopy.html) +// operation. // -// You must initiate a multipart upload (see CreateMultipartUpload) before you -// can upload any part. In response to your initiate request, Amazon S3 returns -// an upload ID, a unique identifier, that you must include in your upload part -// request. +// You must initiate a multipart upload (see CreateMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateMultipartUpload.html)) +// before you can upload any part. In response to your initiate request, Amazon +// S3 returns an upload ID, a unique identifier, that you must include in your +// upload part request. // // Part numbers can be any number from 1 to 10,000, inclusive. A part number // uniquely identifies a part and also defines its position within the object @@ -9851,25 +9884,25 @@ func (c *S3) UploadPartRequest(input *UploadPartInput) (req *request.Request, ou // key, or you can use the AWS managed encryption keys. If you choose to provide // your own encryption key, the request headers you provide in the request must // match the headers you used in the request to initiate the upload by using -// CreateMultipartUpload. For more information, go to Using Server-Side Encryption -// (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html) +// CreateMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateMultipartUpload.html). +// For more information, go to Using Server-Side Encryption (https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingServerSideEncryption.html) // in the Amazon Simple Storage Service Developer Guide. // // Server-side encryption is supported by the S3 Multipart Upload actions. Unless // you are using a customer-provided encryption key, you don't need to specify // the encryption parameters in each UploadPart request. Instead, you only need // to specify the server-side encryption parameters in the initial Initiate -// Multipart request. For more information, see CreateMultipartUpload. +// Multipart request. For more information, see CreateMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateMultipartUpload.html). // // If you requested server-side encryption using a customer-provided encryption // key in your initiate multipart upload request, you must provide identical // encryption information in each part upload using the following headers. // -// * x-amz-server-side​-encryption​-customer-algorithm +// * x-amz-server-side-encryption-customer-algorithm // -// * x-amz-server-side​-encryption​-customer-key +// * x-amz-server-side-encryption-customer-key // -// * x-amz-server-side​-encryption​-customer-key-MD5 +// * x-amz-server-side-encryption-customer-key-MD5 // // Special Errors // @@ -9880,15 +9913,15 @@ func (c *S3) UploadPartRequest(input *UploadPartInput) (req *request.Request, ou // // Related Resources // -// * CreateMultipartUpload +// * CreateMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateMultipartUpload.html) // -// * CompleteMultipartUpload +// * CompleteMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html) // -// * AbortMultipartUpload +// * AbortMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_AbortMultipartUpload.html) // -// * ListParts +// * ListParts (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListParts.html) // -// * ListMultipartUploads +// * ListMultipartUploads (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListMultipartUploads.html) // // 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 @@ -9972,7 +10005,8 @@ func (c *S3) UploadPartCopyRequest(input *UploadPartCopyInput) (req *request.Req // in the Amazon Simple Storage Service Developer Guide. // // Instead of using an existing object as part data, you might use the UploadPart -// operation and provide data in your request. +// (https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPart.html) operation +// and provide data in your request. // // You must initiate a multipart upload before you can upload any part. In response // to your initiate request. Amazon S3 returns a unique identifier, the upload @@ -9993,8 +10027,8 @@ func (c *S3) UploadPartCopyRequest(input *UploadPartCopyInput) (req *request.Req // in the Amazon Simple Storage Service Developer Guide. // // * For information about using server-side encryption with customer-provided -// encryption keys with the UploadPartCopy operation, see CopyObject and -// UploadPart. +// encryption keys with the UploadPartCopy operation, see CopyObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CopyObject.html) +// and UploadPart (https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPart.html). // // Note the following additional considerations about the request headers x-amz-copy-source-if-match, // x-amz-copy-source-if-none-match, x-amz-copy-source-if-unmodified-since, and @@ -10039,17 +10073,17 @@ func (c *S3) UploadPartCopyRequest(input *UploadPartCopyInput) (req *request.Req // // Related Resources // -// * CreateMultipartUpload +// * CreateMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateMultipartUpload.html) // -// * UploadPart +// * UploadPart (https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPart.html) // -// * CompleteMultipartUpload +// * CompleteMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_CompleteMultipartUpload.html) // -// * AbortMultipartUpload +// * AbortMultipartUpload (https://docs.aws.amazon.com/AmazonS3/latest/API/API_AbortMultipartUpload.html) // -// * ListParts +// * ListParts (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListParts.html) // -// * ListMultipartUploads +// * ListMultipartUploads (https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListMultipartUploads.html) // // 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 @@ -10123,6 +10157,11 @@ type AbortMultipartUploadInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Key of the object for which the multipart upload was initiated. // // Key is a required field @@ -10189,6 +10228,12 @@ func (s *AbortMultipartUploadInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *AbortMultipartUploadInput) SetExpectedBucketOwner(v string) *AbortMultipartUploadInput { + s.ExpectedBucketOwner = &v + return s +} + // SetKey sets the Key field's value. func (s *AbortMultipartUploadInput) SetKey(v string) *AbortMultipartUploadInput { s.Key = &v @@ -10615,8 +10660,11 @@ type AnalyticsS3BucketDestination struct { // Bucket is a required field Bucket *string `type:"string" required:"true"` - // The account ID that owns the destination bucket. If no account ID is provided, - // the owner will not be validated prior to exporting data. + // The account ID that owns the destination S3 bucket. If no account ID is provided, + // the owner is not validated before exporting data. + // + // Although this value is optional, we strongly recommend that you set it to + // help prevent problems if the destination bucket ownership changes. BucketAccountId *string `type:"string"` // Specifies the file format used when exporting data to Amazon S3. @@ -11226,6 +11274,11 @@ type CompleteMultipartUploadInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Object key for which the multipart upload was initiated. // // Key is a required field @@ -11295,6 +11348,12 @@ func (s *CompleteMultipartUploadInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *CompleteMultipartUploadInput) SetExpectedBucketOwner(v string) *CompleteMultipartUploadInput { + s.ExpectedBucketOwner = &v + return s +} + // SetKey sets the Key field's value. func (s *CompleteMultipartUploadInput) SetKey(v string) *CompleteMultipartUploadInput { s.Key = &v @@ -11578,6 +11637,8 @@ func (s *ContinuationEvent) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *ContinuationEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType)) return msg, err @@ -11611,8 +11672,30 @@ type CopyObjectInput struct { // A standard MIME type describing the format of the object data. ContentType *string `location:"header" locationName:"Content-Type" type:"string"` - // The name of the source bucket and key name of the source object, separated - // by a slash (/). Must be URL-encoded. + // Specifies the source object for the copy operation. You specify the value + // in one of two formats, depending on whether you want to access the source + // object through an access point (https://docs.aws.amazon.com/AmazonS3/latest/dev/access-points.html): + // + // * For objects not accessed through an access point, specify the name of + // the source bucket and the key of the source object, separated by a slash + // (/). For example, to copy the object reports/january.pdf from the bucket + // awsexamplebucket, use awsexamplebucket/reports/january.pdf. The value + // must be URL encoded. + // + // * For objects accessed through access points, specify the Amazon Resource + // Name (ARN) of the object as accessed through the access point, in the + // format arn:aws:s3:::accesspoint//object/. + // For example, to copy the object reports/january.pdf through access point + // my-access-point owned by account 123456789012 in Region us-west-2, use + // the URL encoding of arn:aws:s3:us-west-2:123456789012:accesspoint/my-access-point/object/reports/january.pdf. + // The value must be URL encoded. Amazon S3 supports copy operations using + // access points only when the source and destination buckets are in the + // same AWS Region. + // + // To copy a specific version of an object, append ?versionId= to + // the value (for example, awsexamplebucket/reports/january.pdf?versionId=QUpfdndhfd8438MNFDN93jdnJFkdmqnh893). + // If you don't specify a version ID, Amazon S3 copies the latest version of + // the source object. // // CopySource is a required field CopySource *string `location:"header" locationName:"x-amz-copy-source" type:"string" required:"true"` @@ -11644,6 +11727,16 @@ type CopyObjectInput struct { // encryption key was transmitted without error. CopySourceSSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-key-MD5" type:"string"` + // The account id of the expected destination bucket owner. If the destination + // bucket is owned by a different account, the request will fail with an HTTP + // 403 (Access Denied) error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + + // The account id of the expected source bucket owner. If the source bucket + // is owned by a different account, the request will fail with an HTTP 403 (Access + // Denied) error. + ExpectedSourceBucketOwner *string `location:"header" locationName:"x-amz-source-expected-bucket-owner" type:"string"` + // The date and time at which the object is no longer cacheable. Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp"` @@ -11694,7 +11787,7 @@ type CopyObjectInput struct { // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting // data. This value is used to store the object and then it is discarded; Amazon // S3 does not store the encryption key. The key must be appropriate for use - // with the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm + // with the algorithm specified in the x-amz-server-side-encryption-customer-algorithm // header. SSECustomerKey *string `marshal-as:"blob" location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string" sensitive:"true"` @@ -11877,6 +11970,18 @@ func (s *CopyObjectInput) SetCopySourceSSECustomerKeyMD5(v string) *CopyObjectIn return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *CopyObjectInput) SetExpectedBucketOwner(v string) *CopyObjectInput { + s.ExpectedBucketOwner = &v + return s +} + +// SetExpectedSourceBucketOwner sets the ExpectedSourceBucketOwner field's value. +func (s *CopyObjectInput) SetExpectedSourceBucketOwner(v string) *CopyObjectInput { + s.ExpectedSourceBucketOwner = &v + return s +} + // SetExpires sets the Expires field's value. func (s *CopyObjectInput) SetExpires(v time.Time) *CopyObjectInput { s.Expires = &v @@ -12411,6 +12516,11 @@ type CreateMultipartUploadInput struct { // A standard MIME type describing the format of the object data. ContentType *string `location:"header" locationName:"Content-Type" type:"string"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The date and time at which the object is no longer cacheable. Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp"` @@ -12457,7 +12567,7 @@ type CreateMultipartUploadInput struct { // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting // data. This value is used to store the object and then it is discarded; Amazon // S3 does not store the encryption key. The key must be appropriate for use - // with the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm + // with the algorithm specified in the x-amz-server-side-encryption-customer-algorithm // header. SSECustomerKey *string `marshal-as:"blob" location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string" sensitive:"true"` @@ -12576,6 +12686,12 @@ func (s *CreateMultipartUploadInput) SetContentType(v string) *CreateMultipartUp return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *CreateMultipartUploadInput) SetExpectedBucketOwner(v string) *CreateMultipartUploadInput { + s.ExpectedBucketOwner = &v + return s +} + // SetExpires sets the Expires field's value. func (s *CreateMultipartUploadInput) SetExpires(v time.Time) *CreateMultipartUploadInput { s.Expires = &v @@ -12975,6 +13091,11 @@ type DeleteBucketAnalyticsConfigurationInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The ID that identifies the analytics configuration. // // Id is a required field @@ -13023,6 +13144,12 @@ func (s *DeleteBucketAnalyticsConfigurationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *DeleteBucketAnalyticsConfigurationInput) SetExpectedBucketOwner(v string) *DeleteBucketAnalyticsConfigurationInput { + s.ExpectedBucketOwner = &v + return s +} + // SetId sets the Id field's value. func (s *DeleteBucketAnalyticsConfigurationInput) SetId(v string) *DeleteBucketAnalyticsConfigurationInput { s.Id = &v @@ -13064,6 +13191,11 @@ type DeleteBucketCorsInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -13105,6 +13237,12 @@ func (s *DeleteBucketCorsInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *DeleteBucketCorsInput) SetExpectedBucketOwner(v string) *DeleteBucketCorsInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *DeleteBucketCorsInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -13141,6 +13279,11 @@ type DeleteBucketEncryptionInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -13182,6 +13325,12 @@ func (s *DeleteBucketEncryptionInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *DeleteBucketEncryptionInput) SetExpectedBucketOwner(v string) *DeleteBucketEncryptionInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *DeleteBucketEncryptionInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -13217,6 +13366,11 @@ type DeleteBucketInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -13258,6 +13412,12 @@ func (s *DeleteBucketInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *DeleteBucketInput) SetExpectedBucketOwner(v string) *DeleteBucketInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *DeleteBucketInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -13280,6 +13440,11 @@ type DeleteBucketInventoryConfigurationInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The ID used to identify the inventory configuration. // // Id is a required field @@ -13328,6 +13493,12 @@ func (s *DeleteBucketInventoryConfigurationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *DeleteBucketInventoryConfigurationInput) SetExpectedBucketOwner(v string) *DeleteBucketInventoryConfigurationInput { + s.ExpectedBucketOwner = &v + return s +} + // SetId sets the Id field's value. func (s *DeleteBucketInventoryConfigurationInput) SetId(v string) *DeleteBucketInventoryConfigurationInput { s.Id = &v @@ -13369,6 +13540,11 @@ type DeleteBucketLifecycleInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -13410,6 +13586,12 @@ func (s *DeleteBucketLifecycleInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *DeleteBucketLifecycleInput) SetExpectedBucketOwner(v string) *DeleteBucketLifecycleInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *DeleteBucketLifecycleInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -13446,6 +13628,11 @@ type DeleteBucketMetricsConfigurationInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The ID used to identify the metrics configuration. // // Id is a required field @@ -13494,6 +13681,12 @@ func (s *DeleteBucketMetricsConfigurationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *DeleteBucketMetricsConfigurationInput) SetExpectedBucketOwner(v string) *DeleteBucketMetricsConfigurationInput { + s.ExpectedBucketOwner = &v + return s +} + // SetId sets the Id field's value. func (s *DeleteBucketMetricsConfigurationInput) SetId(v string) *DeleteBucketMetricsConfigurationInput { s.Id = &v @@ -13549,6 +13742,11 @@ type DeleteBucketPolicyInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -13590,6 +13788,12 @@ func (s *DeleteBucketPolicyInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *DeleteBucketPolicyInput) SetExpectedBucketOwner(v string) *DeleteBucketPolicyInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *DeleteBucketPolicyInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -13625,6 +13829,11 @@ type DeleteBucketReplicationInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -13666,6 +13875,12 @@ func (s *DeleteBucketReplicationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *DeleteBucketReplicationInput) SetExpectedBucketOwner(v string) *DeleteBucketReplicationInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *DeleteBucketReplicationInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -13701,6 +13916,11 @@ type DeleteBucketTaggingInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -13742,6 +13962,12 @@ func (s *DeleteBucketTaggingInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *DeleteBucketTaggingInput) SetExpectedBucketOwner(v string) *DeleteBucketTaggingInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *DeleteBucketTaggingInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -13777,6 +14003,11 @@ type DeleteBucketWebsiteInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -13818,6 +14049,12 @@ func (s *DeleteBucketWebsiteInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *DeleteBucketWebsiteInput) SetExpectedBucketOwner(v string) *DeleteBucketWebsiteInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *DeleteBucketWebsiteInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -13963,6 +14200,11 @@ type DeleteObjectInput struct { // to process this operation. BypassGovernanceRetention *bool `location:"header" locationName:"x-amz-bypass-governance-retention" type:"boolean"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Key name of the object to delete. // // Key is a required field @@ -14036,6 +14278,12 @@ func (s *DeleteObjectInput) SetBypassGovernanceRetention(v bool) *DeleteObjectIn return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *DeleteObjectInput) SetExpectedBucketOwner(v string) *DeleteObjectInput { + s.ExpectedBucketOwner = &v + return s +} + // SetKey sets the Key field's value. func (s *DeleteObjectInput) SetKey(v string) *DeleteObjectInput { s.Key = &v @@ -14133,7 +14381,12 @@ type DeleteObjectTaggingInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // Name of the tag. + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + + // Name of the object key. // // Key is a required field Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` @@ -14187,6 +14440,12 @@ func (s *DeleteObjectTaggingInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *DeleteObjectTaggingInput) SetExpectedBucketOwner(v string) *DeleteObjectTaggingInput { + s.ExpectedBucketOwner = &v + return s +} + // SetKey sets the Key field's value. func (s *DeleteObjectTaggingInput) SetKey(v string) *DeleteObjectTaggingInput { s.Key = &v @@ -14261,6 +14520,11 @@ type DeleteObjectsInput struct { // Delete is a required field Delete *Delete `locationName:"Delete" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The concatenation of the authentication device's serial number, a space, // and the value that is displayed on your authentication device. Required to // permanently delete a versioned object if versioning is configured with MFA @@ -14334,6 +14598,12 @@ func (s *DeleteObjectsInput) SetDelete(v *Delete) *DeleteObjectsInput { return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *DeleteObjectsInput) SetExpectedBucketOwner(v string) *DeleteObjectsInput { + s.ExpectedBucketOwner = &v + return s +} + // SetMFA sets the MFA field's value. func (s *DeleteObjectsInput) SetMFA(v string) *DeleteObjectsInput { s.MFA = &v @@ -14411,6 +14681,11 @@ type DeletePublicAccessBlockInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -14452,6 +14727,12 @@ func (s *DeletePublicAccessBlockInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *DeletePublicAccessBlockInput) SetExpectedBucketOwner(v string) *DeletePublicAccessBlockInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *DeletePublicAccessBlockInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -14575,9 +14856,9 @@ type Destination struct { // must be replicated. Must be specified together with a Metrics block. ReplicationTime *ReplicationTime `type:"structure"` - // The storage class to use when replicating objects, such as standard or reduced - // redundancy. By default, Amazon S3 uses the storage class of the source object - // to create the object replica. + // The storage class to use when replicating objects, such as S3 Standard or + // reduced redundancy. By default, Amazon S3 uses the storage class of the source + // object to create the object replica. // // For valid values, see the StorageClass element of the PUT Bucket replication // (https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTreplication.html) @@ -14794,6 +15075,8 @@ func (s *EndEvent) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *EndEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType)) return msg, err @@ -15331,6 +15614,11 @@ type GetBucketAccelerateConfigurationInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -15372,6 +15660,12 @@ func (s *GetBucketAccelerateConfigurationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketAccelerateConfigurationInput) SetExpectedBucketOwner(v string) *GetBucketAccelerateConfigurationInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetBucketAccelerateConfigurationInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -15416,6 +15710,11 @@ type GetBucketAclInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -15457,6 +15756,12 @@ func (s *GetBucketAclInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketAclInput) SetExpectedBucketOwner(v string) *GetBucketAclInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetBucketAclInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -15511,6 +15816,11 @@ type GetBucketAnalyticsConfigurationInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The ID that identifies the analytics configuration. // // Id is a required field @@ -15559,6 +15869,12 @@ func (s *GetBucketAnalyticsConfigurationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketAnalyticsConfigurationInput) SetExpectedBucketOwner(v string) *GetBucketAnalyticsConfigurationInput { + s.ExpectedBucketOwner = &v + return s +} + // SetId sets the Id field's value. func (s *GetBucketAnalyticsConfigurationInput) SetId(v string) *GetBucketAnalyticsConfigurationInput { s.Id = &v @@ -15609,6 +15925,11 @@ type GetBucketCorsInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -15650,6 +15971,12 @@ func (s *GetBucketCorsInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketCorsInput) SetExpectedBucketOwner(v string) *GetBucketCorsInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetBucketCorsInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -15696,6 +16023,11 @@ type GetBucketEncryptionInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -15737,6 +16069,12 @@ func (s *GetBucketEncryptionInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketEncryptionInput) SetExpectedBucketOwner(v string) *GetBucketEncryptionInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetBucketEncryptionInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -15782,6 +16120,11 @@ type GetBucketInventoryConfigurationInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The ID used to identify the inventory configuration. // // Id is a required field @@ -15830,6 +16173,12 @@ func (s *GetBucketInventoryConfigurationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketInventoryConfigurationInput) SetExpectedBucketOwner(v string) *GetBucketInventoryConfigurationInput { + s.ExpectedBucketOwner = &v + return s +} + // SetId sets the Id field's value. func (s *GetBucketInventoryConfigurationInput) SetId(v string) *GetBucketInventoryConfigurationInput { s.Id = &v @@ -15880,6 +16229,11 @@ type GetBucketLifecycleConfigurationInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -15921,6 +16275,12 @@ func (s *GetBucketLifecycleConfigurationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketLifecycleConfigurationInput) SetExpectedBucketOwner(v string) *GetBucketLifecycleConfigurationInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetBucketLifecycleConfigurationInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -15965,6 +16325,11 @@ type GetBucketLifecycleInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -16006,6 +16371,12 @@ func (s *GetBucketLifecycleInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketLifecycleInput) SetExpectedBucketOwner(v string) *GetBucketLifecycleInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetBucketLifecycleInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -16050,6 +16421,11 @@ type GetBucketLocationInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -16091,6 +16467,12 @@ func (s *GetBucketLocationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketLocationInput) SetExpectedBucketOwner(v string) *GetBucketLocationInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetBucketLocationInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -16110,6 +16492,7 @@ type GetBucketLocationOutput struct { // Specifies the Region where the bucket resides. For a list of all the Amazon // S3 supported location constraints by Region, see Regions and Endpoints (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region). + // Buckets in Region us-east-1 have a LocationConstraint of null. LocationConstraint *string `type:"string" enum:"BucketLocationConstraint"` } @@ -16136,6 +16519,11 @@ type GetBucketLoggingInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -16177,6 +16565,12 @@ func (s *GetBucketLoggingInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketLoggingInput) SetExpectedBucketOwner(v string) *GetBucketLoggingInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetBucketLoggingInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -16225,6 +16619,11 @@ type GetBucketMetricsConfigurationInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The ID used to identify the metrics configuration. // // Id is a required field @@ -16273,6 +16672,12 @@ func (s *GetBucketMetricsConfigurationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketMetricsConfigurationInput) SetExpectedBucketOwner(v string) *GetBucketMetricsConfigurationInput { + s.ExpectedBucketOwner = &v + return s +} + // SetId sets the Id field's value. func (s *GetBucketMetricsConfigurationInput) SetId(v string) *GetBucketMetricsConfigurationInput { s.Id = &v @@ -16319,10 +16724,15 @@ func (s *GetBucketMetricsConfigurationOutput) SetMetricsConfiguration(v *Metrics type GetBucketNotificationConfigurationRequest struct { _ struct{} `locationName:"GetBucketNotificationConfigurationRequest" type:"structure"` - // Name of the bucket for which to get the notification configuration + // Name of the bucket for which to get the notification configuration. // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -16364,6 +16774,12 @@ func (s *GetBucketNotificationConfigurationRequest) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketNotificationConfigurationRequest) SetExpectedBucketOwner(v string) *GetBucketNotificationConfigurationRequest { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetBucketNotificationConfigurationRequest) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -16385,6 +16801,11 @@ type GetBucketPolicyInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -16426,6 +16847,12 @@ func (s *GetBucketPolicyInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketPolicyInput) SetExpectedBucketOwner(v string) *GetBucketPolicyInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetBucketPolicyInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -16470,6 +16897,11 @@ type GetBucketPolicyStatusInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -16511,6 +16943,12 @@ func (s *GetBucketPolicyStatusInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketPolicyStatusInput) SetExpectedBucketOwner(v string) *GetBucketPolicyStatusInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetBucketPolicyStatusInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -16555,6 +16993,11 @@ type GetBucketReplicationInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -16596,6 +17039,12 @@ func (s *GetBucketReplicationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketReplicationInput) SetExpectedBucketOwner(v string) *GetBucketReplicationInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetBucketReplicationInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -16641,6 +17090,11 @@ type GetBucketRequestPaymentInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -16682,6 +17136,12 @@ func (s *GetBucketRequestPaymentInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketRequestPaymentInput) SetExpectedBucketOwner(v string) *GetBucketRequestPaymentInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetBucketRequestPaymentInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -16726,6 +17186,11 @@ type GetBucketTaggingInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -16767,6 +17232,12 @@ func (s *GetBucketTaggingInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketTaggingInput) SetExpectedBucketOwner(v string) *GetBucketTaggingInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetBucketTaggingInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -16813,6 +17284,11 @@ type GetBucketVersioningInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -16854,6 +17330,12 @@ func (s *GetBucketVersioningInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketVersioningInput) SetExpectedBucketOwner(v string) *GetBucketVersioningInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetBucketVersioningInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -16909,6 +17391,11 @@ type GetBucketWebsiteInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -16950,6 +17437,12 @@ func (s *GetBucketWebsiteInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetBucketWebsiteInput) SetExpectedBucketOwner(v string) *GetBucketWebsiteInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetBucketWebsiteInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -16967,10 +17460,10 @@ func (s *GetBucketWebsiteInput) hasEndpointARN() bool { type GetBucketWebsiteOutput struct { _ struct{} `type:"structure"` - // The name of the error document for the website. + // The object key name of the website error document to use for 4XX class errors. ErrorDocument *ErrorDocument `type:"structure"` - // The name of the index document for the website. + // The name of the index document for the website (for example index.html). IndexDocument *IndexDocument `type:"structure"` // Specifies the redirect behavior of all requests to a website endpoint of @@ -17030,6 +17523,11 @@ type GetObjectAclInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The key of the object for which to get the ACL information. // // Key is a required field @@ -17091,6 +17589,12 @@ func (s *GetObjectAclInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetObjectAclInput) SetExpectedBucketOwner(v string) *GetObjectAclInput { + s.ExpectedBucketOwner = &v + return s +} + // SetKey sets the Key field's value. func (s *GetObjectAclInput) SetKey(v string) *GetObjectAclInput { s.Key = &v @@ -17180,6 +17684,11 @@ type GetObjectInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Return the object only if its entity tag (ETag) is the same as the one specified, // otherwise return a 412 (precondition failed). IfMatch *string `location:"header" locationName:"If-Match" type:"string"` @@ -17207,7 +17716,10 @@ type GetObjectInput struct { PartNumber *int64 `location:"querystring" locationName:"partNumber" type:"integer"` // Downloads the specified range bytes of an object. For more information about - // the HTTP Range header, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. + // the HTTP Range header, see https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 + // (https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35). + // + // Amazon S3 doesn't support retrieving multiple ranges of data per GET request. Range *string `location:"header" locationName:"Range" type:"string"` // Confirms that the requester knows that they will be charged for the request. @@ -17242,7 +17754,7 @@ type GetObjectInput struct { // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting // data. This value is used to store the object and then it is discarded; Amazon // S3 does not store the encryption key. The key must be appropriate for use - // with the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm + // with the algorithm specified in the x-amz-server-side-encryption-customer-algorithm // header. SSECustomerKey *string `marshal-as:"blob" location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string" sensitive:"true"` @@ -17300,6 +17812,12 @@ func (s *GetObjectInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetObjectInput) SetExpectedBucketOwner(v string) *GetObjectInput { + s.ExpectedBucketOwner = &v + return s +} + // SetIfMatch sets the IfMatch field's value. func (s *GetObjectInput) SetIfMatch(v string) *GetObjectInput { s.IfMatch = &v @@ -17445,6 +17963,11 @@ type GetObjectLegalHoldInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The key name for the object whose Legal Hold status you want to retrieve. // // Key is a required field @@ -17506,6 +18029,12 @@ func (s *GetObjectLegalHoldInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetObjectLegalHoldInput) SetExpectedBucketOwner(v string) *GetObjectLegalHoldInput { + s.ExpectedBucketOwner = &v + return s +} + // SetKey sets the Key field's value. func (s *GetObjectLegalHoldInput) SetKey(v string) *GetObjectLegalHoldInput { s.Key = &v @@ -17568,6 +18097,11 @@ type GetObjectLockConfigurationInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -17609,6 +18143,12 @@ func (s *GetObjectLockConfigurationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetObjectLockConfigurationInput) SetExpectedBucketOwner(v string) *GetObjectLockConfigurationInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetObjectLockConfigurationInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -17756,7 +18296,7 @@ type GetObjectOutput struct { ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` // Provides storage class information of the object. Amazon S3 returns this - // header for all objects except for Standard storage class objects. + // header for all objects except for S3 Standard storage class objects. StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` // The number of tags, if any, on the object. @@ -17983,6 +18523,11 @@ type GetObjectRetentionInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The key name for the object whose retention settings you want to retrieve. // // Key is a required field @@ -18044,6 +18589,12 @@ func (s *GetObjectRetentionInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetObjectRetentionInput) SetExpectedBucketOwner(v string) *GetObjectRetentionInput { + s.ExpectedBucketOwner = &v + return s +} + // SetKey sets the Key field's value. func (s *GetObjectRetentionInput) SetKey(v string) *GetObjectRetentionInput { s.Key = &v @@ -18114,6 +18665,11 @@ type GetObjectTaggingInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Object key for which to get the tagging information. // // Key is a required field @@ -18168,6 +18724,12 @@ func (s *GetObjectTaggingInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetObjectTaggingInput) SetExpectedBucketOwner(v string) *GetObjectTaggingInput { + s.ExpectedBucketOwner = &v + return s +} + // SetKey sets the Key field's value. func (s *GetObjectTaggingInput) SetKey(v string) *GetObjectTaggingInput { s.Key = &v @@ -18237,6 +18799,11 @@ type GetObjectTorrentInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The object key for which to get the information. // // Key is a required field @@ -18295,6 +18862,12 @@ func (s *GetObjectTorrentInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetObjectTorrentInput) SetExpectedBucketOwner(v string) *GetObjectTorrentInput { + s.ExpectedBucketOwner = &v + return s +} + // SetKey sets the Key field's value. func (s *GetObjectTorrentInput) SetKey(v string) *GetObjectTorrentInput { s.Key = &v @@ -18362,6 +18935,11 @@ type GetPublicAccessBlockInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -18403,6 +18981,12 @@ func (s *GetPublicAccessBlockInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *GetPublicAccessBlockInput) SetExpectedBucketOwner(v string) *GetPublicAccessBlockInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *GetPublicAccessBlockInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -18441,11 +19025,11 @@ func (s *GetPublicAccessBlockOutput) SetPublicAccessBlockConfiguration(v *Public return s } -// Container for Glacier job parameters. +// Container for S3 Glacier job parameters. type GlacierJobParameters struct { _ struct{} `type:"structure"` - // Glacier retrieval tier at which the restore will be processed. + // S3 Glacier retrieval tier at which the restore will be processed. // // Tier is a required field Tier *string `type:"string" required:"true" enum:"Tier"` @@ -18536,6 +19120,29 @@ type Grantee struct { DisplayName *string `type:"string"` // Email address of the grantee. + // + // Using email addresses to specify a grantee is only supported in the following + // AWS Regions: + // + // * US East (N. Virginia) + // + // * US West (N. California) + // + // * US West (Oregon) + // + // * Asia Pacific (Singapore) + // + // * Asia Pacific (Sydney) + // + // * Asia Pacific (Tokyo) + // + // * Europe (Ireland) + // + // * South America (São Paulo) + // + // For a list of all the Amazon S3 supported Regions and endpoints, see Regions + // and Endpoints (https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) + // in the AWS General Reference. EmailAddress *string `type:"string"` // The canonical user ID of the grantee. @@ -18610,6 +19217,11 @@ type HeadBucketInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -18651,6 +19263,12 @@ func (s *HeadBucketInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *HeadBucketInput) SetExpectedBucketOwner(v string) *HeadBucketInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *HeadBucketInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -18687,6 +19305,11 @@ type HeadObjectInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Return the object only if its entity tag (ETag) is the same as the one specified, // otherwise return a 412 (precondition failed). IfMatch *string `location:"header" locationName:"If-Match" type:"string"` @@ -18716,6 +19339,8 @@ type HeadObjectInput struct { // Downloads the specified range bytes of an object. For more information about // the HTTP Range header, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. + // + // Amazon S3 doesn't support retrieving multiple ranges of data per GET request. Range *string `location:"header" locationName:"Range" type:"string"` // Confirms that the requester knows that they will be charged for the request. @@ -18732,7 +19357,7 @@ type HeadObjectInput struct { // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting // data. This value is used to store the object and then it is discarded; Amazon // S3 does not store the encryption key. The key must be appropriate for use - // with the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm + // with the algorithm specified in the x-amz-server-side-encryption-customer-algorithm // header. SSECustomerKey *string `marshal-as:"blob" location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string" sensitive:"true"` @@ -18790,6 +19415,12 @@ func (s *HeadObjectInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *HeadObjectInput) SetExpectedBucketOwner(v string) *HeadObjectInput { + s.ExpectedBucketOwner = &v + return s +} + // SetIfMatch sets the IfMatch field's value. func (s *HeadObjectInput) SetIfMatch(v string) *HeadObjectInput { s.IfMatch = &v @@ -18993,7 +19624,8 @@ type HeadObjectOutput struct { // If the object is an archived object (an object whose storage class is GLACIER), // the response includes this header if either the archive restoration is in - // progress (see RestoreObject or an archive copy is already restored. + // progress (see RestoreObject (https://docs.aws.amazon.com/AmazonS3/latest/API/API_RestoreObject.html) + // or an archive copy is already restored. // // If an archive copy is already restored, the header value indicates when Amazon // S3 is scheduled to delete the object copy. For example: @@ -19029,7 +19661,7 @@ type HeadObjectOutput struct { ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` // Provides storage class information of the object. Amazon S3 returns this - // header for all objects except for Standard storage class objects. + // header for all objects except for S3 Standard storage class objects. // // For more information, see Storage Classes (https://docs.aws.amazon.com/AmazonS3/latest/dev/storage-class-intro.html). StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` @@ -19624,7 +20256,11 @@ func (s *InventoryFilter) SetPrefix(v string) *InventoryFilter { type InventoryS3BucketDestination struct { _ struct{} `type:"structure"` - // The ID of the account that owns the destination bucket. + // The account ID that owns the destination S3 bucket. If no account ID is provided, + // the owner is not validated before exporting data. + // + // Although this value is optional, we strongly recommend that you set it to + // help prevent problems if the destination bucket ownership changes. AccountId *string `type:"string"` // The Amazon Resource Name (ARN) of the bucket where inventory results will @@ -19781,7 +20417,8 @@ func (s *JSONInput) SetType(v string) *JSONInput { type JSONOutput struct { _ struct{} `type:"structure"` - // The value used to separate individual records in the output. + // The value used to separate individual records in the output. If no value + // is specified, Amazon S3 uses a newline character ('\n'). RecordDelimiter *string `type:"string"` } @@ -20265,6 +20902,11 @@ type ListBucketAnalyticsConfigurationsInput struct { // The ContinuationToken that represents a placeholder from where this request // should begin. ContinuationToken *string `location:"querystring" locationName:"continuation-token" type:"string"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -20312,6 +20954,12 @@ func (s *ListBucketAnalyticsConfigurationsInput) SetContinuationToken(v string) return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *ListBucketAnalyticsConfigurationsInput) SetExpectedBucketOwner(v string) *ListBucketAnalyticsConfigurationsInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *ListBucketAnalyticsConfigurationsInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -20394,6 +21042,11 @@ type ListBucketInventoryConfigurationsInput struct { // response to continue the listing. The continuation token is an opaque value // that Amazon S3 understands. ContinuationToken *string `location:"querystring" locationName:"continuation-token" type:"string"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -20441,6 +21094,12 @@ func (s *ListBucketInventoryConfigurationsInput) SetContinuationToken(v string) return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *ListBucketInventoryConfigurationsInput) SetExpectedBucketOwner(v string) *ListBucketInventoryConfigurationsInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *ListBucketInventoryConfigurationsInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -20523,6 +21182,11 @@ type ListBucketMetricsConfigurationsInput struct { // list response to continue the listing. The continuation token is an opaque // value that Amazon S3 understands. ContinuationToken *string `location:"querystring" locationName:"continuation-token" type:"string"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -20570,6 +21234,12 @@ func (s *ListBucketMetricsConfigurationsInput) SetContinuationToken(v string) *L return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *ListBucketMetricsConfigurationsInput) SetExpectedBucketOwner(v string) *ListBucketMetricsConfigurationsInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *ListBucketMetricsConfigurationsInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -20719,6 +21389,11 @@ type ListMultipartUploadsInput struct { // keys in the response. EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string" enum:"EncodingType"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Together with upload-id-marker, this parameter specifies the multipart upload // after which listing should begin. // @@ -20800,6 +21475,12 @@ func (s *ListMultipartUploadsInput) SetEncodingType(v string) *ListMultipartUplo return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *ListMultipartUploadsInput) SetExpectedBucketOwner(v string) *ListMultipartUploadsInput { + s.ExpectedBucketOwner = &v + return s +} + // SetKeyMarker sets the KeyMarker field's value. func (s *ListMultipartUploadsInput) SetKeyMarker(v string) *ListMultipartUploadsInput { s.KeyMarker = &v @@ -21014,14 +21695,20 @@ type ListObjectVersionsInput struct { // keys in the response. EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string" enum:"EncodingType"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Specifies the key to start with when listing objects in a bucket. KeyMarker *string `location:"querystring" locationName:"key-marker" type:"string"` - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. If additional keys satisfy - // the search criteria, but were not returned because max-keys was exceeded, - // the response contains true. To return the additional - // keys, see key-marker and version-id-marker. + // Sets the maximum number of keys returned in the response. By default the + // API returns up to 1,000 key names. The response might contain fewer keys + // but will never contain more. If additional keys satisfy the search criteria, + // but were not returned because max-keys was exceeded, the response contains + // true. To return the additional keys, see key-marker + // and version-id-marker. MaxKeys *int64 `location:"querystring" locationName:"max-keys" type:"integer"` // Use this parameter to select only those keys that begin with the specified @@ -21086,6 +21773,12 @@ func (s *ListObjectVersionsInput) SetEncodingType(v string) *ListObjectVersionsI return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *ListObjectVersionsInput) SetExpectedBucketOwner(v string) *ListObjectVersionsInput { + s.ExpectedBucketOwner = &v + return s +} + // SetKeyMarker sets the KeyMarker field's value. func (s *ListObjectVersionsInput) SetKeyMarker(v string) *ListObjectVersionsInput { s.KeyMarker = &v @@ -21295,11 +21988,17 @@ type ListObjectsInput struct { // keys in the response. EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string" enum:"EncodingType"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Specifies the key to start with when listing objects in a bucket. Marker *string `location:"querystring" locationName:"marker" type:"string"` - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. + // Sets the maximum number of keys returned in the response. By default the + // API returns up to 1,000 key names. The response might contain fewer keys + // but will never contain more. MaxKeys *int64 `location:"querystring" locationName:"max-keys" type:"integer"` // Limits the response to keys that begin with the specified prefix. @@ -21362,6 +22061,12 @@ func (s *ListObjectsInput) SetEncodingType(v string) *ListObjectsInput { return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *ListObjectsInput) SetExpectedBucketOwner(v string) *ListObjectsInput { + s.ExpectedBucketOwner = &v + return s +} + // SetMarker sets the Marker field's value. func (s *ListObjectsInput) SetMarker(v string) *ListObjectsInput { s.Marker = &v @@ -21451,7 +22156,7 @@ type ListObjectsOutput struct { // is true), you can use the key name in this field as marker in the subsequent // request to get next set of objects. Amazon S3 lists objects in alphabetical // order Note: This element is returned only if you have delimiter request parameter - // specified. If response does not include the NextMaker and it is truncated, + // specified. If response does not include the NextMarker and it is truncated, // you can use the value of the last Key in the response as the marker in the // subsequent request to get the next set of object keys. NextMarker *string `type:"string"` @@ -21556,13 +22261,19 @@ type ListObjectsV2Input struct { // Encoding type used by Amazon S3 to encode object keys in the response. EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string" enum:"EncodingType"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The owner field is not present in listV2 by default, if you want to return // owner field with each key in the result then set the fetch owner field to // true. FetchOwner *bool `location:"querystring" locationName:"fetch-owner" type:"boolean"` - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. + // Sets the maximum number of keys returned in the response. By default the + // API returns up to 1,000 key names. The response might contain fewer keys + // but will never contain more. MaxKeys *int64 `location:"querystring" locationName:"max-keys" type:"integer"` // Limits the response to keys that begin with the specified prefix. @@ -21635,6 +22346,12 @@ func (s *ListObjectsV2Input) SetEncodingType(v string) *ListObjectsV2Input { return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *ListObjectsV2Input) SetExpectedBucketOwner(v string) *ListObjectsV2Input { + s.ExpectedBucketOwner = &v + return s +} + // SetFetchOwner sets the FetchOwner field's value. func (s *ListObjectsV2Input) SetFetchOwner(v bool) *ListObjectsV2Input { s.FetchOwner = &v @@ -21731,8 +22448,9 @@ type ListObjectsV2Output struct { // result will include less than equals 50 keys KeyCount *int64 `type:"integer"` - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. + // Sets the maximum number of keys returned in the response. By default the + // API returns up to 1,000 key names. The response might contain fewer keys + // but will never contain more. MaxKeys *int64 `type:"integer"` // Bucket name. @@ -21855,6 +22573,11 @@ type ListPartsInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Object key for which the multipart upload was initiated. // // Key is a required field @@ -21928,6 +22651,12 @@ func (s *ListPartsInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *ListPartsInput) SetExpectedBucketOwner(v string) *ListPartsInput { + s.ExpectedBucketOwner = &v + return s +} + // SetKey sets the Key field's value. func (s *ListPartsInput) SetKey(v string) *ListPartsInput { s.Key = &v @@ -22929,8 +23658,22 @@ func (s *NotificationConfigurationFilter) SetKey(v *KeyFilter) *NotificationConf type Object struct { _ struct{} `type:"structure"` - // The entity tag is an MD5 hash of the object. ETag reflects only changes to - // the contents of an object, not its metadata. + // The entity tag is a hash of the object. The ETag reflects changes only to + // the contents of an object, not its metadata. The ETag may or may not be an + // MD5 digest of the object data. Whether or not it is depends on how the object + // was created and how it is encrypted as described below: + // + // * Objects created by the PUT Object, POST Object, or Copy operation, or + // through the AWS Management Console, and are encrypted by SSE-S3 or plaintext, + // have ETags that are an MD5 digest of their object data. + // + // * Objects created by the PUT Object, POST Object, or Copy operation, or + // through the AWS Management Console, and are encrypted by SSE-C or SSE-KMS, + // have ETags that are not an MD5 digest of their object data. + // + // * If an object is created by either the Multipart Upload or Part Copy + // operation, the ETag is not an MD5 digest, regardless of the method of + // encryption. ETag *string `type:"string"` // The name that you assign to an object. You use the object key to retrieve @@ -23530,6 +24273,8 @@ func (s *ProgressEvent) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *ProgressEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType)) var buf bytes.Buffer @@ -23634,6 +24379,11 @@ type PutBucketAccelerateConfigurationInput struct { // // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -23684,6 +24434,12 @@ func (s *PutBucketAccelerateConfigurationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketAccelerateConfigurationInput) SetExpectedBucketOwner(v string) *PutBucketAccelerateConfigurationInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *PutBucketAccelerateConfigurationInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -23726,6 +24482,11 @@ type PutBucketAclInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Allows grantee the read, write, read ACP, and write ACP permissions on the // bucket. GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` @@ -23799,6 +24560,12 @@ func (s *PutBucketAclInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketAclInput) SetExpectedBucketOwner(v string) *PutBucketAclInput { + s.ExpectedBucketOwner = &v + return s +} + // SetGrantFullControl sets the GrantFullControl field's value. func (s *PutBucketAclInput) SetGrantFullControl(v string) *PutBucketAclInput { s.GrantFullControl = &v @@ -23870,6 +24637,11 @@ type PutBucketAnalyticsConfigurationInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The ID that identifies the analytics configuration. // // Id is a required field @@ -23932,6 +24704,12 @@ func (s *PutBucketAnalyticsConfigurationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketAnalyticsConfigurationInput) SetExpectedBucketOwner(v string) *PutBucketAnalyticsConfigurationInput { + s.ExpectedBucketOwner = &v + return s +} + // SetId sets the Id field's value. func (s *PutBucketAnalyticsConfigurationInput) SetId(v string) *PutBucketAnalyticsConfigurationInput { s.Id = &v @@ -23976,11 +24754,16 @@ type PutBucketCorsInput struct { // Describes the cross-origin access configuration for objects in an Amazon // S3 bucket. For more information, see Enabling Cross-Origin Resource Sharing - // (https://docs.aws.amazon.com/AmazonS3/latest/dev//cors.html) in the Amazon + // (https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html) in the Amazon // Simple Storage Service Developer Guide. // // CORSConfiguration is a required field CORSConfiguration *CORSConfiguration `locationName:"CORSConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -24036,6 +24819,12 @@ func (s *PutBucketCorsInput) SetCORSConfiguration(v *CORSConfiguration) *PutBuck return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketCorsInput) SetExpectedBucketOwner(v string) *PutBucketCorsInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *PutBucketCorsInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -24076,6 +24865,11 @@ type PutBucketEncryptionInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Specifies the default server-side-encryption configuration. // // ServerSideEncryptionConfiguration is a required field @@ -24129,6 +24923,12 @@ func (s *PutBucketEncryptionInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketEncryptionInput) SetExpectedBucketOwner(v string) *PutBucketEncryptionInput { + s.ExpectedBucketOwner = &v + return s +} + // SetServerSideEncryptionConfiguration sets the ServerSideEncryptionConfiguration field's value. func (s *PutBucketEncryptionInput) SetServerSideEncryptionConfiguration(v *ServerSideEncryptionConfiguration) *PutBucketEncryptionInput { s.ServerSideEncryptionConfiguration = v @@ -24171,6 +24971,11 @@ type PutBucketInventoryConfigurationInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The ID used to identify the inventory configuration. // // Id is a required field @@ -24232,6 +25037,12 @@ func (s *PutBucketInventoryConfigurationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketInventoryConfigurationInput) SetExpectedBucketOwner(v string) *PutBucketInventoryConfigurationInput { + s.ExpectedBucketOwner = &v + return s +} + // SetId sets the Id field's value. func (s *PutBucketInventoryConfigurationInput) SetId(v string) *PutBucketInventoryConfigurationInput { s.Id = &v @@ -24280,6 +25091,11 @@ type PutBucketLifecycleConfigurationInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Container for lifecycle rules. You can add as many as 1,000 rules. LifecycleConfiguration *BucketLifecycleConfiguration `locationName:"LifecycleConfiguration" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` } @@ -24328,6 +25144,12 @@ func (s *PutBucketLifecycleConfigurationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketLifecycleConfigurationInput) SetExpectedBucketOwner(v string) *PutBucketLifecycleConfigurationInput { + s.ExpectedBucketOwner = &v + return s +} + // SetLifecycleConfiguration sets the LifecycleConfiguration field's value. func (s *PutBucketLifecycleConfigurationInput) SetLifecycleConfiguration(v *BucketLifecycleConfiguration) *PutBucketLifecycleConfigurationInput { s.LifecycleConfiguration = v @@ -24368,6 +25190,11 @@ type PutBucketLifecycleInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Container for lifecycle rules. You can add as many as 1000 rules. LifecycleConfiguration *LifecycleConfiguration `locationName:"LifecycleConfiguration" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` } @@ -24416,6 +25243,12 @@ func (s *PutBucketLifecycleInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketLifecycleInput) SetExpectedBucketOwner(v string) *PutBucketLifecycleInput { + s.ExpectedBucketOwner = &v + return s +} + // SetLifecycleConfiguration sets the LifecycleConfiguration field's value. func (s *PutBucketLifecycleInput) SetLifecycleConfiguration(v *LifecycleConfiguration) *PutBucketLifecycleInput { s.LifecycleConfiguration = v @@ -24462,6 +25295,11 @@ type PutBucketLoggingInput struct { // // BucketLoggingStatus is a required field BucketLoggingStatus *BucketLoggingStatus `locationName:"BucketLoggingStatus" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` + + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` } // String returns the string representation @@ -24517,6 +25355,12 @@ func (s *PutBucketLoggingInput) SetBucketLoggingStatus(v *BucketLoggingStatus) * return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketLoggingInput) SetExpectedBucketOwner(v string) *PutBucketLoggingInput { + s.ExpectedBucketOwner = &v + return s +} + func (s *PutBucketLoggingInput) getEndpointARN() (arn.Resource, error) { if s.Bucket == nil { return nil, fmt.Errorf("member Bucket is nil") @@ -24553,6 +25397,11 @@ type PutBucketMetricsConfigurationInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The ID used to identify the metrics configuration. // // Id is a required field @@ -24614,6 +25463,12 @@ func (s *PutBucketMetricsConfigurationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketMetricsConfigurationInput) SetExpectedBucketOwner(v string) *PutBucketMetricsConfigurationInput { + s.ExpectedBucketOwner = &v + return s +} + // SetId sets the Id field's value. func (s *PutBucketMetricsConfigurationInput) SetId(v string) *PutBucketMetricsConfigurationInput { s.Id = &v @@ -24662,6 +25517,11 @@ type PutBucketNotificationConfigurationInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // A container for specifying the notification configuration of the bucket. // If this element is empty, notifications are turned off for the bucket. // @@ -24716,6 +25576,12 @@ func (s *PutBucketNotificationConfigurationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketNotificationConfigurationInput) SetExpectedBucketOwner(v string) *PutBucketNotificationConfigurationInput { + s.ExpectedBucketOwner = &v + return s +} + // SetNotificationConfiguration sets the NotificationConfiguration field's value. func (s *PutBucketNotificationConfigurationInput) SetNotificationConfiguration(v *NotificationConfiguration) *PutBucketNotificationConfigurationInput { s.NotificationConfiguration = v @@ -24758,6 +25624,11 @@ type PutBucketNotificationInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The container for the configuration. // // NotificationConfiguration is a required field @@ -24806,6 +25677,12 @@ func (s *PutBucketNotificationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketNotificationInput) SetExpectedBucketOwner(v string) *PutBucketNotificationInput { + s.ExpectedBucketOwner = &v + return s +} + // SetNotificationConfiguration sets the NotificationConfiguration field's value. func (s *PutBucketNotificationInput) SetNotificationConfiguration(v *NotificationConfigurationDeprecated) *PutBucketNotificationInput { s.NotificationConfiguration = v @@ -24852,6 +25729,11 @@ type PutBucketPolicyInput struct { // to change this bucket policy in the future. ConfirmRemoveSelfBucketAccess *bool `location:"header" locationName:"x-amz-confirm-remove-self-bucket-access" type:"boolean"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The bucket policy as a JSON document. // // Policy is a required field @@ -24906,6 +25788,12 @@ func (s *PutBucketPolicyInput) SetConfirmRemoveSelfBucketAccess(v bool) *PutBuck return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketPolicyInput) SetExpectedBucketOwner(v string) *PutBucketPolicyInput { + s.ExpectedBucketOwner = &v + return s +} + // SetPolicy sets the Policy field's value. func (s *PutBucketPolicyInput) SetPolicy(v string) *PutBucketPolicyInput { s.Policy = &v @@ -24948,6 +25836,11 @@ type PutBucketReplicationInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // A container for replication rules. You can add up to 1,000 rules. The maximum // size of a replication configuration is 2 MB. // @@ -25004,6 +25897,12 @@ func (s *PutBucketReplicationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketReplicationInput) SetExpectedBucketOwner(v string) *PutBucketReplicationInput { + s.ExpectedBucketOwner = &v + return s +} + // SetReplicationConfiguration sets the ReplicationConfiguration field's value. func (s *PutBucketReplicationInput) SetReplicationConfiguration(v *ReplicationConfiguration) *PutBucketReplicationInput { s.ReplicationConfiguration = v @@ -25052,6 +25951,11 @@ type PutBucketRequestPaymentInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Container for Payer. // // RequestPaymentConfiguration is a required field @@ -25105,6 +26009,12 @@ func (s *PutBucketRequestPaymentInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketRequestPaymentInput) SetExpectedBucketOwner(v string) *PutBucketRequestPaymentInput { + s.ExpectedBucketOwner = &v + return s +} + // SetRequestPaymentConfiguration sets the RequestPaymentConfiguration field's value. func (s *PutBucketRequestPaymentInput) SetRequestPaymentConfiguration(v *RequestPaymentConfiguration) *PutBucketRequestPaymentInput { s.RequestPaymentConfiguration = v @@ -25147,6 +26057,11 @@ type PutBucketTaggingInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Container for the TagSet and Tag elements. // // Tagging is a required field @@ -25200,6 +26115,12 @@ func (s *PutBucketTaggingInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketTaggingInput) SetExpectedBucketOwner(v string) *PutBucketTaggingInput { + s.ExpectedBucketOwner = &v + return s +} + // SetTagging sets the Tagging field's value. func (s *PutBucketTaggingInput) SetTagging(v *Tagging) *PutBucketTaggingInput { s.Tagging = v @@ -25242,6 +26163,11 @@ type PutBucketVersioningInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The concatenation of the authentication device's serial number, a space, // and the value that is displayed on your authentication device. MFA *string `location:"header" locationName:"x-amz-mfa" type:"string"` @@ -25294,6 +26220,12 @@ func (s *PutBucketVersioningInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketVersioningInput) SetExpectedBucketOwner(v string) *PutBucketVersioningInput { + s.ExpectedBucketOwner = &v + return s +} + // SetMFA sets the MFA field's value. func (s *PutBucketVersioningInput) SetMFA(v string) *PutBucketVersioningInput { s.MFA = &v @@ -25342,6 +26274,11 @@ type PutBucketWebsiteInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Container for the request. // // WebsiteConfiguration is a required field @@ -25395,6 +26332,12 @@ func (s *PutBucketWebsiteInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutBucketWebsiteInput) SetExpectedBucketOwner(v string) *PutBucketWebsiteInput { + s.ExpectedBucketOwner = &v + return s +} + // SetWebsiteConfiguration sets the WebsiteConfiguration field's value. func (s *PutBucketWebsiteInput) SetWebsiteConfiguration(v *WebsiteConfiguration) *PutBucketWebsiteInput { s.WebsiteConfiguration = v @@ -25452,6 +26395,11 @@ type PutObjectAclInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Allows grantee the read, write, read ACP, and write ACP permissions on the // bucket. GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` @@ -25546,6 +26494,12 @@ func (s *PutObjectAclInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutObjectAclInput) SetExpectedBucketOwner(v string) *PutObjectAclInput { + s.ExpectedBucketOwner = &v + return s +} + // SetGrantFullControl sets the GrantFullControl field's value. func (s *PutObjectAclInput) SetGrantFullControl(v string) *PutObjectAclInput { s.GrantFullControl = &v @@ -25689,6 +26643,11 @@ type PutObjectInput struct { // see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17). ContentType *string `location:"header" locationName:"Content-Type" type:"string"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The date and time at which the object is no longer cacheable. For more information, // see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21). Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp"` @@ -25737,7 +26696,7 @@ type PutObjectInput struct { // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting // data. This value is used to store the object and then it is discarded; Amazon // S3 does not store the encryption key. The key must be appropriate for use - // with the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm + // with the algorithm specified in the x-amz-server-side-encryption-customer-algorithm // header. SSECustomerKey *string `marshal-as:"blob" location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string" sensitive:"true"` @@ -25767,8 +26726,8 @@ type PutObjectInput struct { // S3 (for example, AES256, aws:kms). ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` - // If you don't specify, Standard is the default storage class. Amazon S3 supports - // other storage classes. + // If you don't specify, S3 Standard is the default storage class. Amazon S3 + // supports other storage classes. StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` // The tag-set for the object. The tag-set must be encoded as URL Query parameters. @@ -25895,6 +26854,12 @@ func (s *PutObjectInput) SetContentType(v string) *PutObjectInput { return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutObjectInput) SetExpectedBucketOwner(v string) *PutObjectInput { + s.ExpectedBucketOwner = &v + return s +} + // SetExpires sets the Expires field's value. func (s *PutObjectInput) SetExpires(v time.Time) *PutObjectInput { s.Expires = &v @@ -26052,6 +27017,11 @@ type PutObjectLegalHoldInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The key name for the object that you want to place a Legal Hold on. // // Key is a required field @@ -26117,6 +27087,12 @@ func (s *PutObjectLegalHoldInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutObjectLegalHoldInput) SetExpectedBucketOwner(v string) *PutObjectLegalHoldInput { + s.ExpectedBucketOwner = &v + return s +} + // SetKey sets the Key field's value. func (s *PutObjectLegalHoldInput) SetKey(v string) *PutObjectLegalHoldInput { s.Key = &v @@ -26187,6 +27163,11 @@ type PutObjectLockConfigurationInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The Object Lock configuration that you want to apply to the specified bucket. ObjectLockConfiguration *ObjectLockConfiguration `locationName:"ObjectLockConfiguration" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` @@ -26240,6 +27221,12 @@ func (s *PutObjectLockConfigurationInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutObjectLockConfigurationInput) SetExpectedBucketOwner(v string) *PutObjectLockConfigurationInput { + s.ExpectedBucketOwner = &v + return s +} + // SetObjectLockConfiguration sets the ObjectLockConfiguration field's value. func (s *PutObjectLockConfigurationInput) SetObjectLockConfiguration(v *ObjectLockConfiguration) *PutObjectLockConfigurationInput { s.ObjectLockConfiguration = v @@ -26302,7 +27289,8 @@ type PutObjectOutput struct { // Entity tag for the uploaded object. ETag *string `location:"header" locationName:"ETag" type:"string"` - // If the expiration is configured for the object (see PutBucketLifecycleConfiguration), + // If the expiration is configured for the object (see PutBucketLifecycleConfiguration + // (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLifecycleConfiguration.html)), // the response includes this header. It includes the expiry-date and rule-id // key-value pairs that provide information about object expiration. The value // of the rule-id is URL encoded. @@ -26426,6 +27414,11 @@ type PutObjectRetentionInput struct { // Indicates whether this operation should bypass Governance-mode restrictions. BypassGovernanceRetention *bool `location:"header" locationName:"x-amz-bypass-governance-retention" type:"boolean"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The key name for the object that you want to apply this Object Retention // configuration to. // @@ -26498,6 +27491,12 @@ func (s *PutObjectRetentionInput) SetBypassGovernanceRetention(v bool) *PutObjec return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutObjectRetentionInput) SetExpectedBucketOwner(v string) *PutObjectRetentionInput { + s.ExpectedBucketOwner = &v + return s +} + // SetKey sets the Key field's value. func (s *PutObjectRetentionInput) SetKey(v string) *PutObjectRetentionInput { s.Key = &v @@ -26575,7 +27574,12 @@ type PutObjectTaggingInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // Name of the tag. + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + + // Name of the object key. // // Key is a required field Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` @@ -26642,6 +27646,12 @@ func (s *PutObjectTaggingInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutObjectTaggingInput) SetExpectedBucketOwner(v string) *PutObjectTaggingInput { + s.ExpectedBucketOwner = &v + return s +} + // SetKey sets the Key field's value. func (s *PutObjectTaggingInput) SetKey(v string) *PutObjectTaggingInput { s.Key = &v @@ -26706,6 +27716,11 @@ type PutPublicAccessBlockInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The PublicAccessBlock configuration that you want to apply to this Amazon // S3 bucket. You can enable the configuration options in any combination. For // more information about when Amazon S3 considers a bucket or object public, @@ -26758,6 +27773,12 @@ func (s *PutPublicAccessBlockInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *PutPublicAccessBlockInput) SetExpectedBucketOwner(v string) *PutPublicAccessBlockInput { + s.ExpectedBucketOwner = &v + return s +} + // SetPublicAccessBlockConfiguration sets the PublicAccessBlockConfiguration field's value. func (s *PutPublicAccessBlockInput) SetPublicAccessBlockConfiguration(v *PublicAccessBlockConfiguration) *PutPublicAccessBlockInput { s.PublicAccessBlockConfiguration = v @@ -26868,10 +27889,10 @@ func (s *QueueConfiguration) SetQueueArn(v string) *QueueConfiguration { return s } -// This data type is deprecated. Use QueueConfiguration for the same purposes. -// This data type specifies the configuration for publishing messages to an -// Amazon Simple Queue Service (Amazon SQS) queue when Amazon S3 detects specified -// events. +// This data type is deprecated. Use QueueConfiguration (https://docs.aws.amazon.com/AmazonS3/latest/API/API_QueueConfiguration.html) +// for the same purposes. This data type specifies the configuration for publishing +// messages to an Amazon Simple Queue Service (Amazon SQS) queue when Amazon +// S3 detects specified events. type QueueConfigurationDeprecated struct { _ struct{} `type:"structure"` @@ -26966,6 +27987,8 @@ func (s *RecordsEvent) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *RecordsEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType)) msg.Headers.Set(":content-type", eventstream.StringValue("application/octet-stream")) @@ -27632,6 +28655,11 @@ type RestoreObjectInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Object key for which the operation was initiated. // // Key is a required field @@ -27701,6 +28729,12 @@ func (s *RestoreObjectInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *RestoreObjectInput) SetExpectedBucketOwner(v string) *RestoreObjectInput { + s.ExpectedBucketOwner = &v + return s +} + // SetKey sets the Key field's value. func (s *RestoreObjectInput) SetKey(v string) *RestoreObjectInput { s.Key = &v @@ -27784,7 +28818,7 @@ type RestoreRequest struct { // The optional description for the job. Description *string `type:"string"` - // Glacier related parameters pertaining to this job. Do not use with restores + // S3 Glacier related parameters pertaining to this job. Do not use with restores // that specify OutputLocation. GlacierJobParameters *GlacierJobParameters `type:"structure"` @@ -27794,7 +28828,7 @@ type RestoreRequest struct { // Describes the parameters for Select job types. SelectParameters *SelectParameters `type:"structure"` - // Glacier retrieval tier at which the restore will be processed. + // S3 Glacier retrieval tier at which the restore will be processed. Tier *string `type:"string" enum:"Tier"` // Type of restore request. @@ -27878,7 +28912,10 @@ func (s *RestoreRequest) SetType(v string) *RestoreRequest { return s } -// Specifies the redirect behavior and when a redirect is applied. +// Specifies the redirect behavior and when a redirect is applied. For more +// information about routing rules, see Configuring advanced conditional redirects +// (https://docs.aws.amazon.com/AmazonS3/latest/dev/how-to-page-redirect.html#advanced-conditional-redirects) +// in the Amazon Simple Storage Service Developer Guide. type RoutingRule struct { _ struct{} `type:"structure"` @@ -27932,8 +28969,9 @@ func (s *RoutingRule) SetRedirect(v *Redirect) *RoutingRule { } // Specifies lifecycle rules for an Amazon S3 bucket. For more information, -// see PUT Bucket lifecycle (https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlifecycle.html) -// in the Amazon Simple Storage Service API Reference. +// see Put Bucket Lifecycle Configuration (https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlifecycle.html) +// in the Amazon Simple Storage Service API Reference. For examples, see Put +// Bucket Lifecycle Configuration Examples (https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLifecycleConfiguration.html#API_PutBucketLifecycleConfiguration_Examples) type Rule struct { _ struct{} `type:"structure"` @@ -27978,7 +29016,10 @@ type Rule struct { // Status is a required field Status *string `type:"string" required:"true" enum:"ExpirationStatus"` - // Specifies when an object transitions to a specified storage class. + // Specifies when an object transitions to a specified storage class. For more + // information about Amazon S3 lifecycle configuration rules, see Transitioning + // Objects Using Amazon S3 Lifecycle (https://docs.aws.amazon.com/AmazonS3/latest/dev/lifecycle-transition-general-considerations.html) + // in the Amazon Simple Storage Service Developer Guide. Transition *Transition `type:"structure"` } @@ -28182,6 +29223,7 @@ type SelectObjectContentEventStreamEvent interface { // * ProgressEvent // * RecordsEvent // * StatsEvent +// * SelectObjectContentEventStreamUnknownEvent type SelectObjectContentEventStreamReader interface { // Returns a channel of events as they are read from the event stream. Events() <-chan SelectObjectContentEventStreamEvent @@ -28256,6 +29298,9 @@ func (r *readSelectObjectContentEventStream) readEventStream() { return default: } + if _, ok := err.(*eventstreamapi.UnknownMessageTypeError); ok { + continue + } r.err.SetError(err) return } @@ -28285,14 +29330,39 @@ func (u unmarshalerForSelectObjectContentEventStreamEvent) UnmarshalerForEventNa case "Stats": return &StatsEvent{}, nil default: - return nil, awserr.New( - request.ErrCodeSerialization, - fmt.Sprintf("unknown event type name, %s, for SelectObjectContentEventStream", eventType), - nil, - ) + return &SelectObjectContentEventStreamUnknownEvent{Type: eventType}, nil } } +// SelectObjectContentEventStreamUnknownEvent provides a failsafe event for the +// SelectObjectContentEventStream group of events when an unknown event is received. +type SelectObjectContentEventStreamUnknownEvent struct { + Type string + Message eventstream.Message +} + +// The SelectObjectContentEventStreamUnknownEvent is and event in the SelectObjectContentEventStream +// group of events. +func (s *SelectObjectContentEventStreamUnknownEvent) eventSelectObjectContentEventStream() {} + +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. +func (e *SelectObjectContentEventStreamUnknownEvent) MarshalEvent(pm protocol.PayloadMarshaler) ( + msg eventstream.Message, err error, +) { + return e.Message.Clone(), nil +} + +// UnmarshalEvent unmarshals the EventStream Message into the SelectObjectContentEventStreamData value. +// This method is only used internally within the SDK's EventStream handling. +func (e *SelectObjectContentEventStreamUnknownEvent) UnmarshalEvent( + payloadUnmarshaler protocol.PayloadUnmarshaler, + msg eventstream.Message, +) error { + e.Message = msg.Clone() + return nil +} + // Request to filter the contents of an Amazon S3 object based on a simple Structured // Query Language (SQL) statement. In the request, along with the SQL expression, // you must specify a data serialization format (JSON or CSV) of the object. @@ -28308,6 +29378,11 @@ type SelectObjectContentInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The expression that is used to query the object. // // Expression is a required field @@ -28424,6 +29499,12 @@ func (s *SelectObjectContentInput) getBucket() (v string) { return *s.Bucket } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *SelectObjectContentInput) SetExpectedBucketOwner(v string) *SelectObjectContentInput { + s.ExpectedBucketOwner = &v + return s +} + // SetExpression sets the Expression field's value. func (s *SelectObjectContentInput) SetExpression(v string) *SelectObjectContentInput { s.Expression = &v @@ -28623,8 +29704,24 @@ func (s *SelectParameters) SetOutputSerialization(v *OutputSerialization) *Selec type ServerSideEncryptionByDefault struct { _ struct{} `type:"structure"` - // KMS master key ID to use for the default encryption. This parameter is allowed - // if and only if SSEAlgorithm is set to aws:kms. + // AWS Key Management Service (KMS) customer master key ID to use for the default + // encryption. This parameter is allowed if and only if SSEAlgorithm is set + // to aws:kms. + // + // You can specify the key ID or the Amazon Resource Name (ARN) of the CMK. + // However, if you are using encryption with cross-account operations, you must + // use a fully qualified CMK ARN. For more information, see Using encryption + // for cross-account operations (https://docs.aws.amazon.com/AmazonS3/latest/dev/bucket-encryption.html#bucket-encryption-update-bucket-policy). + // + // For example: + // + // * Key ID: 1234abcd-12ab-34cd-56ef-1234567890ab + // + // * Key ARN: arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab + // + // Amazon S3 only supports symmetric CMKs and not asymmetric CMKs. For more + // information, see Using Symmetric and Asymmetric Keys (https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html) + // in the AWS Key Management Service Developer Guide. KMSMasterKeyID *string `type:"string" sensitive:"true"` // Server-side encryption algorithm to use for the default encryption. @@ -28928,6 +30025,8 @@ func (s *StatsEvent) UnmarshalEvent( return nil } +// MarshalEvent marshals the type into an stream event value. This method +// should only used internally within the SDK's EventStream handling. func (s *StatsEvent) MarshalEvent(pm protocol.PayloadMarshaler) (msg eventstream.Message, err error) { msg.Headers.Set(eventstreamapi.MessageTypeHeader, eventstream.StringValue(eventstreamapi.EventMessageType)) var buf bytes.Buffer @@ -29043,7 +30142,7 @@ func (s *StorageClassAnalysisDataExport) SetOutputSchemaVersion(v string) *Stora type Tag struct { _ struct{} `type:"structure"` - // Name of the tag. + // Name of the object key. // // Key is a required field Key *string `min:"1" type:"string" required:"true"` @@ -29274,6 +30373,7 @@ func (s *TopicConfiguration) SetTopicArn(v string) *TopicConfiguration { // A container for specifying the configuration for publication of messages // to an Amazon Simple Notification Service (Amazon SNS) topic when Amazon S3 // detects specified events. This data type is deprecated. Use TopicConfiguration +// (https://docs.aws.amazon.com/AmazonS3/latest/API/API_TopicConfiguration.html) // instead. type TopicConfigurationDeprecated struct { _ struct{} `type:"structure"` @@ -29329,7 +30429,10 @@ func (s *TopicConfigurationDeprecated) SetTopic(v string) *TopicConfigurationDep return s } -// Specifies when an object transitions to a specified storage class. +// Specifies when an object transitions to a specified storage class. For more +// information about Amazon S3 lifecycle configuration rules, see Transitioning +// Objects Using Amazon S3 Lifecycle (https://docs.aws.amazon.com/AmazonS3/latest/dev/lifecycle-transition-general-considerations.html) +// in the Amazon Simple Storage Service Developer Guide. type Transition struct { _ struct{} `type:"structure"` @@ -29381,8 +30484,29 @@ type UploadPartCopyInput struct { // Bucket is a required field Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - // The name of the source bucket and key name of the source object, separated - // by a slash (/). Must be URL-encoded. + // Specifies the source object for the copy operation. You specify the value + // in one of two formats, depending on whether you want to access the source + // object through an access point (https://docs.aws.amazon.com/AmazonS3/latest/dev/access-points.html): + // + // * For objects not accessed through an access point, specify the name of + // the source bucket and key of the source object, separated by a slash (/). + // For example, to copy the object reports/january.pdf from the bucket awsexamplebucket, + // use awsexamplebucket/reports/january.pdf. The value must be URL encoded. + // + // * For objects accessed through access points, specify the Amazon Resource + // Name (ARN) of the object as accessed through the access point, in the + // format arn:aws:s3:::accesspoint//object/. + // For example, to copy the object reports/january.pdf through the access + // point my-access-point owned by account 123456789012 in Region us-west-2, + // use the URL encoding of arn:aws:s3:us-west-2:123456789012:accesspoint/my-access-point/object/reports/january.pdf. + // The value must be URL encoded. Amazon S3 supports copy operations using + // access points only when the source and destination buckets are in the + // same AWS Region. + // + // To copy a specific version of an object, append ?versionId= to + // the value (for example, awsexamplebucket/reports/january.pdf?versionId=QUpfdndhfd8438MNFDN93jdnJFkdmqnh893). + // If you don't specify a version ID, Amazon S3 copies the latest version of + // the source object. // // CopySource is a required field CopySource *string `location:"header" locationName:"x-amz-copy-source" type:"string" required:"true"` @@ -29421,6 +30545,16 @@ type UploadPartCopyInput struct { // encryption key was transmitted without error. CopySourceSSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-key-MD5" type:"string"` + // The account id of the expected destination bucket owner. If the destination + // bucket is owned by a different account, the request will fail with an HTTP + // 403 (Access Denied) error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + + // The account id of the expected source bucket owner. If the source bucket + // is owned by a different account, the request will fail with an HTTP 403 (Access + // Denied) error. + ExpectedSourceBucketOwner *string `location:"header" locationName:"x-amz-source-expected-bucket-owner" type:"string"` + // Object key for which the multipart upload was initiated. // // Key is a required field @@ -29446,7 +30580,7 @@ type UploadPartCopyInput struct { // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting // data. This value is used to store the object and then it is discarded; Amazon // S3 does not store the encryption key. The key must be appropriate for use - // with the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm + // with the algorithm specified in the x-amz-server-side-encryption-customer-algorithm // header. This must be the same encryption key specified in the initiate multipart // upload request. SSECustomerKey *string `marshal-as:"blob" location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string" sensitive:"true"` @@ -29577,6 +30711,18 @@ func (s *UploadPartCopyInput) SetCopySourceSSECustomerKeyMD5(v string) *UploadPa return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *UploadPartCopyInput) SetExpectedBucketOwner(v string) *UploadPartCopyInput { + s.ExpectedBucketOwner = &v + return s +} + +// SetExpectedSourceBucketOwner sets the ExpectedSourceBucketOwner field's value. +func (s *UploadPartCopyInput) SetExpectedSourceBucketOwner(v string) *UploadPartCopyInput { + s.ExpectedSourceBucketOwner = &v + return s +} + // SetKey sets the Key field's value. func (s *UploadPartCopyInput) SetKey(v string) *UploadPartCopyInput { s.Key = &v @@ -29746,6 +30892,11 @@ type UploadPartInput struct { // if object lock parameters are specified. ContentMD5 *string `location:"header" locationName:"Content-MD5" type:"string"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // Object key for which the multipart upload was initiated. // // Key is a required field @@ -29771,7 +30922,7 @@ type UploadPartInput struct { // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting // data. This value is used to store the object and then it is discarded; Amazon // S3 does not store the encryption key. The key must be appropriate for use - // with the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm + // with the algorithm specified in the x-amz-server-side-encryption-customer-algorithm // header. This must be the same encryption key specified in the initiate multipart // upload request. SSECustomerKey *string `marshal-as:"blob" location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string" sensitive:"true"` @@ -29856,6 +31007,12 @@ func (s *UploadPartInput) SetContentMD5(v string) *UploadPartInput { return s } +// SetExpectedBucketOwner sets the ExpectedBucketOwner field's value. +func (s *UploadPartInput) SetExpectedBucketOwner(v string) *UploadPartInput { + s.ExpectedBucketOwner = &v + return s +} + // SetKey sets the Key field's value. func (s *UploadPartInput) SetKey(v string) *UploadPartInput { s.Key = &v @@ -30124,6 +31281,13 @@ const ( AnalyticsS3ExportFileFormatCsv = "CSV" ) +// AnalyticsS3ExportFileFormat_Values returns all elements of the AnalyticsS3ExportFileFormat enum +func AnalyticsS3ExportFileFormat_Values() []string { + return []string{ + AnalyticsS3ExportFileFormatCsv, + } +} + const ( // BucketAccelerateStatusEnabled is a BucketAccelerateStatus enum value BucketAccelerateStatusEnabled = "Enabled" @@ -30132,6 +31296,14 @@ const ( BucketAccelerateStatusSuspended = "Suspended" ) +// BucketAccelerateStatus_Values returns all elements of the BucketAccelerateStatus enum +func BucketAccelerateStatus_Values() []string { + return []string{ + BucketAccelerateStatusEnabled, + BucketAccelerateStatusSuspended, + } +} + const ( // BucketCannedACLPrivate is a BucketCannedACL enum value BucketCannedACLPrivate = "private" @@ -30146,18 +31318,31 @@ const ( BucketCannedACLAuthenticatedRead = "authenticated-read" ) +// BucketCannedACL_Values returns all elements of the BucketCannedACL enum +func BucketCannedACL_Values() []string { + return []string{ + BucketCannedACLPrivate, + BucketCannedACLPublicRead, + BucketCannedACLPublicReadWrite, + BucketCannedACLAuthenticatedRead, + } +} + const ( - // BucketLocationConstraintEu is a BucketLocationConstraint enum value - BucketLocationConstraintEu = "EU" + // BucketLocationConstraintAfSouth1 is a BucketLocationConstraint enum value + BucketLocationConstraintAfSouth1 = "af-south-1" - // BucketLocationConstraintEuWest1 is a BucketLocationConstraint enum value - BucketLocationConstraintEuWest1 = "eu-west-1" + // BucketLocationConstraintApEast1 is a BucketLocationConstraint enum value + BucketLocationConstraintApEast1 = "ap-east-1" - // BucketLocationConstraintUsWest1 is a BucketLocationConstraint enum value - BucketLocationConstraintUsWest1 = "us-west-1" + // BucketLocationConstraintApNortheast1 is a BucketLocationConstraint enum value + BucketLocationConstraintApNortheast1 = "ap-northeast-1" - // BucketLocationConstraintUsWest2 is a BucketLocationConstraint enum value - BucketLocationConstraintUsWest2 = "us-west-2" + // BucketLocationConstraintApNortheast2 is a BucketLocationConstraint enum value + BucketLocationConstraintApNortheast2 = "ap-northeast-2" + + // BucketLocationConstraintApNortheast3 is a BucketLocationConstraint enum value + BucketLocationConstraintApNortheast3 = "ap-northeast-3" // BucketLocationConstraintApSouth1 is a BucketLocationConstraint enum value BucketLocationConstraintApSouth1 = "ap-south-1" @@ -30168,19 +31353,89 @@ const ( // BucketLocationConstraintApSoutheast2 is a BucketLocationConstraint enum value BucketLocationConstraintApSoutheast2 = "ap-southeast-2" - // BucketLocationConstraintApNortheast1 is a BucketLocationConstraint enum value - BucketLocationConstraintApNortheast1 = "ap-northeast-1" - - // BucketLocationConstraintSaEast1 is a BucketLocationConstraint enum value - BucketLocationConstraintSaEast1 = "sa-east-1" + // BucketLocationConstraintCaCentral1 is a BucketLocationConstraint enum value + BucketLocationConstraintCaCentral1 = "ca-central-1" // BucketLocationConstraintCnNorth1 is a BucketLocationConstraint enum value BucketLocationConstraintCnNorth1 = "cn-north-1" + // BucketLocationConstraintCnNorthwest1 is a BucketLocationConstraint enum value + BucketLocationConstraintCnNorthwest1 = "cn-northwest-1" + + // BucketLocationConstraintEu is a BucketLocationConstraint enum value + BucketLocationConstraintEu = "EU" + // BucketLocationConstraintEuCentral1 is a BucketLocationConstraint enum value BucketLocationConstraintEuCentral1 = "eu-central-1" + + // BucketLocationConstraintEuNorth1 is a BucketLocationConstraint enum value + BucketLocationConstraintEuNorth1 = "eu-north-1" + + // BucketLocationConstraintEuSouth1 is a BucketLocationConstraint enum value + BucketLocationConstraintEuSouth1 = "eu-south-1" + + // BucketLocationConstraintEuWest1 is a BucketLocationConstraint enum value + BucketLocationConstraintEuWest1 = "eu-west-1" + + // BucketLocationConstraintEuWest2 is a BucketLocationConstraint enum value + BucketLocationConstraintEuWest2 = "eu-west-2" + + // BucketLocationConstraintEuWest3 is a BucketLocationConstraint enum value + BucketLocationConstraintEuWest3 = "eu-west-3" + + // BucketLocationConstraintMeSouth1 is a BucketLocationConstraint enum value + BucketLocationConstraintMeSouth1 = "me-south-1" + + // BucketLocationConstraintSaEast1 is a BucketLocationConstraint enum value + BucketLocationConstraintSaEast1 = "sa-east-1" + + // BucketLocationConstraintUsEast2 is a BucketLocationConstraint enum value + BucketLocationConstraintUsEast2 = "us-east-2" + + // BucketLocationConstraintUsGovEast1 is a BucketLocationConstraint enum value + BucketLocationConstraintUsGovEast1 = "us-gov-east-1" + + // BucketLocationConstraintUsGovWest1 is a BucketLocationConstraint enum value + BucketLocationConstraintUsGovWest1 = "us-gov-west-1" + + // BucketLocationConstraintUsWest1 is a BucketLocationConstraint enum value + BucketLocationConstraintUsWest1 = "us-west-1" + + // BucketLocationConstraintUsWest2 is a BucketLocationConstraint enum value + BucketLocationConstraintUsWest2 = "us-west-2" ) +// BucketLocationConstraint_Values returns all elements of the BucketLocationConstraint enum +func BucketLocationConstraint_Values() []string { + return []string{ + BucketLocationConstraintAfSouth1, + BucketLocationConstraintApEast1, + BucketLocationConstraintApNortheast1, + BucketLocationConstraintApNortheast2, + BucketLocationConstraintApNortheast3, + BucketLocationConstraintApSouth1, + BucketLocationConstraintApSoutheast1, + BucketLocationConstraintApSoutheast2, + BucketLocationConstraintCaCentral1, + BucketLocationConstraintCnNorth1, + BucketLocationConstraintCnNorthwest1, + BucketLocationConstraintEu, + BucketLocationConstraintEuCentral1, + BucketLocationConstraintEuNorth1, + BucketLocationConstraintEuSouth1, + BucketLocationConstraintEuWest1, + BucketLocationConstraintEuWest2, + BucketLocationConstraintEuWest3, + BucketLocationConstraintMeSouth1, + BucketLocationConstraintSaEast1, + BucketLocationConstraintUsEast2, + BucketLocationConstraintUsGovEast1, + BucketLocationConstraintUsGovWest1, + BucketLocationConstraintUsWest1, + BucketLocationConstraintUsWest2, + } +} + const ( // BucketLogsPermissionFullControl is a BucketLogsPermission enum value BucketLogsPermissionFullControl = "FULL_CONTROL" @@ -30192,6 +31447,15 @@ const ( BucketLogsPermissionWrite = "WRITE" ) +// BucketLogsPermission_Values returns all elements of the BucketLogsPermission enum +func BucketLogsPermission_Values() []string { + return []string{ + BucketLogsPermissionFullControl, + BucketLogsPermissionRead, + BucketLogsPermissionWrite, + } +} + const ( // BucketVersioningStatusEnabled is a BucketVersioningStatus enum value BucketVersioningStatusEnabled = "Enabled" @@ -30200,6 +31464,14 @@ const ( BucketVersioningStatusSuspended = "Suspended" ) +// BucketVersioningStatus_Values returns all elements of the BucketVersioningStatus enum +func BucketVersioningStatus_Values() []string { + return []string{ + BucketVersioningStatusEnabled, + BucketVersioningStatusSuspended, + } +} + const ( // CompressionTypeNone is a CompressionType enum value CompressionTypeNone = "NONE" @@ -30211,6 +31483,15 @@ const ( CompressionTypeBzip2 = "BZIP2" ) +// CompressionType_Values returns all elements of the CompressionType enum +func CompressionType_Values() []string { + return []string{ + CompressionTypeNone, + CompressionTypeGzip, + CompressionTypeBzip2, + } +} + const ( // DeleteMarkerReplicationStatusEnabled is a DeleteMarkerReplicationStatus enum value DeleteMarkerReplicationStatusEnabled = "Enabled" @@ -30219,6 +31500,14 @@ const ( DeleteMarkerReplicationStatusDisabled = "Disabled" ) +// DeleteMarkerReplicationStatus_Values returns all elements of the DeleteMarkerReplicationStatus enum +func DeleteMarkerReplicationStatus_Values() []string { + return []string{ + DeleteMarkerReplicationStatusEnabled, + DeleteMarkerReplicationStatusDisabled, + } +} + // Requests Amazon S3 to encode the object keys in the response and specifies // the encoding method to use. An object key may contain any Unicode character; // however, XML 1.0 parser cannot parse some characters, such as characters @@ -30230,6 +31519,13 @@ const ( EncodingTypeUrl = "url" ) +// EncodingType_Values returns all elements of the EncodingType enum +func EncodingType_Values() []string { + return []string{ + EncodingTypeUrl, + } +} + // The bucket event for which to send notifications. const ( // EventS3ReducedRedundancyLostObject is a Event enum value @@ -30284,6 +31580,29 @@ const ( EventS3ReplicationOperationReplicatedAfterThreshold = "s3:Replication:OperationReplicatedAfterThreshold" ) +// Event_Values returns all elements of the Event enum +func Event_Values() []string { + return []string{ + EventS3ReducedRedundancyLostObject, + EventS3ObjectCreated, + EventS3ObjectCreatedPut, + EventS3ObjectCreatedPost, + EventS3ObjectCreatedCopy, + EventS3ObjectCreatedCompleteMultipartUpload, + EventS3ObjectRemoved, + EventS3ObjectRemovedDelete, + EventS3ObjectRemovedDeleteMarkerCreated, + EventS3ObjectRestore, + EventS3ObjectRestorePost, + EventS3ObjectRestoreCompleted, + EventS3Replication, + EventS3ReplicationOperationFailedReplication, + EventS3ReplicationOperationNotTracked, + EventS3ReplicationOperationMissedThreshold, + EventS3ReplicationOperationReplicatedAfterThreshold, + } +} + const ( // ExistingObjectReplicationStatusEnabled is a ExistingObjectReplicationStatus enum value ExistingObjectReplicationStatusEnabled = "Enabled" @@ -30292,6 +31611,14 @@ const ( ExistingObjectReplicationStatusDisabled = "Disabled" ) +// ExistingObjectReplicationStatus_Values returns all elements of the ExistingObjectReplicationStatus enum +func ExistingObjectReplicationStatus_Values() []string { + return []string{ + ExistingObjectReplicationStatusEnabled, + ExistingObjectReplicationStatusDisabled, + } +} + const ( // ExpirationStatusEnabled is a ExpirationStatus enum value ExpirationStatusEnabled = "Enabled" @@ -30300,11 +31627,26 @@ const ( ExpirationStatusDisabled = "Disabled" ) +// ExpirationStatus_Values returns all elements of the ExpirationStatus enum +func ExpirationStatus_Values() []string { + return []string{ + ExpirationStatusEnabled, + ExpirationStatusDisabled, + } +} + const ( // ExpressionTypeSql is a ExpressionType enum value ExpressionTypeSql = "SQL" ) +// ExpressionType_Values returns all elements of the ExpressionType enum +func ExpressionType_Values() []string { + return []string{ + ExpressionTypeSql, + } +} + const ( // FileHeaderInfoUse is a FileHeaderInfo enum value FileHeaderInfoUse = "USE" @@ -30316,6 +31658,15 @@ const ( FileHeaderInfoNone = "NONE" ) +// FileHeaderInfo_Values returns all elements of the FileHeaderInfo enum +func FileHeaderInfo_Values() []string { + return []string{ + FileHeaderInfoUse, + FileHeaderInfoIgnore, + FileHeaderInfoNone, + } +} + const ( // FilterRuleNamePrefix is a FilterRuleName enum value FilterRuleNamePrefix = "prefix" @@ -30324,6 +31675,14 @@ const ( FilterRuleNameSuffix = "suffix" ) +// FilterRuleName_Values returns all elements of the FilterRuleName enum +func FilterRuleName_Values() []string { + return []string{ + FilterRuleNamePrefix, + FilterRuleNameSuffix, + } +} + const ( // InventoryFormatCsv is a InventoryFormat enum value InventoryFormatCsv = "CSV" @@ -30335,6 +31694,15 @@ const ( InventoryFormatParquet = "Parquet" ) +// InventoryFormat_Values returns all elements of the InventoryFormat enum +func InventoryFormat_Values() []string { + return []string{ + InventoryFormatCsv, + InventoryFormatOrc, + InventoryFormatParquet, + } +} + const ( // InventoryFrequencyDaily is a InventoryFrequency enum value InventoryFrequencyDaily = "Daily" @@ -30343,6 +31711,14 @@ const ( InventoryFrequencyWeekly = "Weekly" ) +// InventoryFrequency_Values returns all elements of the InventoryFrequency enum +func InventoryFrequency_Values() []string { + return []string{ + InventoryFrequencyDaily, + InventoryFrequencyWeekly, + } +} + const ( // InventoryIncludedObjectVersionsAll is a InventoryIncludedObjectVersions enum value InventoryIncludedObjectVersionsAll = "All" @@ -30351,6 +31727,14 @@ const ( InventoryIncludedObjectVersionsCurrent = "Current" ) +// InventoryIncludedObjectVersions_Values returns all elements of the InventoryIncludedObjectVersions enum +func InventoryIncludedObjectVersions_Values() []string { + return []string{ + InventoryIncludedObjectVersionsAll, + InventoryIncludedObjectVersionsCurrent, + } +} + const ( // InventoryOptionalFieldSize is a InventoryOptionalField enum value InventoryOptionalFieldSize = "Size" @@ -30386,6 +31770,23 @@ const ( InventoryOptionalFieldIntelligentTieringAccessTier = "IntelligentTieringAccessTier" ) +// InventoryOptionalField_Values returns all elements of the InventoryOptionalField enum +func InventoryOptionalField_Values() []string { + return []string{ + InventoryOptionalFieldSize, + InventoryOptionalFieldLastModifiedDate, + InventoryOptionalFieldStorageClass, + InventoryOptionalFieldEtag, + InventoryOptionalFieldIsMultipartUploaded, + InventoryOptionalFieldReplicationStatus, + InventoryOptionalFieldEncryptionStatus, + InventoryOptionalFieldObjectLockRetainUntilDate, + InventoryOptionalFieldObjectLockMode, + InventoryOptionalFieldObjectLockLegalHoldStatus, + InventoryOptionalFieldIntelligentTieringAccessTier, + } +} + const ( // JSONTypeDocument is a JSONType enum value JSONTypeDocument = "DOCUMENT" @@ -30394,6 +31795,14 @@ const ( JSONTypeLines = "LINES" ) +// JSONType_Values returns all elements of the JSONType enum +func JSONType_Values() []string { + return []string{ + JSONTypeDocument, + JSONTypeLines, + } +} + const ( // MFADeleteEnabled is a MFADelete enum value MFADeleteEnabled = "Enabled" @@ -30402,6 +31811,14 @@ const ( MFADeleteDisabled = "Disabled" ) +// MFADelete_Values returns all elements of the MFADelete enum +func MFADelete_Values() []string { + return []string{ + MFADeleteEnabled, + MFADeleteDisabled, + } +} + const ( // MFADeleteStatusEnabled is a MFADeleteStatus enum value MFADeleteStatusEnabled = "Enabled" @@ -30410,6 +31827,14 @@ const ( MFADeleteStatusDisabled = "Disabled" ) +// MFADeleteStatus_Values returns all elements of the MFADeleteStatus enum +func MFADeleteStatus_Values() []string { + return []string{ + MFADeleteStatusEnabled, + MFADeleteStatusDisabled, + } +} + const ( // MetadataDirectiveCopy is a MetadataDirective enum value MetadataDirectiveCopy = "COPY" @@ -30418,6 +31843,14 @@ const ( MetadataDirectiveReplace = "REPLACE" ) +// MetadataDirective_Values returns all elements of the MetadataDirective enum +func MetadataDirective_Values() []string { + return []string{ + MetadataDirectiveCopy, + MetadataDirectiveReplace, + } +} + const ( // MetricsStatusEnabled is a MetricsStatus enum value MetricsStatusEnabled = "Enabled" @@ -30426,6 +31859,14 @@ const ( MetricsStatusDisabled = "Disabled" ) +// MetricsStatus_Values returns all elements of the MetricsStatus enum +func MetricsStatus_Values() []string { + return []string{ + MetricsStatusEnabled, + MetricsStatusDisabled, + } +} + const ( // ObjectCannedACLPrivate is a ObjectCannedACL enum value ObjectCannedACLPrivate = "private" @@ -30449,11 +31890,31 @@ const ( ObjectCannedACLBucketOwnerFullControl = "bucket-owner-full-control" ) +// ObjectCannedACL_Values returns all elements of the ObjectCannedACL enum +func ObjectCannedACL_Values() []string { + return []string{ + ObjectCannedACLPrivate, + ObjectCannedACLPublicRead, + ObjectCannedACLPublicReadWrite, + ObjectCannedACLAuthenticatedRead, + ObjectCannedACLAwsExecRead, + ObjectCannedACLBucketOwnerRead, + ObjectCannedACLBucketOwnerFullControl, + } +} + const ( // ObjectLockEnabledEnabled is a ObjectLockEnabled enum value ObjectLockEnabledEnabled = "Enabled" ) +// ObjectLockEnabled_Values returns all elements of the ObjectLockEnabled enum +func ObjectLockEnabled_Values() []string { + return []string{ + ObjectLockEnabledEnabled, + } +} + const ( // ObjectLockLegalHoldStatusOn is a ObjectLockLegalHoldStatus enum value ObjectLockLegalHoldStatusOn = "ON" @@ -30462,6 +31923,14 @@ const ( ObjectLockLegalHoldStatusOff = "OFF" ) +// ObjectLockLegalHoldStatus_Values returns all elements of the ObjectLockLegalHoldStatus enum +func ObjectLockLegalHoldStatus_Values() []string { + return []string{ + ObjectLockLegalHoldStatusOn, + ObjectLockLegalHoldStatusOff, + } +} + const ( // ObjectLockModeGovernance is a ObjectLockMode enum value ObjectLockModeGovernance = "GOVERNANCE" @@ -30470,6 +31939,14 @@ const ( ObjectLockModeCompliance = "COMPLIANCE" ) +// ObjectLockMode_Values returns all elements of the ObjectLockMode enum +func ObjectLockMode_Values() []string { + return []string{ + ObjectLockModeGovernance, + ObjectLockModeCompliance, + } +} + const ( // ObjectLockRetentionModeGovernance is a ObjectLockRetentionMode enum value ObjectLockRetentionModeGovernance = "GOVERNANCE" @@ -30478,6 +31955,14 @@ const ( ObjectLockRetentionModeCompliance = "COMPLIANCE" ) +// ObjectLockRetentionMode_Values returns all elements of the ObjectLockRetentionMode enum +func ObjectLockRetentionMode_Values() []string { + return []string{ + ObjectLockRetentionModeGovernance, + ObjectLockRetentionModeCompliance, + } +} + const ( // ObjectStorageClassStandard is a ObjectStorageClass enum value ObjectStorageClassStandard = "STANDARD" @@ -30501,16 +31986,43 @@ const ( ObjectStorageClassDeepArchive = "DEEP_ARCHIVE" ) +// ObjectStorageClass_Values returns all elements of the ObjectStorageClass enum +func ObjectStorageClass_Values() []string { + return []string{ + ObjectStorageClassStandard, + ObjectStorageClassReducedRedundancy, + ObjectStorageClassGlacier, + ObjectStorageClassStandardIa, + ObjectStorageClassOnezoneIa, + ObjectStorageClassIntelligentTiering, + ObjectStorageClassDeepArchive, + } +} + const ( // ObjectVersionStorageClassStandard is a ObjectVersionStorageClass enum value ObjectVersionStorageClassStandard = "STANDARD" ) +// ObjectVersionStorageClass_Values returns all elements of the ObjectVersionStorageClass enum +func ObjectVersionStorageClass_Values() []string { + return []string{ + ObjectVersionStorageClassStandard, + } +} + const ( // OwnerOverrideDestination is a OwnerOverride enum value OwnerOverrideDestination = "Destination" ) +// OwnerOverride_Values returns all elements of the OwnerOverride enum +func OwnerOverride_Values() []string { + return []string{ + OwnerOverrideDestination, + } +} + const ( // PayerRequester is a Payer enum value PayerRequester = "Requester" @@ -30519,6 +32031,14 @@ const ( PayerBucketOwner = "BucketOwner" ) +// Payer_Values returns all elements of the Payer enum +func Payer_Values() []string { + return []string{ + PayerRequester, + PayerBucketOwner, + } +} + const ( // PermissionFullControl is a Permission enum value PermissionFullControl = "FULL_CONTROL" @@ -30536,6 +32056,17 @@ const ( PermissionReadAcp = "READ_ACP" ) +// Permission_Values returns all elements of the Permission enum +func Permission_Values() []string { + return []string{ + PermissionFullControl, + PermissionWrite, + PermissionWriteAcp, + PermissionRead, + PermissionReadAcp, + } +} + const ( // ProtocolHttp is a Protocol enum value ProtocolHttp = "http" @@ -30544,6 +32075,14 @@ const ( ProtocolHttps = "https" ) +// Protocol_Values returns all elements of the Protocol enum +func Protocol_Values() []string { + return []string{ + ProtocolHttp, + ProtocolHttps, + } +} + const ( // QuoteFieldsAlways is a QuoteFields enum value QuoteFieldsAlways = "ALWAYS" @@ -30552,6 +32091,14 @@ const ( QuoteFieldsAsneeded = "ASNEEDED" ) +// QuoteFields_Values returns all elements of the QuoteFields enum +func QuoteFields_Values() []string { + return []string{ + QuoteFieldsAlways, + QuoteFieldsAsneeded, + } +} + const ( // ReplicationRuleStatusEnabled is a ReplicationRuleStatus enum value ReplicationRuleStatusEnabled = "Enabled" @@ -30560,6 +32107,14 @@ const ( ReplicationRuleStatusDisabled = "Disabled" ) +// ReplicationRuleStatus_Values returns all elements of the ReplicationRuleStatus enum +func ReplicationRuleStatus_Values() []string { + return []string{ + ReplicationRuleStatusEnabled, + ReplicationRuleStatusDisabled, + } +} + const ( // ReplicationStatusComplete is a ReplicationStatus enum value ReplicationStatusComplete = "COMPLETE" @@ -30574,6 +32129,16 @@ const ( ReplicationStatusReplica = "REPLICA" ) +// ReplicationStatus_Values returns all elements of the ReplicationStatus enum +func ReplicationStatus_Values() []string { + return []string{ + ReplicationStatusComplete, + ReplicationStatusPending, + ReplicationStatusFailed, + ReplicationStatusReplica, + } +} + const ( // ReplicationTimeStatusEnabled is a ReplicationTimeStatus enum value ReplicationTimeStatusEnabled = "Enabled" @@ -30582,6 +32147,14 @@ const ( ReplicationTimeStatusDisabled = "Disabled" ) +// ReplicationTimeStatus_Values returns all elements of the ReplicationTimeStatus enum +func ReplicationTimeStatus_Values() []string { + return []string{ + ReplicationTimeStatusEnabled, + ReplicationTimeStatusDisabled, + } +} + // If present, indicates that the requester was successfully charged for the // request. const ( @@ -30589,6 +32162,13 @@ const ( RequestChargedRequester = "requester" ) +// RequestCharged_Values returns all elements of the RequestCharged enum +func RequestCharged_Values() []string { + return []string{ + RequestChargedRequester, + } +} + // Confirms that the requester knows that they will be charged for the request. // Bucket owners need not specify this parameter in their requests. For information // about downloading objects from requester pays buckets, see Downloading Objects @@ -30599,11 +32179,25 @@ const ( RequestPayerRequester = "requester" ) +// RequestPayer_Values returns all elements of the RequestPayer enum +func RequestPayer_Values() []string { + return []string{ + RequestPayerRequester, + } +} + const ( // RestoreRequestTypeSelect is a RestoreRequestType enum value RestoreRequestTypeSelect = "SELECT" ) +// RestoreRequestType_Values returns all elements of the RestoreRequestType enum +func RestoreRequestType_Values() []string { + return []string{ + RestoreRequestTypeSelect, + } +} + const ( // ServerSideEncryptionAes256 is a ServerSideEncryption enum value ServerSideEncryptionAes256 = "AES256" @@ -30612,6 +32206,14 @@ const ( ServerSideEncryptionAwsKms = "aws:kms" ) +// ServerSideEncryption_Values returns all elements of the ServerSideEncryption enum +func ServerSideEncryption_Values() []string { + return []string{ + ServerSideEncryptionAes256, + ServerSideEncryptionAwsKms, + } +} + const ( // SseKmsEncryptedObjectsStatusEnabled is a SseKmsEncryptedObjectsStatus enum value SseKmsEncryptedObjectsStatusEnabled = "Enabled" @@ -30620,6 +32222,14 @@ const ( SseKmsEncryptedObjectsStatusDisabled = "Disabled" ) +// SseKmsEncryptedObjectsStatus_Values returns all elements of the SseKmsEncryptedObjectsStatus enum +func SseKmsEncryptedObjectsStatus_Values() []string { + return []string{ + SseKmsEncryptedObjectsStatusEnabled, + SseKmsEncryptedObjectsStatusDisabled, + } +} + const ( // StorageClassStandard is a StorageClass enum value StorageClassStandard = "STANDARD" @@ -30643,11 +32253,31 @@ const ( StorageClassDeepArchive = "DEEP_ARCHIVE" ) +// StorageClass_Values returns all elements of the StorageClass enum +func StorageClass_Values() []string { + return []string{ + StorageClassStandard, + StorageClassReducedRedundancy, + StorageClassStandardIa, + StorageClassOnezoneIa, + StorageClassIntelligentTiering, + StorageClassGlacier, + StorageClassDeepArchive, + } +} + const ( // StorageClassAnalysisSchemaVersionV1 is a StorageClassAnalysisSchemaVersion enum value StorageClassAnalysisSchemaVersionV1 = "V_1" ) +// StorageClassAnalysisSchemaVersion_Values returns all elements of the StorageClassAnalysisSchemaVersion enum +func StorageClassAnalysisSchemaVersion_Values() []string { + return []string{ + StorageClassAnalysisSchemaVersionV1, + } +} + const ( // TaggingDirectiveCopy is a TaggingDirective enum value TaggingDirectiveCopy = "COPY" @@ -30656,6 +32286,14 @@ const ( TaggingDirectiveReplace = "REPLACE" ) +// TaggingDirective_Values returns all elements of the TaggingDirective enum +func TaggingDirective_Values() []string { + return []string{ + TaggingDirectiveCopy, + TaggingDirectiveReplace, + } +} + const ( // TierStandard is a Tier enum value TierStandard = "Standard" @@ -30667,6 +32305,15 @@ const ( TierExpedited = "Expedited" ) +// Tier_Values returns all elements of the Tier enum +func Tier_Values() []string { + return []string{ + TierStandard, + TierBulk, + TierExpedited, + } +} + const ( // TransitionStorageClassGlacier is a TransitionStorageClass enum value TransitionStorageClassGlacier = "GLACIER" @@ -30684,6 +32331,17 @@ const ( TransitionStorageClassDeepArchive = "DEEP_ARCHIVE" ) +// TransitionStorageClass_Values returns all elements of the TransitionStorageClass enum +func TransitionStorageClass_Values() []string { + return []string{ + TransitionStorageClassGlacier, + TransitionStorageClassStandardIa, + TransitionStorageClassOnezoneIa, + TransitionStorageClassIntelligentTiering, + TransitionStorageClassDeepArchive, + } +} + const ( // TypeCanonicalUser is a Type enum value TypeCanonicalUser = "CanonicalUser" @@ -30694,3 +32352,12 @@ const ( // TypeGroup is a Type enum value TypeGroup = "Group" ) + +// Type_Values returns all elements of the Type enum +func Type_Values() []string { + return []string{ + TypeCanonicalUser, + TypeAmazonCustomerByEmail, + TypeGroup, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/body_hash.go b/vendor/github.com/aws/aws-sdk-go/service/s3/body_hash.go index 5c8ce5cc8..407f06b6e 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/body_hash.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/body_hash.go @@ -13,7 +13,6 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/internal/sdkio" ) const ( @@ -25,30 +24,6 @@ const ( appendMD5TxEncoding = "append-md5" ) -// contentMD5 computes and sets the HTTP Content-MD5 header for requests that -// require it. -func contentMD5(r *request.Request) { - h := md5.New() - - if !aws.IsReaderSeekable(r.Body) { - if r.Config.Logger != nil { - r.Config.Logger.Log(fmt.Sprintf( - "Unable to compute Content-MD5 for unseekable body, S3.%s", - r.Operation.Name)) - } - return - } - - if _, err := copySeekableBody(h, r.Body); err != nil { - r.Error = awserr.New("ContentMD5", "failed to compute body MD5", err) - return - } - - // encode the md5 checksum in base64 and set the request header. - v := base64.StdEncoding.EncodeToString(h.Sum(nil)) - r.HTTPRequest.Header.Set(contentMD5Header, v) -} - // computeBodyHashes will add Content MD5 and Content Sha256 hashes to the // request. If the body is not seekable or S3DisableContentMD5Validation set // this handler will be ignored. @@ -90,7 +65,7 @@ func computeBodyHashes(r *request.Request) { dst = io.MultiWriter(hashers...) } - if _, err := copySeekableBody(dst, r.Body); err != nil { + if _, err := aws.CopySeekableBody(dst, r.Body); err != nil { r.Error = awserr.New("BodyHashError", "failed to compute body hashes", err) return } @@ -119,28 +94,6 @@ const ( sha256HexEncLen = sha256.Size * 2 // hex.EncodedLen ) -func copySeekableBody(dst io.Writer, src io.ReadSeeker) (int64, error) { - curPos, err := src.Seek(0, sdkio.SeekCurrent) - if err != nil { - return 0, err - } - - // hash the body. seek back to the first position after reading to reset - // the body for transmission. copy errors may be assumed to be from the - // body. - n, err := io.Copy(dst, src) - if err != nil { - return n, err - } - - _, err = src.Seek(curPos, sdkio.SeekStart) - if err != nil { - return n, err - } - - return n, nil -} - // Adds the x-amz-te: append_md5 header to the request. This requests the service // responds with a trailing MD5 checksum. // diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/customizations.go b/vendor/github.com/aws/aws-sdk-go/service/s3/customizations.go index 036d0b2e0..a7698d5eb 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/customizations.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/customizations.go @@ -33,12 +33,6 @@ func defaultInitRequestFn(r *request.Request) { platformRequestHandlers(r) switch r.Operation.Name { - case opPutBucketCors, opPutBucketLifecycle, opPutBucketPolicy, - opPutBucketTagging, opDeleteObjects, opPutBucketLifecycleConfiguration, - opPutObjectLegalHold, opPutObjectRetention, opPutObjectLockConfiguration, - opPutBucketReplication: - // These S3 operations require Content-MD5 to be set - r.Handlers.Build.PushBack(contentMD5) case opGetBucketLocation: // GetBucketLocation has custom parsing logic r.Handlers.Unmarshal.PushFront(buildGetBucketLocation) diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/doc_custom.go b/vendor/github.com/aws/aws-sdk-go/service/s3/doc_custom.go index 4b65f7153..7f7aca208 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/doc_custom.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/doc_custom.go @@ -104,19 +104,6 @@ // content from S3. The Encryption and Decryption clients can be used concurrently // once the client is created. // -// sess := session.Must(session.NewSession()) -// -// // Create the decryption client. -// svc := s3crypto.NewDecryptionClient(sess) -// -// // The object will be downloaded from S3 and decrypted locally. By metadata -// // about the object's encryption will instruct the decryption client how -// // decrypt the content of the object. By default KMS is used for keys. -// result, err := svc.GetObject(&s3.GetObjectInput { -// Bucket: aws.String(myBucket), -// Key: aws.String(myKey), -// }) -// // See the s3crypto package documentation for more information. // https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/ // diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/bucket_region.go b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/bucket_region.go index f61665a58..9cc1e5970 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/bucket_region.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/bucket_region.go @@ -3,6 +3,7 @@ package s3manager import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/client" + "github.com/aws/aws-sdk-go/aws/corehandlers" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/service/s3" @@ -35,6 +36,30 @@ import ( // } // fmt.Printf("Bucket %s is in %s region\n", bucket, region) // +// By default the request will be made to the Amazon S3 endpoint using the Path +// style addressing. +// +// s3.us-west-2.amazonaws.com/bucketname +// +// This is not compatible with Amazon S3's FIPS endpoints. To override this +// behavior to use Virtual Host style addressing, provide a functional option +// that will set the Request's Config.S3ForcePathStyle to aws.Bool(false). +// +// region, err := s3manager.GetBucketRegion(ctx, sess, "bucketname", "us-west-2", func(r *request.Request) { +// r.S3ForcePathStyle = aws.Bool(false) +// }) +// +// To configure the GetBucketRegion to make a request via the Amazon +// S3 FIPS endpoints directly when a FIPS region name is not available, (e.g. +// fips-us-gov-west-1) set the Config.Endpoint on the Session, or client the +// utility is called with. The hint region will be ignored if an endpoint URL +// is configured on the session or client. +// +// sess, err := session.NewSession(&aws.Config{ +// Endpoint: aws.String("https://s3-fips.us-west-2.amazonaws.com"), +// }) +// +// region, err := s3manager.GetBucketRegion(context.Background(), sess, "bucketname", "") func GetBucketRegion(ctx aws.Context, c client.ConfigProvider, bucket, regionHint string, opts ...request.Option) (string, error) { var cfg aws.Config if len(regionHint) != 0 { @@ -50,12 +75,38 @@ const bucketRegionHeader = "X-Amz-Bucket-Region" // that it takes a S3 service client instead of a Session. The regionHint is // derived from the region the S3 service client was created in. // +// By default the request will be made to the Amazon S3 endpoint using the Path +// style addressing. +// +// s3.us-west-2.amazonaws.com/bucketname +// +// This is not compatible with Amazon S3's FIPS endpoints. To override this +// behavior to use Virtual Host style addressing, provide a functional option +// that will set the Request's Config.S3ForcePathStyle to aws.Bool(false). +// +// region, err := s3manager.GetBucketRegionWithClient(ctx, client, "bucketname", func(r *request.Request) { +// r.S3ForcePathStyle = aws.Bool(false) +// }) +// +// To configure the GetBucketRegion to make a request via the Amazon +// S3 FIPS endpoints directly when a FIPS region name is not available, (e.g. +// fips-us-gov-west-1) set the Config.Endpoint on the Session, or client the +// utility is called with. The hint region will be ignored if an endpoint URL +// is configured on the session or client. +// +// region, err := s3manager.GetBucketRegionWithClient(context.Background(), +// s3.New(sess, &aws.Config{ +// Endpoint: aws.String("https://s3-fips.us-west-2.amazonaws.com"), +// }), +// "bucketname") +// // See GetBucketRegion for more information. func GetBucketRegionWithClient(ctx aws.Context, svc s3iface.S3API, bucket string, opts ...request.Option) (string, error) { req, _ := svc.HeadBucketRequest(&s3.HeadBucketInput{ Bucket: aws.String(bucket), }) req.Config.S3ForcePathStyle = aws.Bool(true) + req.Config.Credentials = credentials.AnonymousCredentials req.SetContext(ctx) @@ -75,6 +126,16 @@ func GetBucketRegionWithClient(ctx aws.Context, svc s3iface.S3API, bucket string r.HTTPResponse.Status = "OK" r.Error = nil }) + // Replace the endpoint validation handler to not require a region if an + // endpoint URL was specified. Since these requests are not authenticated, + // requiring a region is not needed when an endpoint URL is provided. + req.Handlers.Validate.Swap( + corehandlers.ValidateEndpointHandler.Name, + request.NamedHandler{ + Name: "validateEndpointWithoutRegion", + Fn: validateEndpointWithoutRegion, + }, + ) req.ApplyOptions(opts...) @@ -86,3 +147,13 @@ func GetBucketRegionWithClient(ctx aws.Context, svc s3iface.S3API, bucket string return bucketRegion, nil } + +func validateEndpointWithoutRegion(r *request.Request) { + // Check if the caller provided an explicit URL instead of one derived by + // the SDK's endpoint resolver. For GetBucketRegion, with an explicit + // endpoint URL, a region is not needed. If no endpoint URL is provided, + // fallback the SDK's standard endpoint validation handler. + if len(aws.StringValue(r.Config.Endpoint)) == 0 { + corehandlers.ValidateEndpointHandler.Fn(r) + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/upload_input.go b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/upload_input.go index 9a5b46388..5aebddf91 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/upload_input.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/s3manager/upload_input.go @@ -63,6 +63,11 @@ type UploadInput struct { // see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17). ContentType *string `location:"header" locationName:"Content-Type" type:"string"` + // The account id of the expected bucket owner. If the bucket is owned by a + // different account, the request will fail with an HTTP 403 (Access Denied) + // error. + ExpectedBucketOwner *string `location:"header" locationName:"x-amz-expected-bucket-owner" type:"string"` + // The date and time at which the object is no longer cacheable. For more information, // see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21). Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp"` @@ -111,7 +116,7 @@ type UploadInput struct { // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting // data. This value is used to store the object and then it is discarded; Amazon // S3 does not store the encryption key. The key must be appropriate for use - // with the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm + // with the algorithm specified in the x-amz-server-side-encryption-customer-algorithm // header. SSECustomerKey *string `marshal-as:"blob" location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string" sensitive:"true"` @@ -141,8 +146,8 @@ type UploadInput struct { // S3 (for example, AES256, aws:kms). ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` - // If you don't specify, Standard is the default storage class. Amazon S3 supports - // other storage classes. + // If you don't specify, S3 Standard is the default storage class. Amazon S3 + // supports other storage classes. StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` // The tag-set for the object. The tag-set must be encoded as URL Query parameters. diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/sse.go b/vendor/github.com/aws/aws-sdk-go/service/s3/sse.go index b71c835de..57a0bd92c 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/sse.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/sse.go @@ -69,7 +69,7 @@ func computeKeyMD5(keyHeader, keyMD5Header, key string, r *http.Request) { return } - // In backwards compatiable, the header's value is not base64 encoded, + // In backwards compatible, the header's value is not base64 encoded, // and needs to be encoded and updated by the SDK's customizations. b64Key := base64.StdEncoding.EncodeToString([]byte(key)) r.Header.Set(keyHeader, b64Key) diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/statusok_error.go b/vendor/github.com/aws/aws-sdk-go/service/s3/statusok_error.go index f6a69aed1..247770e4c 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/statusok_error.go +++ b/vendor/github.com/aws/aws-sdk-go/service/s3/statusok_error.go @@ -2,6 +2,7 @@ package s3 import ( "bytes" + "io" "io/ioutil" "net/http" @@ -24,17 +25,18 @@ func copyMultipartStatusOKUnmarhsalError(r *request.Request) { r.HTTPResponse.Body = ioutil.NopCloser(body) defer body.Seek(0, sdkio.SeekStart) - if body.Len() == 0 { - // If there is no body don't attempt to parse the body. - return - } - unmarshalError(r) if err, ok := r.Error.(awserr.Error); ok && err != nil { - if err.Code() == request.ErrCodeSerialization { + if err.Code() == request.ErrCodeSerialization && + err.OrigErr() != io.EOF { r.Error = nil return } - r.HTTPResponse.StatusCode = http.StatusServiceUnavailable + // if empty payload + if err.OrigErr() == io.EOF { + r.HTTPResponse.StatusCode = http.StatusInternalServerError + } else { + r.HTTPResponse.StatusCode = http.StatusServiceUnavailable + } } } 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 5b63fac72..6eecf6691 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 @@ -1,6 +1,7 @@ package s3 import ( + "bytes" "encoding/xml" "fmt" "io" @@ -45,17 +46,24 @@ func unmarshalError(r *request.Request) { // Attempt to parse error from body if it is known var errResp xmlErrorResponse - err := xmlutil.UnmarshalXMLError(&errResp, r.HTTPResponse.Body) - if err == io.EOF { - // Only capture the error if an unmarshal error occurs that is not EOF, - // because S3 might send an error without a error message which causes - // the XML unmarshal to fail with EOF. - err = nil + var err error + if r.HTTPResponse.StatusCode >= 200 && r.HTTPResponse.StatusCode < 300 { + err = s3unmarshalXMLError(&errResp, r.HTTPResponse.Body) + } else { + err = xmlutil.UnmarshalXMLError(&errResp, r.HTTPResponse.Body) } + if err != nil { + var errorMsg string + if err == io.EOF { + errorMsg = "empty response payload" + } else { + errorMsg = "failed to unmarshal error message" + } + r.Error = awserr.NewRequestFailure( awserr.New(request.ErrCodeSerialization, - "failed to unmarshal error message", err), + errorMsg, err), r.HTTPResponse.StatusCode, r.RequestID, ) @@ -86,3 +94,21 @@ type RequestFailure interface { // Host ID is the S3 Host ID needed for debug, and contacting support HostID() string } + +// s3unmarshalXMLError is s3 specific xml error unmarshaler +// for 200 OK errors and response payloads. +// This function differs from the xmlUtil.UnmarshalXMLError +// func. It does not ignore the EOF error and passes it up. +// Related to bug fix for `s3 200 OK response with empty payload` +func s3unmarshalXMLError(v interface{}, stream io.Reader) error { + var errBuf bytes.Buffer + body := io.TeeReader(stream, &errBuf) + + err := xml.NewDecoder(body).Decode(v) + if err != nil && err != io.EOF { + return awserr.NewUnmarshalError(err, + "failed to unmarshal error message", errBuf.Bytes()) + } + + return err +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/api.go b/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/api.go index 7dfecc658..b89f513d5 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/api.go @@ -58,28 +58,28 @@ func (c *SecretsManager) CancelRotateSecretRequest(input *CancelRotateSecretInpu // CancelRotateSecret API operation for AWS Secrets Manager. // // Disables automatic scheduled rotation and cancels the rotation of a secret -// if one is currently in progress. +// if currently in progress. // // To re-enable scheduled rotation, call RotateSecret with AutomaticallyRotateAfterDays -// set to a value greater than 0. This will immediately rotate your secret and -// then enable the automatic schedule. +// set to a value greater than 0. This immediately rotates your secret and then +// enables the automatic schedule. // -// If you cancel a rotation that is in progress, it can leave the VersionStage -// labels in an unexpected state. Depending on what step of the rotation was -// in progress, you might need to remove the staging label AWSPENDING from the -// partially created version, specified by the VersionId response value. You -// should also evaluate the partially rotated new version to see if it should -// be deleted, which you can do by removing all staging labels from the new -// version's VersionStage field. +// If you cancel a rotation while in progress, it can leave the VersionStage +// labels in an unexpected state. Depending on the step of the rotation in progress, +// you might need to remove the staging label AWSPENDING from the partially +// created version, specified by the VersionId response value. You should also +// evaluate the partially rotated new version to see if it should be deleted, +// which you can do by removing all staging labels from the new version VersionStage +// field. // // To successfully start a rotation, the staging label AWSPENDING must be in // one of the following states: // -// * Not be attached to any version at all +// * Not attached to any version at all // // * Attached to the same version as the staging label AWSCURRENT // -// If the staging label AWSPENDING is attached to a different version than the +// If the staging label AWSPENDING attached to a different version than the // version with AWSCURRENT then the attempt to rotate fails. // // Minimum permissions @@ -205,7 +205,7 @@ func (c *SecretsManager) CreateSecretRequest(input *CreateSecretInput) (req *req // labels" that identify where the version is in the rotation cycle. The SecretVersionsToStages // field of the secret contains the mapping of staging labels to the active // versions of the secret. Versions without a staging label are considered deprecated -// and are not included in the list. +// and not included in the list. // // You provide the secret data to be encrypted by putting text in either the // SecretString parameter or binary data in the SecretBinary parameter, but @@ -213,20 +213,19 @@ func (c *SecretsManager) CreateSecretRequest(input *CreateSecretInput) (req *req // also creates an initial secret version and automatically attaches the staging // label AWSCURRENT to the new version. // -// * If you call an operation that needs to encrypt or decrypt the SecretString -// or SecretBinary for a secret in the same account as the calling user and -// that secret doesn't specify a AWS KMS encryption key, Secrets Manager -// uses the account's default AWS managed customer master key (CMK) with -// the alias aws/secretsmanager. If this key doesn't already exist in your -// account then Secrets Manager creates it for you automatically. All users -// and roles in the same AWS account automatically have access to use the -// default CMK. Note that if an Secrets Manager API call results in AWS having -// to create the account's AWS-managed CMK, it can result in a one-time significant -// delay in returning the result. +// * If you call an operation to encrypt or decrypt the SecretString or SecretBinary +// for a secret in the same account as the calling user and that secret doesn't +// specify a AWS KMS encryption key, Secrets Manager uses the account's default +// AWS managed customer master key (CMK) with the alias aws/secretsmanager. +// If this key doesn't already exist in your account then Secrets Manager +// creates it for you automatically. All users and roles in the same AWS +// account automatically have access to use the default CMK. Note that if +// an Secrets Manager API call results in AWS creating the account's AWS-managed +// CMK, it can result in a one-time significant delay in returning the result. // -// * If the secret is in a different AWS account from the credentials calling -// an API that requires encryption or decryption of the secret value then -// you must create and use a custom AWS KMS CMK because you can't access +// * If the secret resides in a different AWS account from the credentials +// calling an API that requires encryption or decryption of the secret value +// then you must create and use a custom AWS KMS CMK because you can't access // the default CMK for the account using credentials from a different AWS // account. Store the ARN of the CMK in the secret when you create the secret // or when you update it by including it in the KMSKeyId. If you call an @@ -243,10 +242,10 @@ func (c *SecretsManager) CreateSecretRequest(input *CreateSecretInput) (req *req // // * kms:GenerateDataKey - needed only if you use a customer-managed AWS // KMS key to encrypt the secret. You do not need this permission to use -// the account's default AWS managed CMK for Secrets Manager. +// the account default AWS managed CMK for Secrets Manager. // // * kms:Decrypt - needed only if you use a customer-managed AWS KMS key -// to encrypt the secret. You do not need this permission to use the account's +// to encrypt the secret. You do not need this permission to use the account // default AWS managed CMK for Secrets Manager. // // * secretsmanager:TagResource - needed only if you include the Tags parameter. @@ -384,7 +383,7 @@ func (c *SecretsManager) DeleteResourcePolicyRequest(input *DeleteResourcePolicy // DeleteResourcePolicy API operation for AWS Secrets Manager. // -// Deletes the resource-based permission policy that's attached to the secret. +// Deletes the resource-based permission policy attached to the secret. // // Minimum permissions // @@ -628,7 +627,7 @@ func (c *SecretsManager) DescribeSecretRequest(input *DescribeSecretInput) (req // DescribeSecret API operation for AWS Secrets Manager. // // Retrieves the details of a secret. It does not include the encrypted fields. -// Only those fields that are populated with a value are returned in the response. +// Secrets Manager only returns fields populated with a value in the response. // // Minimum permissions // @@ -831,10 +830,10 @@ func (c *SecretsManager) GetResourcePolicyRequest(input *GetResourcePolicyInput) // GetResourcePolicy API operation for AWS Secrets Manager. // -// Retrieves the JSON text of the resource-based policy document that's attached -// to the specified secret. The JSON request string input and response output -// are shown formatted with white space and line breaks for better readability. -// Submit your input as a single line JSON string. +// Retrieves the JSON text of the resource-based policy document attached to +// the specified secret. The JSON request string input and response output displays +// formatted code with white space and line breaks for better readability. Submit +// your input as a single line JSON string. // // Minimum permissions // @@ -846,8 +845,7 @@ func (c *SecretsManager) GetResourcePolicyRequest(input *GetResourcePolicyInput) // // * To attach a resource policy to a secret, use PutResourcePolicy. // -// * To delete the resource-based policy that's attached to a secret, use -// DeleteResourcePolicy. +// * To delete the resource-based policy attached to a secret, use DeleteResourcePolicy. // // * To list all of the currently available secrets, use ListSecrets. // @@ -1077,7 +1075,7 @@ func (c *SecretsManager) ListSecretVersionIdsRequest(input *ListSecretVersionIds // // Always check the NextToken response parameter when calling any of the List* // operations. These operations can occasionally return an empty or shorter -// than expected list of results even when there are more results available. +// than expected list of results even when there more results become available. // When this happens, the NextToken response parameter contains a value to pass // to the next call to the same API to request the next part of the list. // @@ -1239,7 +1237,7 @@ func (c *SecretsManager) ListSecretsRequest(input *ListSecretsInput) (req *reque // // Always check the NextToken response parameter when calling any of the List* // operations. These operations can occasionally return an empty or shorter -// than expected list of results even when there are more results available. +// than expected list of results even when there more results become available. // When this happens, the NextToken response parameter contains a value to pass // to the next call to the same API to request the next part of the list. // @@ -1408,7 +1406,7 @@ func (c *SecretsManager) PutResourcePolicyRequest(input *PutResourcePolicyInput) // // Related operations // -// * To retrieve the resource policy that's attached to a secret, use GetResourcePolicy. +// * To retrieve the resource policy attached to a secret, use GetResourcePolicy. // // * To delete the resource-based policy that's attached to a secret, use // DeleteResourcePolicy. @@ -1448,6 +1446,9 @@ func (c *SecretsManager) PutResourcePolicyRequest(input *PutResourcePolicyInput) // Lambda function ARN configured and you didn't include such an ARN as a // parameter in this call. // +// * PublicPolicyException +// The resource policy did not prevent broad access to the secret. +// // See also, https://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/PutResourcePolicy func (c *SecretsManager) PutResourcePolicy(input *PutResourcePolicyInput) (*PutResourcePolicyOutput, error) { req, out := c.PutResourcePolicyRequest(input) @@ -1542,20 +1543,19 @@ func (c *SecretsManager) PutSecretValueRequest(input *PutSecretValueInput) (req // However, if the secret data is different, then the operation fails because // you cannot modify an existing version; you can only create new ones. // -// * If you call an operation that needs to encrypt or decrypt the SecretString -// or SecretBinary for a secret in the same account as the calling user and -// that secret doesn't specify a AWS KMS encryption key, Secrets Manager -// uses the account's default AWS managed customer master key (CMK) with -// the alias aws/secretsmanager. If this key doesn't already exist in your -// account then Secrets Manager creates it for you automatically. All users -// and roles in the same AWS account automatically have access to use the -// default CMK. Note that if an Secrets Manager API call results in AWS having -// to create the account's AWS-managed CMK, it can result in a one-time significant -// delay in returning the result. +// * If you call an operation to encrypt or decrypt the SecretString or SecretBinary +// for a secret in the same account as the calling user and that secret doesn't +// specify a AWS KMS encryption key, Secrets Manager uses the account's default +// AWS managed customer master key (CMK) with the alias aws/secretsmanager. +// If this key doesn't already exist in your account then Secrets Manager +// creates it for you automatically. All users and roles in the same AWS +// account automatically have access to use the default CMK. Note that if +// an Secrets Manager API call results in AWS creating the account's AWS-managed +// CMK, it can result in a one-time significant delay in returning the result. // -// * If the secret is in a different AWS account from the credentials calling -// an API that requires encryption or decryption of the secret value then -// you must create and use a custom AWS KMS CMK because you can't access +// * If the secret resides in a different AWS account from the credentials +// calling an API that requires encryption or decryption of the secret value +// then you must create and use a custom AWS KMS CMK because you can't access // the default CMK for the account using credentials from a different AWS // account. Store the ARN of the CMK in the secret when you create the secret // or when you update it by including it in the KMSKeyId. If you call an @@ -1821,7 +1821,7 @@ func (c *SecretsManager) RotateSecretRequest(input *RotateSecretInput) (req *req // (https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html) // in the AWS Secrets Manager User Guide. // -// Secrets Manager schedules the next rotation when the previous one is complete. +// Secrets Manager schedules the next rotation when the previous one completes. // Secrets Manager schedules the date by adding the rotation interval (number // of days) to the actual date of the last rotation. The service chooses the // hour within that 24-hour date window randomly. The minute is also chosen @@ -1836,10 +1836,9 @@ func (c *SecretsManager) RotateSecretRequest(input *RotateSecretInput) (req *req // // * The AWSPENDING staging label is not attached to any version of the secret. // -// If instead the AWSPENDING staging label is present but is not attached to -// the same version as AWSCURRENT then any later invocation of RotateSecret -// assumes that a previous rotation request is still in progress and returns -// an error. +// If the AWSPENDING staging label is present but not attached to the same version +// as AWSCURRENT then any later invocation of RotateSecret assumes that a previous +// rotation request is still in progress and returns an error. // // Minimum permissions // @@ -1973,14 +1972,14 @@ func (c *SecretsManager) TagResourceRequest(input *TagResourceInput) (req *reque // // * Tag keys and values are case sensitive. // -// * Do not use the aws: prefix in your tag names or values because it is -// reserved for AWS use. You can't edit or delete tag names or values with -// this prefix. Tags with this prefix do not count against your tags per -// secret limit. +// * Do not use the aws: prefix in your tag names or values because AWS reserves +// it for AWS use. You can't edit or delete tag names or values with this +// prefix. Tags with this prefix do not count against your tags per secret +// limit. // -// * If your tagging schema will be used across multiple services and resources, -// remember that other services might have restrictions on allowed characters. -// Generally allowed characters are: letters, spaces, and numbers representable +// * If you use your tagging schema across multiple services and resources, +// remember other services might have restrictions on allowed characters. +// Generally allowed characters: letters, spaces, and numbers representable // in UTF-8, plus the following special characters: + - = . _ : / @. // // If you use tags as part of your security strategy, then adding or removing @@ -2236,20 +2235,19 @@ func (c *SecretsManager) UpdateSecretRequest(input *UpdateSecretInput) (req *req // Secrets Manager automatically attaches the staging label AWSCURRENT to // the new version. // -// * If you call an operation that needs to encrypt or decrypt the SecretString -// or SecretBinary for a secret in the same account as the calling user and -// that secret doesn't specify a AWS KMS encryption key, Secrets Manager -// uses the account's default AWS managed customer master key (CMK) with -// the alias aws/secretsmanager. If this key doesn't already exist in your -// account then Secrets Manager creates it for you automatically. All users -// and roles in the same AWS account automatically have access to use the -// default CMK. Note that if an Secrets Manager API call results in AWS having -// to create the account's AWS-managed CMK, it can result in a one-time significant -// delay in returning the result. +// * If you call an operation to encrypt or decrypt the SecretString or SecretBinary +// for a secret in the same account as the calling user and that secret doesn't +// specify a AWS KMS encryption key, Secrets Manager uses the account's default +// AWS managed customer master key (CMK) with the alias aws/secretsmanager. +// If this key doesn't already exist in your account then Secrets Manager +// creates it for you automatically. All users and roles in the same AWS +// account automatically have access to use the default CMK. Note that if +// an Secrets Manager API call results in AWS creating the account's AWS-managed +// CMK, it can result in a one-time significant delay in returning the result. // -// * If the secret is in a different AWS account from the credentials calling -// an API that requires encryption or decryption of the secret value then -// you must create and use a custom AWS KMS CMK because you can't access +// * If the secret resides in a different AWS account from the credentials +// calling an API that requires encryption or decryption of the secret value +// then you must create and use a custom AWS KMS CMK because you can't access // the default CMK for the account using credentials from a different AWS // account. Store the ARN of the CMK in the secret when you create the secret // or when you update it by including it in the KMSKeyId. If you call an @@ -2487,12 +2485,115 @@ func (c *SecretsManager) UpdateSecretVersionStageWithContext(ctx aws.Context, in return out, req.Send() } +const opValidateResourcePolicy = "ValidateResourcePolicy" + +// ValidateResourcePolicyRequest generates a "aws/request.Request" representing the +// client's request for the ValidateResourcePolicy operation. The "output" return +// value will be populated with the request's response once the request completes +// successfully. +// +// Use "Send" method on the returned Request to send the API call to the service. +// the "output" return value is not valid until after Send returns without error. +// +// See ValidateResourcePolicy for more information on using the ValidateResourcePolicy +// API call, and error handling. +// +// This method is useful when you want to inject custom logic or configuration +// into the SDK's request lifecycle. Such as custom headers, or retry logic. +// +// +// // Example sending a request using the ValidateResourcePolicyRequest method. +// req, resp := client.ValidateResourcePolicyRequest(params) +// +// err := req.Send() +// if err == nil { // resp is now filled +// fmt.Println(resp) +// } +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/ValidateResourcePolicy +func (c *SecretsManager) ValidateResourcePolicyRequest(input *ValidateResourcePolicyInput) (req *request.Request, output *ValidateResourcePolicyOutput) { + op := &request.Operation{ + Name: opValidateResourcePolicy, + HTTPMethod: "POST", + HTTPPath: "/", + } + + if input == nil { + input = &ValidateResourcePolicyInput{} + } + + output = &ValidateResourcePolicyOutput{} + req = c.newRequest(op, input, output) + return +} + +// ValidateResourcePolicy API operation for AWS Secrets Manager. +// +// Validates the JSON text of the resource-based policy document attached to +// the specified secret. The JSON request string input and response output displays +// formatted code with white space and line breaks for better readability. Submit +// your input as a single line JSON string. A resource-based policy is optional. +// +// 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 Secrets Manager's +// API operation ValidateResourcePolicy for usage and error information. +// +// Returned Error Types: +// * MalformedPolicyDocumentException +// The policy document that you provided isn't valid. +// +// * ResourceNotFoundException +// We can't find the resource that you asked for. +// +// * InvalidParameterException +// You provided an invalid value for a parameter. +// +// * InternalServiceError +// An error occurred on the server side. +// +// * InvalidRequestException +// You provided a parameter value that is not valid for the current state of +// the resource. +// +// Possible causes: +// +// * You tried to perform the operation on a secret that's currently marked +// deleted. +// +// * You tried to enable rotation on a secret that doesn't already have a +// Lambda function ARN configured and you didn't include such an ARN as a +// parameter in this call. +// +// See also, https://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/ValidateResourcePolicy +func (c *SecretsManager) ValidateResourcePolicy(input *ValidateResourcePolicyInput) (*ValidateResourcePolicyOutput, error) { + req, out := c.ValidateResourcePolicyRequest(input) + return out, req.Send() +} + +// ValidateResourcePolicyWithContext is the same as ValidateResourcePolicy with the addition of +// the ability to pass a context and additional request options. +// +// See ValidateResourcePolicy 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 *SecretsManager) ValidateResourcePolicyWithContext(ctx aws.Context, input *ValidateResourcePolicyInput, opts ...request.Option) (*ValidateResourcePolicyOutput, error) { + req, out := c.ValidateResourcePolicyRequest(input) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return out, req.Send() +} + type CancelRotateSecretInput struct { _ struct{} `type:"structure"` - // Specifies the secret for which you want to cancel a rotation request. You - // can specify either the Amazon Resource Name (ARN) or the friendly name of - // the secret. + // Specifies the secret to cancel a rotation request. You can specify either + // the Amazon Resource Name (ARN) or the friendly name of the secret. // // If you specify an ARN, we generally recommend that you specify a complete // ARN. You can specify a partial ARN too—for example, if you don’t include @@ -2504,7 +2605,12 @@ type CancelRotateSecretInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -2551,11 +2657,11 @@ type CancelRotateSecretOutput struct { // The friendly name of the secret for which rotation was canceled. Name *string `min:"1" type:"string"` - // The unique identifier of the version of the secret that was created during - // the rotation. This version might not be complete, and should be evaluated - // for possible deletion. At the very least, you should remove the VersionStage - // value AWSPENDING to enable this version to be deleted. Failing to clean up - // a cancelled rotation can block you from successfully starting future rotations. + // The unique identifier of the version of the secret created during the rotation. + // This version might not be complete, and should be evaluated for possible + // deletion. At the very least, you should remove the VersionStage value AWSPENDING + // to enable this version to be deleted. Failing to clean up a cancelled rotation + // can block you from successfully starting future rotations. VersionId *string `min:"32" type:"string"` } @@ -2599,7 +2705,7 @@ type CreateSecretInput struct { // for you and includes it as the value for this parameter in the request. If // you don't use the SDK and instead generate a raw HTTP request to the Secrets // Manager service endpoint, then you must generate a ClientRequestToken yourself - // for the new version and include that value in the request. + // for the new version and include the value in the request. // // This value helps ensure idempotency. Secrets Manager uses this value to prevent // the accidental creation of duplicate versions if there are failures and retries @@ -2609,9 +2715,9 @@ type CreateSecretInput struct { // * If the ClientRequestToken value isn't already associated with a version // of the secret then a new version of the secret is created. // - // * If a version with this value already exists and that version's SecretString + // * If a version with this value already exists and the version SecretString // and SecretBinary values are the same as those in the request, then the - // request is ignored (the operation is idempotent). + // request is ignored. // // * If a version with this value already exists and that version's SecretString // and SecretBinary values are different from those in the request then the @@ -2638,9 +2744,9 @@ type CreateSecretInput struct { // you automatically the first time it needs to encrypt a version's SecretString // or SecretBinary fields. // - // You can use the account's default CMK to encrypt and decrypt only if you - // call this operation using credentials from the same account that owns the - // secret. If the secret is in a different account, then you must create a custom + // You can use the account default CMK to encrypt and decrypt only if you call + // this operation using credentials from the same account that owns the secret. + // If the secret resides in a different account, then you must create a custom // CMK and specify the ARN in this field. KmsKeyId *string `type:"string"` @@ -2649,10 +2755,10 @@ type CreateSecretInput struct { // The secret name must be ASCII letters, digits, or the following characters // : /_+=.@- // - // Don't end your secret name with a hyphen followed by six characters. If you - // do so, you risk confusion and unexpected results when searching for a secret - // by partial ARN. This is because Secrets Manager automatically adds a hyphen - // and six random characters at the end of the ARN. + // Do not end your secret name with a hyphen followed by six characters. If + // you do so, you risk confusion and unexpected results when searching for a + // secret by partial ARN. Secrets Manager automatically adds a hyphen and six + // random characters at the end of the ARN. // // Name is a required field Name *string `min:"1" type:"string" required:"true"` @@ -2688,7 +2794,7 @@ type CreateSecretInput struct { // JSON for Parameters (https://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html#cli-using-param-json) // in the AWS CLI User Guide. For example: // - // [{"username":"bob"},{"password":"abc123xyz456"}] + // {"username":"bob","password":"abc123xyz456"} // // If your command-line tool or SDK requires quotation marks around the parameter, // you should use single quotes to avoid confusion with the double quotes required @@ -2729,14 +2835,14 @@ type CreateSecretInput struct { // // * Tag keys and values are case sensitive. // - // * Do not use the aws: prefix in your tag names or values because it is - // reserved for AWS use. You can't edit or delete tag names or values with - // this prefix. Tags with this prefix do not count against your tags per - // secret limit. + // * Do not use the aws: prefix in your tag names or values because AWS reserves + // it for AWS use. You can't edit or delete tag names or values with this + // prefix. Tags with this prefix do not count against your tags per secret + // limit. // - // * If your tagging schema will be used across multiple services and resources, - // remember that other services might have restrictions on allowed characters. - // Generally allowed characters are: letters, spaces, and numbers representable + // * If you use your tagging schema across multiple services and resources, + // remember other services might have restrictions on allowed characters. + // Generally allowed characters: letters, spaces, and numbers representable // in UTF-8, plus the following special characters: + - = . _ : / @. Tags []*Tag `type:"list"` } @@ -2838,8 +2944,8 @@ type CreateSecretOutput struct { // The friendly name of the secret that you just created. Name *string `min:"1" type:"string"` - // The unique identifier that's associated with the version of the secret you - // just created. + // The unique identifier associated with the version of the secret you just + // created. VersionId *string `min:"32" type:"string"` } @@ -2945,7 +3051,12 @@ type DeleteResourcePolicyInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -3055,7 +3166,12 @@ type DeleteSecretInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -3165,7 +3281,12 @@ type DescribeSecretInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -3209,6 +3330,9 @@ type DescribeSecretOutput struct { // The ARN of the secret. ARN *string `min:"20" type:"string"` + // The date that the secret was created. + CreatedDate *time.Time `type:"timestamp"` + // This value exists if the secret is scheduled for deletion. Some time after // the specified date and time, Secrets Manager deletes the secret and all of // its versions. @@ -3288,6 +3412,12 @@ func (s *DescribeSecretOutput) SetARN(v string) *DescribeSecretOutput { return s } +// SetCreatedDate sets the CreatedDate field's value. +func (s *DescribeSecretOutput) SetCreatedDate(v time.Time) *DescribeSecretOutput { + s.CreatedDate = &v + return s +} + // SetDeletedDate sets the DeletedDate field's value. func (s *DescribeSecretOutput) SetDeletedDate(v time.Time) *DescribeSecretOutput { s.DeletedDate = &v @@ -3425,6 +3555,52 @@ func (s *EncryptionFailure) RequestID() string { return s.RespMetadata.RequestID } +// Allows you to filter your list of secrets. +type Filter struct { + _ struct{} `type:"structure"` + + // Filters your list of secrets by a specific key. + Key *string `type:"string" enum:"FilterNameStringType"` + + // Filters your list of secrets by a specific value. + Values []*string `min:"1" type:"list"` +} + +// String returns the string representation +func (s Filter) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s Filter) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *Filter) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "Filter"} + if s.Values != nil && len(s.Values) < 1 { + invalidParams.Add(request.NewErrParamMinLen("Values", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetKey sets the Key field's value. +func (s *Filter) SetKey(v string) *Filter { + s.Key = &v + return s +} + +// SetValues sets the Values field's value. +func (s *Filter) SetValues(v []*string) *Filter { + s.Values = v + return s +} + type GetRandomPasswordInput struct { _ struct{} `type:"structure"` @@ -3584,7 +3760,12 @@ type GetResourcePolicyInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -3687,7 +3868,12 @@ type GetSecretValueInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -4162,7 +4348,7 @@ type ListSecretVersionIdsInput struct { // deprecated and are subject to deletion by Secrets Manager as needed. IncludeDeprecated *bool `type:"boolean"` - // (Optional) Limits the number of results that you want to include in the response. + // (Optional) Limits the number of results you want to include in the response. // If you don't include this parameter, it defaults to a value that's specific // to the operation. If additional items exist beyond the maximum you specify, // the NextToken response element is present and has a value (isn't null). Include @@ -4174,9 +4360,9 @@ type ListSecretVersionIdsInput struct { MaxResults *int64 `min:"1" type:"integer"` // (Optional) Use this parameter in a request if you receive a NextToken response - // in a previous request that indicates that there's more output available. - // In a subsequent call, set it to the value of the previous call's NextToken - // response to indicate where the output should continue from. + // in a previous request indicating there's more output available. In a subsequent + // call, set it to the value of the previous call NextToken response to indicate + // where the output should continue from. NextToken *string `min:"1" type:"string"` // The identifier for the secret containing the versions you want to list. You @@ -4193,7 +4379,12 @@ type ListSecretVersionIdsInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -4272,8 +4463,8 @@ type ListSecretVersionIdsOutput struct { Name *string `min:"1" type:"string"` // If present in the response, this value indicates that there's more output - // available than what's included in the current response. This can occur even - // when the response includes no values at all, such as when you ask for a filtered + // available than included in the current response. This can occur even when + // the response includes no values at all, such as when you ask for a filtered // view of a very long list. Use this value in the NextToken request parameter // in a subsequent call to the operation to continue processing and get the // next part of the output. You should repeat this until the NextToken response @@ -4321,7 +4512,10 @@ func (s *ListSecretVersionIdsOutput) SetVersions(v []*SecretVersionsListEntry) * type ListSecretsInput struct { _ struct{} `type:"structure"` - // (Optional) Limits the number of results that you want to include in the response. + // Lists the secret request filters. + Filters []*Filter `type:"list"` + + // (Optional) Limits the number of results you want to include in the response. // If you don't include this parameter, it defaults to a value that's specific // to the operation. If additional items exist beyond the maximum you specify, // the NextToken response element is present and has a value (isn't null). Include @@ -4333,10 +4527,13 @@ type ListSecretsInput struct { MaxResults *int64 `min:"1" type:"integer"` // (Optional) Use this parameter in a request if you receive a NextToken response - // in a previous request that indicates that there's more output available. - // In a subsequent call, set it to the value of the previous call's NextToken - // response to indicate where the output should continue from. + // in a previous request indicating there's more output available. In a subsequent + // call, set it to the value of the previous call NextToken response to indicate + // where the output should continue from. NextToken *string `min:"1" type:"string"` + + // Lists secrets in the requested order. + SortOrder *string `type:"string" enum:"SortOrderType"` } // String returns the string representation @@ -4358,6 +4555,16 @@ func (s *ListSecretsInput) Validate() error { if s.NextToken != nil && len(*s.NextToken) < 1 { invalidParams.Add(request.NewErrParamMinLen("NextToken", 1)) } + if s.Filters != nil { + for i, v := range s.Filters { + if v == nil { + continue + } + if err := v.Validate(); err != nil { + invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Filters", i), err.(request.ErrInvalidParams)) + } + } + } if invalidParams.Len() > 0 { return invalidParams @@ -4365,6 +4572,12 @@ func (s *ListSecretsInput) Validate() error { return nil } +// SetFilters sets the Filters field's value. +func (s *ListSecretsInput) SetFilters(v []*Filter) *ListSecretsInput { + s.Filters = v + return s +} + // SetMaxResults sets the MaxResults field's value. func (s *ListSecretsInput) SetMaxResults(v int64) *ListSecretsInput { s.MaxResults = &v @@ -4377,12 +4590,18 @@ func (s *ListSecretsInput) SetNextToken(v string) *ListSecretsInput { return s } +// SetSortOrder sets the SortOrder field's value. +func (s *ListSecretsInput) SetSortOrder(v string) *ListSecretsInput { + s.SortOrder = &v + return s +} + type ListSecretsOutput struct { _ struct{} `type:"structure"` // If present in the response, this value indicates that there's more output - // available than what's included in the current response. This can occur even - // when the response includes no values at all, such as when you ask for a filtered + // available than included in the current response. This can occur even when + // the response includes no values at all, such as when you ask for a filtered // view of a very long list. Use this value in the NextToken request parameter // in a subsequent call to the operation to continue processing and get the // next part of the output. You should repeat this until the NextToken response @@ -4527,9 +4746,69 @@ func (s *PreconditionNotMetException) RequestID() string { return s.RespMetadata.RequestID } +// The resource policy did not prevent broad access to the secret. +type PublicPolicyException struct { + _ struct{} `type:"structure"` + RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` + + Message_ *string `locationName:"Message" type:"string"` +} + +// String returns the string representation +func (s PublicPolicyException) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s PublicPolicyException) GoString() string { + return s.String() +} + +func newErrorPublicPolicyException(v protocol.ResponseMetadata) error { + return &PublicPolicyException{ + RespMetadata: v, + } +} + +// Code returns the exception type name. +func (s *PublicPolicyException) Code() string { + return "PublicPolicyException" +} + +// Message returns the exception's message. +func (s *PublicPolicyException) Message() string { + if s.Message_ != nil { + return *s.Message_ + } + return "" +} + +// OrigErr always returns nil, satisfies awserr.Error interface. +func (s *PublicPolicyException) OrigErr() error { + return nil +} + +func (s *PublicPolicyException) Error() string { + return fmt.Sprintf("%s: %s", s.Code(), s.Message()) +} + +// Status code returns the HTTP status code for the request's response error. +func (s *PublicPolicyException) StatusCode() int { + return s.RespMetadata.StatusCode +} + +// RequestID returns the service's response RequestID for request. +func (s *PublicPolicyException) RequestID() string { + return s.RespMetadata.RequestID +} + type PutResourcePolicyInput struct { _ struct{} `type:"structure"` + // Makes an optional API call to Zelkova to validate the Resource Policy to + // prevent broad access to your secret. + BlockPublicPolicy *bool `type:"boolean"` + // A JSON-formatted string that's constructed according to the grammar and syntax // for an AWS resource-based policy. The policy in the string identifies who // can access or manage this secret and its versions. For information on how @@ -4553,7 +4832,12 @@ type PutResourcePolicyInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -4591,6 +4875,12 @@ func (s *PutResourcePolicyInput) Validate() error { return nil } +// SetBlockPublicPolicy sets the BlockPublicPolicy field's value. +func (s *PutResourcePolicyInput) SetBlockPublicPolicy(v bool) *PutResourcePolicyInput { + s.BlockPublicPolicy = &v + return s +} + // SetResourcePolicy sets the ResourcePolicy field's value. func (s *PutResourcePolicyInput) SetResourcePolicy(v string) *PutResourcePolicyInput { s.ResourcePolicy = &v @@ -4606,11 +4896,11 @@ func (s *PutResourcePolicyInput) SetSecretId(v string) *PutResourcePolicyInput { type PutResourcePolicyOutput struct { _ struct{} `type:"structure"` - // The ARN of the secret that the resource-based policy was retrieved for. + // The ARN of the secret retrieved by the resource-based policy. ARN *string `min:"20" type:"string"` - // The friendly name of the secret that the resource-based policy was retrieved - // for. + // The friendly name of the secret that the retrieved by the resource-based + // policy. Name *string `min:"1" type:"string"` } @@ -4661,7 +4951,7 @@ type PutSecretValueInput struct { // or SecretBinary values are the same as those in the request then the request // is ignored (the operation is idempotent). // - // * If a version with this value already exists and that version's SecretString + // * If a version with this value already exists and the version of the SecretString // and SecretBinary values are different from those in the request then the // request fails because you cannot modify an existing secret version. You // can only create new versions to store new secret values. @@ -4696,7 +4986,12 @@ type PutSecretValueInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -4983,7 +5278,12 @@ type RestoreSecretInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -5066,9 +5366,9 @@ type RotateSecretInput struct { // service endpoint, then you must generate a ClientRequestToken yourself for // new versions and include that value in the request. // - // You only need to specify your own value if you are implementing your own - // retry logic and want to ensure that a given secret is not created twice. - // We recommend that you generate a UUID-type (https://wikipedia.org/wiki/Universally_unique_identifier) + // You only need to specify your own value if you implement your own retry logic + // and want to ensure that a given secret is not created twice. We recommend + // that you generate a UUID-type (https://wikipedia.org/wiki/Universally_unique_identifier) // value to ensure uniqueness within the specified secret. // // Secrets Manager uses this value to prevent the accidental creation of duplicate @@ -5095,7 +5395,12 @@ type RotateSecretInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -5259,7 +5564,10 @@ type SecretListEntry struct { // in the AWS Secrets Manager User Guide. ARN *string `min:"20" type:"string"` - // The date and time on which this secret was deleted. Not present on active + // The date and time when a secret was created. + CreatedDate *time.Time `type:"timestamp"` + + // The date and time the deletion of the secret occurred. Not present on active // secrets. The secret can be recovered until the number of days in the recovery // window has passed, as specified in the RecoveryWindowInDays parameter of // the DeleteSecret operation. @@ -5268,10 +5576,10 @@ type SecretListEntry struct { // The user-provided description of the secret. Description *string `type:"string"` - // The ARN or alias of the AWS KMS customer master key (CMK) that's used to - // encrypt the SecretString and SecretBinary fields in each version of the secret. - // If you don't provide a key, then Secrets Manager defaults to encrypting the - // secret fields with the default KMS CMK (the one named awssecretsmanager) + // The ARN or alias of the AWS KMS customer master key (CMK) used to encrypt + // the SecretString and SecretBinary fields in each version of the secret. If + // you don't provide a key, then Secrets Manager defaults to encrypting the + // secret fields with the default KMS CMK, the key named awssecretsmanager, // for this account. KmsKeyId *string `type:"string"` @@ -5297,24 +5605,24 @@ type SecretListEntry struct { // Indicates whether automatic, scheduled rotation is enabled for this secret. RotationEnabled *bool `type:"boolean"` - // The ARN of an AWS Lambda function that's invoked by Secrets Manager to rotate - // and expire the secret either automatically per the schedule or manually by - // a call to RotateSecret. + // The ARN of an AWS Lambda function invoked by Secrets Manager to rotate and + // expire the secret either automatically per the schedule or manually by a + // call to RotateSecret. RotationLambdaARN *string `type:"string"` // A structure that defines the rotation configuration for the secret. RotationRules *RotationRulesType `type:"structure"` // A list of all of the currently assigned SecretVersionStage staging labels - // and the SecretVersionId that each is attached to. Staging labels are used - // to keep track of the different versions during the rotation process. + // and the SecretVersionId attached to each one. Staging labels are used to + // keep track of the different versions during the rotation process. // // A version that does not have any SecretVersionStage is considered deprecated // and subject to deletion. Such versions are not included in this list. SecretVersionsToStages map[string][]*string `type:"map"` - // The list of user-defined tags that are associated with the secret. To add - // tags to a secret, use TagResource. To remove tags, use UntagResource. + // The list of user-defined tags associated with the secret. To add tags to + // a secret, use TagResource. To remove tags, use UntagResource. Tags []*Tag `type:"list"` } @@ -5334,6 +5642,12 @@ func (s *SecretListEntry) SetARN(v string) *SecretListEntry { return s } +// SetCreatedDate sets the CreatedDate field's value. +func (s *SecretListEntry) SetCreatedDate(v time.Time) *SecretListEntry { + s.CreatedDate = &v + return s +} + // SetDeletedDate sets the DeletedDate field's value. func (s *SecretListEntry) SetDeletedDate(v time.Time) *SecretListEntry { s.DeletedDate = &v @@ -5472,7 +5786,7 @@ type Tag struct { // The key identifier, or name, of the tag. Key *string `min:"1" type:"string"` - // The string value that's associated with the key of the tag. + // The string value associated with the key of the tag. Value *string `type:"string"` } @@ -5527,7 +5841,12 @@ type TagResourceInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -5627,7 +5946,12 @@ type UntagResourceInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -5776,7 +6100,12 @@ type UpdateSecretInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -5926,7 +6255,7 @@ func (s *UpdateSecretOutput) SetVersionId(v string) *UpdateSecretOutput { type UpdateSecretVersionStageInput struct { _ struct{} `type:"structure"` - // (Optional) The secret version ID that you want to add the staging label to. + // (Optional) The secret version ID that you want to add the staging label. // If you want to remove a label from a version, then do not specify this parameter. // // If the staging label is already attached to a different version of the secret, @@ -5941,9 +6270,9 @@ type UpdateSecretVersionStageInput struct { // the version ID does not match, then the operation fails. RemoveFromVersionId *string `min:"32" type:"string"` - // Specifies the secret with the version whose list of staging labels you want - // to modify. You can specify either the Amazon Resource Name (ARN) or the friendly - // name of the secret. + // Specifies the secret with the version with the list of staging labels you + // want to modify. You can specify either the Amazon Resource Name (ARN) or + // the friendly name of the secret. // // If you specify an ARN, we generally recommend that you specify a complete // ARN. You can specify a partial ARN too—for example, if you don’t include @@ -5955,7 +6284,12 @@ type UpdateSecretVersionStageInput struct { // a partial ARN, then those characters cause Secrets Manager to assume that // you’re specifying a complete ARN. This confusion can cause unexpected results. // To avoid this situation, we recommend that you don’t create secret names - // that end with a hyphen followed by six characters. + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. // // SecretId is a required field SecretId *string `min:"1" type:"string" required:"true"` @@ -6031,10 +6365,10 @@ func (s *UpdateSecretVersionStageInput) SetVersionStage(v string) *UpdateSecretV type UpdateSecretVersionStageOutput struct { _ struct{} `type:"structure"` - // The ARN of the secret with the staging label that was modified. + // The ARN of the secret with the modified staging label. ARN *string `min:"20" type:"string"` - // The friendly name of the secret with the staging label that was modified. + // The friendly name of the secret with the modified staging label. Name *string `min:"1" type:"string"` } @@ -6059,3 +6393,185 @@ func (s *UpdateSecretVersionStageOutput) SetName(v string) *UpdateSecretVersionS s.Name = &v return s } + +type ValidateResourcePolicyInput struct { + _ struct{} `type:"structure"` + + // Identifies the Resource Policy attached to the secret. + // + // ResourcePolicy is a required field + ResourcePolicy *string `min:"1" type:"string" required:"true"` + + // The identifier for the secret that you want to validate a resource policy. + // You can specify either the Amazon Resource Name (ARN) or the friendly name + // of the secret. + // + // If you specify an ARN, we generally recommend that you specify a complete + // ARN. You can specify a partial ARN too—for example, if you don’t include + // the final hyphen and six random characters that Secrets Manager adds at the + // end of the ARN when you created the secret. A partial ARN match can work + // as long as it uniquely matches only one secret. However, if your secret has + // a name that ends in a hyphen followed by six characters (before Secrets Manager + // adds the hyphen and six characters to the ARN) and you try to use that as + // a partial ARN, then those characters cause Secrets Manager to assume that + // you’re specifying a complete ARN. This confusion can cause unexpected results. + // To avoid this situation, we recommend that you don’t create secret names + // ending with a hyphen followed by six characters. + // + // If you specify an incomplete ARN without the random suffix, and instead provide + // the 'friendly name', you must not include the random suffix. If you do include + // the random suffix added by Secrets Manager, you receive either a ResourceNotFoundException + // or an AccessDeniedException error, depending on your permissions. + SecretId *string `min:"1" type:"string"` +} + +// String returns the string representation +func (s ValidateResourcePolicyInput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ValidateResourcePolicyInput) GoString() string { + return s.String() +} + +// Validate inspects the fields of the type to determine if they are valid. +func (s *ValidateResourcePolicyInput) Validate() error { + invalidParams := request.ErrInvalidParams{Context: "ValidateResourcePolicyInput"} + if s.ResourcePolicy == nil { + invalidParams.Add(request.NewErrParamRequired("ResourcePolicy")) + } + if s.ResourcePolicy != nil && len(*s.ResourcePolicy) < 1 { + invalidParams.Add(request.NewErrParamMinLen("ResourcePolicy", 1)) + } + if s.SecretId != nil && len(*s.SecretId) < 1 { + invalidParams.Add(request.NewErrParamMinLen("SecretId", 1)) + } + + if invalidParams.Len() > 0 { + return invalidParams + } + return nil +} + +// SetResourcePolicy sets the ResourcePolicy field's value. +func (s *ValidateResourcePolicyInput) SetResourcePolicy(v string) *ValidateResourcePolicyInput { + s.ResourcePolicy = &v + return s +} + +// SetSecretId sets the SecretId field's value. +func (s *ValidateResourcePolicyInput) SetSecretId(v string) *ValidateResourcePolicyInput { + s.SecretId = &v + return s +} + +type ValidateResourcePolicyOutput struct { + _ struct{} `type:"structure"` + + // Returns a message stating that your Reource Policy passed validation. + PolicyValidationPassed *bool `type:"boolean"` + + // Returns an error message if your policy doesn't pass validatation. + ValidationErrors []*ValidationErrorsEntry `type:"list"` +} + +// String returns the string representation +func (s ValidateResourcePolicyOutput) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ValidateResourcePolicyOutput) GoString() string { + return s.String() +} + +// SetPolicyValidationPassed sets the PolicyValidationPassed field's value. +func (s *ValidateResourcePolicyOutput) SetPolicyValidationPassed(v bool) *ValidateResourcePolicyOutput { + s.PolicyValidationPassed = &v + return s +} + +// SetValidationErrors sets the ValidationErrors field's value. +func (s *ValidateResourcePolicyOutput) SetValidationErrors(v []*ValidationErrorsEntry) *ValidateResourcePolicyOutput { + s.ValidationErrors = v + return s +} + +// Displays errors that occurred during validation of the resource policy. +type ValidationErrorsEntry struct { + _ struct{} `type:"structure"` + + // Checks the name of the policy. + CheckName *string `min:"1" type:"string"` + + // Displays error messages if validation encounters problems during validation + // of the resource policy. + ErrorMessage *string `type:"string"` +} + +// String returns the string representation +func (s ValidationErrorsEntry) String() string { + return awsutil.Prettify(s) +} + +// GoString returns the string representation +func (s ValidationErrorsEntry) GoString() string { + return s.String() +} + +// SetCheckName sets the CheckName field's value. +func (s *ValidationErrorsEntry) SetCheckName(v string) *ValidationErrorsEntry { + s.CheckName = &v + return s +} + +// SetErrorMessage sets the ErrorMessage field's value. +func (s *ValidationErrorsEntry) SetErrorMessage(v string) *ValidationErrorsEntry { + s.ErrorMessage = &v + return s +} + +const ( + // FilterNameStringTypeDescription is a FilterNameStringType enum value + FilterNameStringTypeDescription = "description" + + // FilterNameStringTypeName is a FilterNameStringType enum value + FilterNameStringTypeName = "name" + + // FilterNameStringTypeTagKey is a FilterNameStringType enum value + FilterNameStringTypeTagKey = "tag-key" + + // FilterNameStringTypeTagValue is a FilterNameStringType enum value + FilterNameStringTypeTagValue = "tag-value" + + // FilterNameStringTypeAll is a FilterNameStringType enum value + FilterNameStringTypeAll = "all" +) + +// FilterNameStringType_Values returns all elements of the FilterNameStringType enum +func FilterNameStringType_Values() []string { + return []string{ + FilterNameStringTypeDescription, + FilterNameStringTypeName, + FilterNameStringTypeTagKey, + FilterNameStringTypeTagValue, + FilterNameStringTypeAll, + } +} + +const ( + // SortOrderTypeAsc is a SortOrderType enum value + SortOrderTypeAsc = "asc" + + // SortOrderTypeDesc is a SortOrderType enum value + SortOrderTypeDesc = "desc" +) + +// SortOrderType_Values returns all elements of the SortOrderType enum +func SortOrderType_Values() []string { + return []string{ + SortOrderTypeAsc, + SortOrderTypeDesc, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/doc.go b/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/doc.go index b931ba87c..71cfce041 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/doc.go @@ -3,7 +3,7 @@ // Package secretsmanager provides the client and types for making API // requests to AWS Secrets Manager. // -// AWS Secrets Manager is a web service that enables you to store, manage, and +// AWS Secrets Manager provides a service to enable you to store, manage, and // retrieve, secrets. // // This guide provides descriptions of the Secrets Manager API. For more information @@ -14,25 +14,25 @@ // This version of the Secrets Manager API Reference documents the Secrets Manager // API version 2017-10-17. // -// As an alternative to using the API directly, you can use one of the AWS SDKs, -// which consist of libraries and sample code for various programming languages -// and platforms (such as Java, Ruby, .NET, iOS, and Android). The SDKs provide -// a convenient way to create programmatic access to AWS Secrets Manager. For -// example, the SDKs take care of cryptographically signing requests, managing -// errors, and retrying requests automatically. For more information about the -// AWS SDKs, including how to download and install them, see Tools for Amazon -// Web Services (http://aws.amazon.com/tools/). +// As an alternative to using the API, you can use one of the AWS SDKs, which +// consist of libraries and sample code for various programming languages and +// platforms such as Java, Ruby, .NET, iOS, and Android. The SDKs provide a +// convenient way to create programmatic access to AWS Secrets Manager. For +// example, the SDKs provide cryptographically signing requests, managing errors, +// and retrying requests automatically. For more information about the AWS SDKs, +// including downloading and installing them, see Tools for Amazon Web Services +// (http://aws.amazon.com/tools/). // -// We recommend that you use the AWS SDKs to make programmatic API calls to -// Secrets Manager. However, you also can use the Secrets Manager HTTP Query -// API to make direct calls to the Secrets Manager web service. To learn more -// about the Secrets Manager HTTP Query API, see Making Query Requests (https://docs.aws.amazon.com/secretsmanager/latest/userguide/query-requests.html) +// We recommend you use the AWS SDKs to make programmatic API calls to Secrets +// Manager. However, you also can use the Secrets Manager HTTP Query API to +// make direct calls to the Secrets Manager web service. To learn more about +// the Secrets Manager HTTP Query API, see Making Query Requests (https://docs.aws.amazon.com/secretsmanager/latest/userguide/query-requests.html) // in the AWS Secrets Manager User Guide. // -// Secrets Manager supports GET and POST requests for all actions. That is, -// the API doesn't require you to use GET for some actions and POST for others. -// However, GET requests are subject to the limitation size of a URL. Therefore, -// for operations that require larger sizes, use a POST request. +// Secrets Manager API supports GET and POST requests for all actions, and doesn't +// require you to use GET for some actions and POST for others. However, GET +// requests are subject to the limitation size of a URL. Therefore, for operations +// that require larger sizes, use a POST request. // // Support and Feedback for AWS Secrets Manager // @@ -44,25 +44,24 @@ // How examples are presented // // The JSON that AWS Secrets Manager expects as your request parameters and -// that the service returns as a response to HTTP query requests are single, +// the service returns as a response to HTTP query requests contain single, // long strings without line breaks or white space formatting. The JSON shown -// in the examples is formatted with both line breaks and white space to improve -// readability. When example input parameters would also result in long strings -// that extend beyond the screen, we insert line breaks to enhance readability. -// You should always submit the input as a single JSON text string. +// in the examples displays the code formatted with both line breaks and white +// space to improve readability. When example input parameters can also cause +// long strings extending beyond the screen, you can insert line breaks to enhance +// readability. You should always submit the input as a single JSON text string. // // Logging API Requests // // AWS Secrets Manager supports AWS CloudTrail, a service that records AWS API // calls for your AWS account and delivers log files to an Amazon S3 bucket. // By using information that's collected by AWS CloudTrail, you can determine -// which requests were successfully made to Secrets Manager, who made the request, -// when it was made, and so on. For more about AWS Secrets Manager and its support +// the requests successfully made to Secrets Manager, who made the request, +// when it was made, and so on. For more about AWS Secrets Manager and support // for AWS CloudTrail, see Logging AWS Secrets Manager Events with AWS CloudTrail // (http://docs.aws.amazon.com/secretsmanager/latest/userguide/monitoring.html#monitoring_cloudtrail) // in the AWS Secrets Manager User Guide. To learn more about CloudTrail, including -// how to turn it on and find your log files, see the AWS CloudTrail User Guide -// (https://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html). +// enabling it and find your log files, see the AWS CloudTrail User Guide (https://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html). // // See https://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17 for more information on this service. // diff --git a/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/errors.go b/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/errors.go index df82716bb..ab90196bb 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/errors.go @@ -77,6 +77,12 @@ const ( // The request failed because you did not complete all the prerequisite steps. ErrCodePreconditionNotMetException = "PreconditionNotMetException" + // ErrCodePublicPolicyException for service response error code + // "PublicPolicyException". + // + // The resource policy did not prevent broad access to the secret. + ErrCodePublicPolicyException = "PublicPolicyException" + // ErrCodeResourceExistsException for service response error code // "ResourceExistsException". // @@ -100,6 +106,7 @@ var exceptionFromCode = map[string]func(protocol.ResponseMetadata) error{ "LimitExceededException": newErrorLimitExceededException, "MalformedPolicyDocumentException": newErrorMalformedPolicyDocumentException, "PreconditionNotMetException": newErrorPreconditionNotMetException, + "PublicPolicyException": newErrorPublicPolicyException, "ResourceExistsException": newErrorResourceExistsException, "ResourceNotFoundException": newErrorResourceNotFoundException, } diff --git a/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/secretsmanageriface/interface.go b/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/secretsmanageriface/interface.go index cf7b46f96..fe386bd58 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/secretsmanageriface/interface.go +++ b/vendor/github.com/aws/aws-sdk-go/service/secretsmanager/secretsmanageriface/interface.go @@ -137,6 +137,10 @@ type SecretsManagerAPI interface { UpdateSecretVersionStage(*secretsmanager.UpdateSecretVersionStageInput) (*secretsmanager.UpdateSecretVersionStageOutput, error) UpdateSecretVersionStageWithContext(aws.Context, *secretsmanager.UpdateSecretVersionStageInput, ...request.Option) (*secretsmanager.UpdateSecretVersionStageOutput, error) UpdateSecretVersionStageRequest(*secretsmanager.UpdateSecretVersionStageInput) (*request.Request, *secretsmanager.UpdateSecretVersionStageOutput) + + ValidateResourcePolicy(*secretsmanager.ValidateResourcePolicyInput) (*secretsmanager.ValidateResourcePolicyOutput, error) + ValidateResourcePolicyWithContext(aws.Context, *secretsmanager.ValidateResourcePolicyInput, ...request.Option) (*secretsmanager.ValidateResourcePolicyOutput, error) + ValidateResourcePolicyRequest(*secretsmanager.ValidateResourcePolicyInput) (*request.Request, *secretsmanager.ValidateResourcePolicyOutput) } var _ SecretsManagerAPI = (*secretsmanager.SecretsManager)(nil) diff --git a/vendor/github.com/aws/aws-sdk-go/service/ssm/api.go b/vendor/github.com/aws/aws-sdk-go/service/ssm/api.go index 52a08bfd3..09f5f40ad 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ssm/api.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ssm/api.go @@ -73,10 +73,11 @@ func (c *SSM) AddTagsToResourceRequest(input *AddTagsToResourceInput) (req *requ // We recommend that you devise a set of tag keys that meets your needs for // each resource type. Using a consistent set of tag keys makes it easier for // you to manage your resources. You can search and filter the resources based -// on the tags you add. Tags don't have any semantic meaning to Amazon EC2 and -// are interpreted strictly as a string of characters. +// on the tags you add. Tags don't have any semantic meaning to and are interpreted +// strictly as a string of characters. // -// For more information about tags, see Tagging Your Amazon EC2 Resources (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) +// For more information about using tags with EC2 instances, see Tagging your +// Amazon EC2 resources (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html) // in the Amazon EC2 User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -290,7 +291,7 @@ func (c *SSM) CancelMaintenanceWindowExecutionRequest(input *CancelMaintenanceWi // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // See also, https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/CancelMaintenanceWindowExecution @@ -365,12 +366,11 @@ func (c *SSM) CreateActivationRequest(input *CreateActivationInput) (req *reques // Systems Manager capabilities. You use the activation code and ID when installing // SSM Agent on machines in your hybrid environment. For more information about // requirements for managing on-premises instances and VMs using Systems Manager, -// see Setting Up AWS Systems Manager for Hybrid Environments (http://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-managedinstances.html) +// see Setting up AWS Systems Manager for hybrid environments (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-managedinstances.html) // in the AWS Systems Manager User Guide. // -// On-premises servers or VMs that are registered with Systems Manager and Amazon -// EC2 instances that you manage with Systems Manager are all called managed -// instances. +// On-premises servers or VMs that are registered with Systems Manager and EC2 +// instances that you manage with Systems Manager are all called managed instances. // // 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 @@ -449,15 +449,18 @@ func (c *SSM) CreateAssociationRequest(input *CreateAssociationInput) (req *requ // CreateAssociation API operation for Amazon Simple Systems Manager (SSM). // -// Associates the specified Systems Manager document with the specified instances -// or targets. -// -// When you associate a document with one or more instances using instance IDs -// or tags, SSM Agent running on the instance processes the document and configures -// the instance as specified. -// -// If you associate a document with an instance that already has an associated -// document, the system returns the AssociationAlreadyExists exception. +// A State Manager association defines the state that you want to maintain on +// your instances. For example, an association can specify that anti-virus software +// must be installed and running on your instances, or that certain ports must +// be closed. For static targets, the association specifies a schedule for when +// the configuration is reapplied. For dynamic targets, such as an AWS Resource +// Group or an AWS Autoscaling Group, State Manager applies the configuration +// when new instances are added to the group. The association also specifies +// actions to take when applying the configuration. For example, an association +// for anti-virus software might run once a day. If the software is not installed, +// then State Manager installs it. If the software is installed, but the service +// is not running, then the association might instruct State Manager to start +// the service. // // 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 @@ -508,7 +511,7 @@ func (c *SSM) CreateAssociationRequest(input *CreateAssociationInput) (req *requ // // * InvalidTarget // The target is not valid or does not exist. It might not be configured for -// EC2 Systems Manager or you might not have permission to perform the operation. +// Systems Manager or you might not have permission to perform the operation. // // * InvalidSchedule // The schedule is invalid. Verify your cron or rate expression and try again. @@ -638,7 +641,7 @@ func (c *SSM) CreateAssociationBatchRequest(input *CreateAssociationBatchInput) // // * InvalidTarget // The target is not valid or does not exist. It might not be configured for -// EC2 Systems Manager or you might not have permission to perform the operation. +// Systems Manager or you might not have permission to perform the operation. // // * InvalidSchedule // The schedule is invalid. Verify your cron or rate expression and try again. @@ -709,10 +712,11 @@ func (c *SSM) CreateDocumentRequest(input *CreateDocumentInput) (req *request.Re // CreateDocument API operation for Amazon Simple Systems Manager (SSM). // -// Creates a Systems Manager document. -// -// After you create a document, you can use CreateAssociation to associate it -// with one or more running instances. +// Creates a Systems Manager (SSM) document. An SSM document defines the actions +// that Systems Manager performs on your managed instances. For more information +// about SSM documents, including information about supported schemas, features, +// and syntax, see AWS Systems Manager Documents (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-ssm-docs.html) +// in the AWS Systems Manager User 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 @@ -832,7 +836,7 @@ func (c *SSM) CreateMaintenanceWindowRequest(input *CreateMaintenanceWindowInput // For example, too many maintenance windows or patch baselines have been created. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -906,13 +910,13 @@ func (c *SSM) CreateOpsItemRequest(input *CreateOpsItemInput) (req *request.Requ // // Creates a new OpsItem. You must have permission in AWS Identity and Access // Management (IAM) to create a new OpsItem. For more information, see Getting -// Started with OpsCenter (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-getting-started.html) +// started with OpsCenter (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-getting-started.html) // in the AWS Systems Manager User Guide. // // Operations engineers and IT professionals use OpsCenter to view, investigate, // and remediate operational issues impacting the performance and health of // their AWS resources. For more information, see AWS Systems Manager OpsCenter -// (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html) +// (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html) // in the AWS Systems Manager User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -931,7 +935,7 @@ func (c *SSM) CreateOpsItemRequest(input *CreateOpsItemInput) (req *request.Requ // // * OpsItemLimitExceededException // The request caused OpsItems to exceed one or more quotas. For information -// about OpsItem quotas, see What are the resource limits for OpsCenter? (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-learn-more.html#OpsCenter-learn-more-limits). +// about OpsItem quotas, see What are the resource limits for OpsCenter? (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-learn-more.html#OpsCenter-learn-more-limits). // // * OpsItemInvalidParameterException // A specified parameter argument isn't valid. Verify the available arguments @@ -1025,7 +1029,7 @@ func (c *SSM) CreatePatchBaselineRequest(input *CreatePatchBaselineInput) (req * // For example, too many maintenance windows or patch baselines have been created. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -1104,16 +1108,16 @@ func (c *SSM) CreateResourceDataSyncRequest(input *CreateResourceDataSyncInput) // // You can configure Systems Manager Inventory to use the SyncToDestination // type to synchronize Inventory data from multiple AWS Regions to a single -// Amazon S3 bucket. For more information, see Configuring Resource Data Sync -// for Inventory (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-inventory-datasync.html) +// S3 bucket. For more information, see Configuring Resource Data Sync for Inventory +// (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-inventory-datasync.html) // in the AWS Systems Manager User Guide. // // You can configure Systems Manager Explorer to use the SyncFromSource type // to synchronize operational work items (OpsItems) and operational data (OpsData) -// from multiple AWS Regions to a single Amazon S3 bucket. This type can synchronize +// from multiple AWS Regions to a single S3 bucket. This type can synchronize // OpsItems and OpsData from multiple AWS accounts and Regions or EntireOrganization -// by using AWS Organizations. For more information, see Setting Up Explorer -// to Display Data from Multiple Accounts and Regions (http://docs.aws.amazon.com/systems-manager/latest/userguide/Explorer-resource-data-sync.html) +// by using AWS Organizations. For more information, see Setting up Systems +// Manager Explorer to display data from multiple accounts and Regions (https://docs.aws.amazon.com/systems-manager/latest/userguide/Explorer-resource-data-sync.html) // in the AWS Systems Manager User Guide. // // A resource data sync is an asynchronous operation that returns immediately. @@ -1508,7 +1512,7 @@ func (c *SSM) DeleteInventoryRequest(input *DeleteInventoryInput) (req *request. // DeleteInventory API operation for Amazon Simple Systems Manager (SSM). // -// Delete a custom inventory type, or the data associated with a custom Inventory +// Delete a custom inventory type or the data associated with a custom Inventory // type. Deleting a custom inventory type is also referred to as deleting a // custom inventory schema. // @@ -2207,7 +2211,7 @@ func (c *SSM) DeregisterTargetFromMaintenanceWindowRequest(input *DeregisterTarg // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -2298,7 +2302,7 @@ func (c *SSM) DeregisterTaskFromMaintenanceWindowRequest(input *DeregisterTaskFr // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -2609,6 +2613,12 @@ func (c *SSM) DescribeAssociationExecutionTargetsRequest(input *DescribeAssociat Name: opDescribeAssociationExecutionTargets, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -2667,6 +2677,58 @@ func (c *SSM) DescribeAssociationExecutionTargetsWithContext(ctx aws.Context, in return out, req.Send() } +// DescribeAssociationExecutionTargetsPages iterates over the pages of a DescribeAssociationExecutionTargets operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeAssociationExecutionTargets method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeAssociationExecutionTargets operation. +// pageNum := 0 +// err := client.DescribeAssociationExecutionTargetsPages(params, +// func(page *ssm.DescribeAssociationExecutionTargetsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeAssociationExecutionTargetsPages(input *DescribeAssociationExecutionTargetsInput, fn func(*DescribeAssociationExecutionTargetsOutput, bool) bool) error { + return c.DescribeAssociationExecutionTargetsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeAssociationExecutionTargetsPagesWithContext same as DescribeAssociationExecutionTargetsPages 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 *SSM) DescribeAssociationExecutionTargetsPagesWithContext(ctx aws.Context, input *DescribeAssociationExecutionTargetsInput, fn func(*DescribeAssociationExecutionTargetsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeAssociationExecutionTargetsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAssociationExecutionTargetsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeAssociationExecutionTargetsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeAssociationExecutions = "DescribeAssociationExecutions" // DescribeAssociationExecutionsRequest generates a "aws/request.Request" representing the @@ -2698,6 +2760,12 @@ func (c *SSM) DescribeAssociationExecutionsRequest(input *DescribeAssociationExe Name: opDescribeAssociationExecutions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -2752,6 +2820,58 @@ func (c *SSM) DescribeAssociationExecutionsWithContext(ctx aws.Context, input *D return out, req.Send() } +// DescribeAssociationExecutionsPages iterates over the pages of a DescribeAssociationExecutions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeAssociationExecutions method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeAssociationExecutions operation. +// pageNum := 0 +// err := client.DescribeAssociationExecutionsPages(params, +// func(page *ssm.DescribeAssociationExecutionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeAssociationExecutionsPages(input *DescribeAssociationExecutionsInput, fn func(*DescribeAssociationExecutionsOutput, bool) bool) error { + return c.DescribeAssociationExecutionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeAssociationExecutionsPagesWithContext same as DescribeAssociationExecutionsPages 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 *SSM) DescribeAssociationExecutionsPagesWithContext(ctx aws.Context, input *DescribeAssociationExecutionsInput, fn func(*DescribeAssociationExecutionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeAssociationExecutionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAssociationExecutionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeAssociationExecutionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeAutomationExecutions = "DescribeAutomationExecutions" // DescribeAutomationExecutionsRequest generates a "aws/request.Request" representing the @@ -2783,6 +2903,12 @@ func (c *SSM) DescribeAutomationExecutionsRequest(input *DescribeAutomationExecu Name: opDescribeAutomationExecutions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -2840,6 +2966,58 @@ func (c *SSM) DescribeAutomationExecutionsWithContext(ctx aws.Context, input *De return out, req.Send() } +// DescribeAutomationExecutionsPages iterates over the pages of a DescribeAutomationExecutions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeAutomationExecutions method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeAutomationExecutions operation. +// pageNum := 0 +// err := client.DescribeAutomationExecutionsPages(params, +// func(page *ssm.DescribeAutomationExecutionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeAutomationExecutionsPages(input *DescribeAutomationExecutionsInput, fn func(*DescribeAutomationExecutionsOutput, bool) bool) error { + return c.DescribeAutomationExecutionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeAutomationExecutionsPagesWithContext same as DescribeAutomationExecutionsPages 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 *SSM) DescribeAutomationExecutionsPagesWithContext(ctx aws.Context, input *DescribeAutomationExecutionsInput, fn func(*DescribeAutomationExecutionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeAutomationExecutionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAutomationExecutionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeAutomationExecutionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeAutomationStepExecutions = "DescribeAutomationStepExecutions" // DescribeAutomationStepExecutionsRequest generates a "aws/request.Request" representing the @@ -2871,6 +3049,12 @@ func (c *SSM) DescribeAutomationStepExecutionsRequest(input *DescribeAutomationS Name: opDescribeAutomationStepExecutions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -2933,6 +3117,58 @@ func (c *SSM) DescribeAutomationStepExecutionsWithContext(ctx aws.Context, input return out, req.Send() } +// DescribeAutomationStepExecutionsPages iterates over the pages of a DescribeAutomationStepExecutions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeAutomationStepExecutions method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeAutomationStepExecutions operation. +// pageNum := 0 +// err := client.DescribeAutomationStepExecutionsPages(params, +// func(page *ssm.DescribeAutomationStepExecutionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeAutomationStepExecutionsPages(input *DescribeAutomationStepExecutionsInput, fn func(*DescribeAutomationStepExecutionsOutput, bool) bool) error { + return c.DescribeAutomationStepExecutionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeAutomationStepExecutionsPagesWithContext same as DescribeAutomationStepExecutionsPages 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 *SSM) DescribeAutomationStepExecutionsPagesWithContext(ctx aws.Context, input *DescribeAutomationStepExecutionsInput, fn func(*DescribeAutomationStepExecutionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeAutomationStepExecutionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAutomationStepExecutionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeAutomationStepExecutionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeAvailablePatches = "DescribeAvailablePatches" // DescribeAvailablePatchesRequest generates a "aws/request.Request" representing the @@ -2964,6 +3200,12 @@ func (c *SSM) DescribeAvailablePatchesRequest(input *DescribeAvailablePatchesInp Name: opDescribeAvailablePatches, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3012,6 +3254,58 @@ func (c *SSM) DescribeAvailablePatchesWithContext(ctx aws.Context, input *Descri return out, req.Send() } +// DescribeAvailablePatchesPages iterates over the pages of a DescribeAvailablePatches operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeAvailablePatches method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeAvailablePatches operation. +// pageNum := 0 +// err := client.DescribeAvailablePatchesPages(params, +// func(page *ssm.DescribeAvailablePatchesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeAvailablePatchesPages(input *DescribeAvailablePatchesInput, fn func(*DescribeAvailablePatchesOutput, bool) bool) error { + return c.DescribeAvailablePatchesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeAvailablePatchesPagesWithContext same as DescribeAvailablePatchesPages 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 *SSM) DescribeAvailablePatchesPagesWithContext(ctx aws.Context, input *DescribeAvailablePatchesInput, fn func(*DescribeAvailablePatchesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeAvailablePatchesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeAvailablePatchesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeAvailablePatchesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeDocument = "DescribeDocument" // DescribeDocumentRequest generates a "aws/request.Request" representing the @@ -3216,6 +3510,12 @@ func (c *SSM) DescribeEffectiveInstanceAssociationsRequest(input *DescribeEffect Name: opDescribeEffectiveInstanceAssociations, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3279,6 +3579,58 @@ func (c *SSM) DescribeEffectiveInstanceAssociationsWithContext(ctx aws.Context, return out, req.Send() } +// DescribeEffectiveInstanceAssociationsPages iterates over the pages of a DescribeEffectiveInstanceAssociations operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeEffectiveInstanceAssociations method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeEffectiveInstanceAssociations operation. +// pageNum := 0 +// err := client.DescribeEffectiveInstanceAssociationsPages(params, +// func(page *ssm.DescribeEffectiveInstanceAssociationsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeEffectiveInstanceAssociationsPages(input *DescribeEffectiveInstanceAssociationsInput, fn func(*DescribeEffectiveInstanceAssociationsOutput, bool) bool) error { + return c.DescribeEffectiveInstanceAssociationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeEffectiveInstanceAssociationsPagesWithContext same as DescribeEffectiveInstanceAssociationsPages 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 *SSM) DescribeEffectiveInstanceAssociationsPagesWithContext(ctx aws.Context, input *DescribeEffectiveInstanceAssociationsInput, fn func(*DescribeEffectiveInstanceAssociationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeEffectiveInstanceAssociationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeEffectiveInstanceAssociationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeEffectiveInstanceAssociationsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeEffectivePatchesForPatchBaseline = "DescribeEffectivePatchesForPatchBaseline" // DescribeEffectivePatchesForPatchBaselineRequest generates a "aws/request.Request" representing the @@ -3310,6 +3662,12 @@ func (c *SSM) DescribeEffectivePatchesForPatchBaselineRequest(input *DescribeEff Name: opDescribeEffectivePatchesForPatchBaseline, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3344,13 +3702,12 @@ func (c *SSM) DescribeEffectivePatchesForPatchBaselineRequest(input *DescribeEff // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * UnsupportedOperatingSystem // The operating systems you specified is not supported, or the operation is -// not supported for the operating system. Valid operating systems include: -// Windows, AmazonLinux, RedhatEnterpriseLinux, and Ubuntu. +// not supported for the operating system. // // * InternalServerError // An error occurred on the server side. @@ -3377,6 +3734,58 @@ func (c *SSM) DescribeEffectivePatchesForPatchBaselineWithContext(ctx aws.Contex return out, req.Send() } +// DescribeEffectivePatchesForPatchBaselinePages iterates over the pages of a DescribeEffectivePatchesForPatchBaseline operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeEffectivePatchesForPatchBaseline method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeEffectivePatchesForPatchBaseline operation. +// pageNum := 0 +// err := client.DescribeEffectivePatchesForPatchBaselinePages(params, +// func(page *ssm.DescribeEffectivePatchesForPatchBaselineOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeEffectivePatchesForPatchBaselinePages(input *DescribeEffectivePatchesForPatchBaselineInput, fn func(*DescribeEffectivePatchesForPatchBaselineOutput, bool) bool) error { + return c.DescribeEffectivePatchesForPatchBaselinePagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeEffectivePatchesForPatchBaselinePagesWithContext same as DescribeEffectivePatchesForPatchBaselinePages 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 *SSM) DescribeEffectivePatchesForPatchBaselinePagesWithContext(ctx aws.Context, input *DescribeEffectivePatchesForPatchBaselineInput, fn func(*DescribeEffectivePatchesForPatchBaselineOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeEffectivePatchesForPatchBaselineInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeEffectivePatchesForPatchBaselineRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeEffectivePatchesForPatchBaselineOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeInstanceAssociationsStatus = "DescribeInstanceAssociationsStatus" // DescribeInstanceAssociationsStatusRequest generates a "aws/request.Request" representing the @@ -3408,6 +3817,12 @@ func (c *SSM) DescribeInstanceAssociationsStatusRequest(input *DescribeInstanceA Name: opDescribeInstanceAssociationsStatus, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3471,6 +3886,58 @@ func (c *SSM) DescribeInstanceAssociationsStatusWithContext(ctx aws.Context, inp return out, req.Send() } +// DescribeInstanceAssociationsStatusPages iterates over the pages of a DescribeInstanceAssociationsStatus operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeInstanceAssociationsStatus method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeInstanceAssociationsStatus operation. +// pageNum := 0 +// err := client.DescribeInstanceAssociationsStatusPages(params, +// func(page *ssm.DescribeInstanceAssociationsStatusOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeInstanceAssociationsStatusPages(input *DescribeInstanceAssociationsStatusInput, fn func(*DescribeInstanceAssociationsStatusOutput, bool) bool) error { + return c.DescribeInstanceAssociationsStatusPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeInstanceAssociationsStatusPagesWithContext same as DescribeInstanceAssociationsStatusPages 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 *SSM) DescribeInstanceAssociationsStatusPagesWithContext(ctx aws.Context, input *DescribeInstanceAssociationsStatusInput, fn func(*DescribeInstanceAssociationsStatusOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeInstanceAssociationsStatusInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstanceAssociationsStatusRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeInstanceAssociationsStatusOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeInstanceInformation = "DescribeInstanceInformation" // DescribeInstanceInformationRequest generates a "aws/request.Request" representing the @@ -3521,16 +3988,18 @@ func (c *SSM) DescribeInstanceInformationRequest(input *DescribeInstanceInformat // DescribeInstanceInformation API operation for Amazon Simple Systems Manager (SSM). // -// Describes one or more of your instances. You can use this to get information -// about instances like the operating system platform, the SSM Agent version -// (Linux), status etc. If you specify one or more instance IDs, it returns -// information for those instances. If you do not specify instance IDs, it returns -// information for all your instances. If you specify an instance ID that is -// not valid or an instance that you do not own, you receive an error. +// Describes one or more of your instances, including information about the +// operating system platform, the version of SSM Agent installed on the instance, +// instance status, and so on. +// +// If you specify one or more instance IDs, it returns information for those +// instances. If you do not specify instance IDs, it returns information for +// all your instances. If you specify an instance ID that is not valid or an +// instance that you do not own, you receive an error. // // The IamRole field for this API action is the Amazon Identity and Access Management // (IAM) role assigned to on-premises instances. This call does not return the -// IAM role for Amazon EC2 instances. +// IAM role for EC2 instances. // // 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 @@ -3669,6 +4138,12 @@ func (c *SSM) DescribeInstancePatchStatesRequest(input *DescribeInstancePatchSta Name: opDescribeInstancePatchStates, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3720,6 +4195,58 @@ func (c *SSM) DescribeInstancePatchStatesWithContext(ctx aws.Context, input *Des return out, req.Send() } +// DescribeInstancePatchStatesPages iterates over the pages of a DescribeInstancePatchStates operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeInstancePatchStates method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeInstancePatchStates operation. +// pageNum := 0 +// err := client.DescribeInstancePatchStatesPages(params, +// func(page *ssm.DescribeInstancePatchStatesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeInstancePatchStatesPages(input *DescribeInstancePatchStatesInput, fn func(*DescribeInstancePatchStatesOutput, bool) bool) error { + return c.DescribeInstancePatchStatesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeInstancePatchStatesPagesWithContext same as DescribeInstancePatchStatesPages 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 *SSM) DescribeInstancePatchStatesPagesWithContext(ctx aws.Context, input *DescribeInstancePatchStatesInput, fn func(*DescribeInstancePatchStatesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeInstancePatchStatesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstancePatchStatesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeInstancePatchStatesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeInstancePatchStatesForPatchGroup = "DescribeInstancePatchStatesForPatchGroup" // DescribeInstancePatchStatesForPatchGroupRequest generates a "aws/request.Request" representing the @@ -3751,6 +4278,12 @@ func (c *SSM) DescribeInstancePatchStatesForPatchGroupRequest(input *DescribeIns Name: opDescribeInstancePatchStatesForPatchGroup, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3807,6 +4340,58 @@ func (c *SSM) DescribeInstancePatchStatesForPatchGroupWithContext(ctx aws.Contex return out, req.Send() } +// DescribeInstancePatchStatesForPatchGroupPages iterates over the pages of a DescribeInstancePatchStatesForPatchGroup operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeInstancePatchStatesForPatchGroup method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeInstancePatchStatesForPatchGroup operation. +// pageNum := 0 +// err := client.DescribeInstancePatchStatesForPatchGroupPages(params, +// func(page *ssm.DescribeInstancePatchStatesForPatchGroupOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeInstancePatchStatesForPatchGroupPages(input *DescribeInstancePatchStatesForPatchGroupInput, fn func(*DescribeInstancePatchStatesForPatchGroupOutput, bool) bool) error { + return c.DescribeInstancePatchStatesForPatchGroupPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeInstancePatchStatesForPatchGroupPagesWithContext same as DescribeInstancePatchStatesForPatchGroupPages 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 *SSM) DescribeInstancePatchStatesForPatchGroupPagesWithContext(ctx aws.Context, input *DescribeInstancePatchStatesForPatchGroupInput, fn func(*DescribeInstancePatchStatesForPatchGroupOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeInstancePatchStatesForPatchGroupInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstancePatchStatesForPatchGroupRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeInstancePatchStatesForPatchGroupOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeInstancePatches = "DescribeInstancePatches" // DescribeInstancePatchesRequest generates a "aws/request.Request" representing the @@ -3838,6 +4423,12 @@ func (c *SSM) DescribeInstancePatchesRequest(input *DescribeInstancePatchesInput Name: opDescribeInstancePatches, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3906,6 +4497,58 @@ func (c *SSM) DescribeInstancePatchesWithContext(ctx aws.Context, input *Describ return out, req.Send() } +// DescribeInstancePatchesPages iterates over the pages of a DescribeInstancePatches operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeInstancePatches method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeInstancePatches operation. +// pageNum := 0 +// err := client.DescribeInstancePatchesPages(params, +// func(page *ssm.DescribeInstancePatchesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeInstancePatchesPages(input *DescribeInstancePatchesInput, fn func(*DescribeInstancePatchesOutput, bool) bool) error { + return c.DescribeInstancePatchesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeInstancePatchesPagesWithContext same as DescribeInstancePatchesPages 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 *SSM) DescribeInstancePatchesPagesWithContext(ctx aws.Context, input *DescribeInstancePatchesInput, fn func(*DescribeInstancePatchesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeInstancePatchesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInstancePatchesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeInstancePatchesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeInventoryDeletions = "DescribeInventoryDeletions" // DescribeInventoryDeletionsRequest generates a "aws/request.Request" representing the @@ -3937,6 +4580,12 @@ func (c *SSM) DescribeInventoryDeletionsRequest(input *DescribeInventoryDeletion Name: opDescribeInventoryDeletions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -3992,6 +4641,58 @@ func (c *SSM) DescribeInventoryDeletionsWithContext(ctx aws.Context, input *Desc return out, req.Send() } +// DescribeInventoryDeletionsPages iterates over the pages of a DescribeInventoryDeletions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeInventoryDeletions method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeInventoryDeletions operation. +// pageNum := 0 +// err := client.DescribeInventoryDeletionsPages(params, +// func(page *ssm.DescribeInventoryDeletionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeInventoryDeletionsPages(input *DescribeInventoryDeletionsInput, fn func(*DescribeInventoryDeletionsOutput, bool) bool) error { + return c.DescribeInventoryDeletionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeInventoryDeletionsPagesWithContext same as DescribeInventoryDeletionsPages 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 *SSM) DescribeInventoryDeletionsPagesWithContext(ctx aws.Context, input *DescribeInventoryDeletionsInput, fn func(*DescribeInventoryDeletionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeInventoryDeletionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeInventoryDeletionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeInventoryDeletionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMaintenanceWindowExecutionTaskInvocations = "DescribeMaintenanceWindowExecutionTaskInvocations" // DescribeMaintenanceWindowExecutionTaskInvocationsRequest generates a "aws/request.Request" representing the @@ -4023,6 +4724,12 @@ func (c *SSM) DescribeMaintenanceWindowExecutionTaskInvocationsRequest(input *De Name: opDescribeMaintenanceWindowExecutionTaskInvocations, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4052,7 +4759,7 @@ func (c *SSM) DescribeMaintenanceWindowExecutionTaskInvocationsRequest(input *De // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -4080,6 +4787,58 @@ func (c *SSM) DescribeMaintenanceWindowExecutionTaskInvocationsWithContext(ctx a return out, req.Send() } +// DescribeMaintenanceWindowExecutionTaskInvocationsPages iterates over the pages of a DescribeMaintenanceWindowExecutionTaskInvocations operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeMaintenanceWindowExecutionTaskInvocations method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeMaintenanceWindowExecutionTaskInvocations operation. +// pageNum := 0 +// err := client.DescribeMaintenanceWindowExecutionTaskInvocationsPages(params, +// func(page *ssm.DescribeMaintenanceWindowExecutionTaskInvocationsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeMaintenanceWindowExecutionTaskInvocationsPages(input *DescribeMaintenanceWindowExecutionTaskInvocationsInput, fn func(*DescribeMaintenanceWindowExecutionTaskInvocationsOutput, bool) bool) error { + return c.DescribeMaintenanceWindowExecutionTaskInvocationsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeMaintenanceWindowExecutionTaskInvocationsPagesWithContext same as DescribeMaintenanceWindowExecutionTaskInvocationsPages 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 *SSM) DescribeMaintenanceWindowExecutionTaskInvocationsPagesWithContext(ctx aws.Context, input *DescribeMaintenanceWindowExecutionTaskInvocationsInput, fn func(*DescribeMaintenanceWindowExecutionTaskInvocationsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeMaintenanceWindowExecutionTaskInvocationsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeMaintenanceWindowExecutionTaskInvocationsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeMaintenanceWindowExecutionTaskInvocationsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMaintenanceWindowExecutionTasks = "DescribeMaintenanceWindowExecutionTasks" // DescribeMaintenanceWindowExecutionTasksRequest generates a "aws/request.Request" representing the @@ -4111,6 +4870,12 @@ func (c *SSM) DescribeMaintenanceWindowExecutionTasksRequest(input *DescribeMain Name: opDescribeMaintenanceWindowExecutionTasks, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4139,7 +4904,7 @@ func (c *SSM) DescribeMaintenanceWindowExecutionTasksRequest(input *DescribeMain // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -4167,6 +4932,58 @@ func (c *SSM) DescribeMaintenanceWindowExecutionTasksWithContext(ctx aws.Context return out, req.Send() } +// DescribeMaintenanceWindowExecutionTasksPages iterates over the pages of a DescribeMaintenanceWindowExecutionTasks operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeMaintenanceWindowExecutionTasks method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeMaintenanceWindowExecutionTasks operation. +// pageNum := 0 +// err := client.DescribeMaintenanceWindowExecutionTasksPages(params, +// func(page *ssm.DescribeMaintenanceWindowExecutionTasksOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeMaintenanceWindowExecutionTasksPages(input *DescribeMaintenanceWindowExecutionTasksInput, fn func(*DescribeMaintenanceWindowExecutionTasksOutput, bool) bool) error { + return c.DescribeMaintenanceWindowExecutionTasksPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeMaintenanceWindowExecutionTasksPagesWithContext same as DescribeMaintenanceWindowExecutionTasksPages 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 *SSM) DescribeMaintenanceWindowExecutionTasksPagesWithContext(ctx aws.Context, input *DescribeMaintenanceWindowExecutionTasksInput, fn func(*DescribeMaintenanceWindowExecutionTasksOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeMaintenanceWindowExecutionTasksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeMaintenanceWindowExecutionTasksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeMaintenanceWindowExecutionTasksOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMaintenanceWindowExecutions = "DescribeMaintenanceWindowExecutions" // DescribeMaintenanceWindowExecutionsRequest generates a "aws/request.Request" representing the @@ -4198,6 +5015,12 @@ func (c *SSM) DescribeMaintenanceWindowExecutionsRequest(input *DescribeMaintena Name: opDescribeMaintenanceWindowExecutions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4248,6 +5071,58 @@ func (c *SSM) DescribeMaintenanceWindowExecutionsWithContext(ctx aws.Context, in return out, req.Send() } +// DescribeMaintenanceWindowExecutionsPages iterates over the pages of a DescribeMaintenanceWindowExecutions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeMaintenanceWindowExecutions method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeMaintenanceWindowExecutions operation. +// pageNum := 0 +// err := client.DescribeMaintenanceWindowExecutionsPages(params, +// func(page *ssm.DescribeMaintenanceWindowExecutionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeMaintenanceWindowExecutionsPages(input *DescribeMaintenanceWindowExecutionsInput, fn func(*DescribeMaintenanceWindowExecutionsOutput, bool) bool) error { + return c.DescribeMaintenanceWindowExecutionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeMaintenanceWindowExecutionsPagesWithContext same as DescribeMaintenanceWindowExecutionsPages 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 *SSM) DescribeMaintenanceWindowExecutionsPagesWithContext(ctx aws.Context, input *DescribeMaintenanceWindowExecutionsInput, fn func(*DescribeMaintenanceWindowExecutionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeMaintenanceWindowExecutionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeMaintenanceWindowExecutionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeMaintenanceWindowExecutionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMaintenanceWindowSchedule = "DescribeMaintenanceWindowSchedule" // DescribeMaintenanceWindowScheduleRequest generates a "aws/request.Request" representing the @@ -4279,6 +5154,12 @@ func (c *SSM) DescribeMaintenanceWindowScheduleRequest(input *DescribeMaintenanc Name: opDescribeMaintenanceWindowSchedule, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4310,7 +5191,7 @@ func (c *SSM) DescribeMaintenanceWindowScheduleRequest(input *DescribeMaintenanc // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // See also, https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/DescribeMaintenanceWindowSchedule @@ -4335,6 +5216,58 @@ func (c *SSM) DescribeMaintenanceWindowScheduleWithContext(ctx aws.Context, inpu return out, req.Send() } +// DescribeMaintenanceWindowSchedulePages iterates over the pages of a DescribeMaintenanceWindowSchedule operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeMaintenanceWindowSchedule method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeMaintenanceWindowSchedule operation. +// pageNum := 0 +// err := client.DescribeMaintenanceWindowSchedulePages(params, +// func(page *ssm.DescribeMaintenanceWindowScheduleOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeMaintenanceWindowSchedulePages(input *DescribeMaintenanceWindowScheduleInput, fn func(*DescribeMaintenanceWindowScheduleOutput, bool) bool) error { + return c.DescribeMaintenanceWindowSchedulePagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeMaintenanceWindowSchedulePagesWithContext same as DescribeMaintenanceWindowSchedulePages 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 *SSM) DescribeMaintenanceWindowSchedulePagesWithContext(ctx aws.Context, input *DescribeMaintenanceWindowScheduleInput, fn func(*DescribeMaintenanceWindowScheduleOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeMaintenanceWindowScheduleInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeMaintenanceWindowScheduleRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeMaintenanceWindowScheduleOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMaintenanceWindowTargets = "DescribeMaintenanceWindowTargets" // DescribeMaintenanceWindowTargetsRequest generates a "aws/request.Request" representing the @@ -4366,6 +5299,12 @@ func (c *SSM) DescribeMaintenanceWindowTargetsRequest(input *DescribeMaintenance Name: opDescribeMaintenanceWindowTargets, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4394,7 +5333,7 @@ func (c *SSM) DescribeMaintenanceWindowTargetsRequest(input *DescribeMaintenance // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -4422,6 +5361,58 @@ func (c *SSM) DescribeMaintenanceWindowTargetsWithContext(ctx aws.Context, input return out, req.Send() } +// DescribeMaintenanceWindowTargetsPages iterates over the pages of a DescribeMaintenanceWindowTargets operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeMaintenanceWindowTargets method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeMaintenanceWindowTargets operation. +// pageNum := 0 +// err := client.DescribeMaintenanceWindowTargetsPages(params, +// func(page *ssm.DescribeMaintenanceWindowTargetsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeMaintenanceWindowTargetsPages(input *DescribeMaintenanceWindowTargetsInput, fn func(*DescribeMaintenanceWindowTargetsOutput, bool) bool) error { + return c.DescribeMaintenanceWindowTargetsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeMaintenanceWindowTargetsPagesWithContext same as DescribeMaintenanceWindowTargetsPages 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 *SSM) DescribeMaintenanceWindowTargetsPagesWithContext(ctx aws.Context, input *DescribeMaintenanceWindowTargetsInput, fn func(*DescribeMaintenanceWindowTargetsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeMaintenanceWindowTargetsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeMaintenanceWindowTargetsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeMaintenanceWindowTargetsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMaintenanceWindowTasks = "DescribeMaintenanceWindowTasks" // DescribeMaintenanceWindowTasksRequest generates a "aws/request.Request" representing the @@ -4453,6 +5444,12 @@ func (c *SSM) DescribeMaintenanceWindowTasksRequest(input *DescribeMaintenanceWi Name: opDescribeMaintenanceWindowTasks, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4481,7 +5478,7 @@ func (c *SSM) DescribeMaintenanceWindowTasksRequest(input *DescribeMaintenanceWi // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -4509,6 +5506,58 @@ func (c *SSM) DescribeMaintenanceWindowTasksWithContext(ctx aws.Context, input * return out, req.Send() } +// DescribeMaintenanceWindowTasksPages iterates over the pages of a DescribeMaintenanceWindowTasks operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeMaintenanceWindowTasks method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeMaintenanceWindowTasks operation. +// pageNum := 0 +// err := client.DescribeMaintenanceWindowTasksPages(params, +// func(page *ssm.DescribeMaintenanceWindowTasksOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeMaintenanceWindowTasksPages(input *DescribeMaintenanceWindowTasksInput, fn func(*DescribeMaintenanceWindowTasksOutput, bool) bool) error { + return c.DescribeMaintenanceWindowTasksPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeMaintenanceWindowTasksPagesWithContext same as DescribeMaintenanceWindowTasksPages 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 *SSM) DescribeMaintenanceWindowTasksPagesWithContext(ctx aws.Context, input *DescribeMaintenanceWindowTasksInput, fn func(*DescribeMaintenanceWindowTasksOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeMaintenanceWindowTasksInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeMaintenanceWindowTasksRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeMaintenanceWindowTasksOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMaintenanceWindows = "DescribeMaintenanceWindows" // DescribeMaintenanceWindowsRequest generates a "aws/request.Request" representing the @@ -4540,6 +5589,12 @@ func (c *SSM) DescribeMaintenanceWindowsRequest(input *DescribeMaintenanceWindow Name: opDescribeMaintenanceWindows, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4588,6 +5643,58 @@ func (c *SSM) DescribeMaintenanceWindowsWithContext(ctx aws.Context, input *Desc return out, req.Send() } +// DescribeMaintenanceWindowsPages iterates over the pages of a DescribeMaintenanceWindows operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeMaintenanceWindows method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeMaintenanceWindows operation. +// pageNum := 0 +// err := client.DescribeMaintenanceWindowsPages(params, +// func(page *ssm.DescribeMaintenanceWindowsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeMaintenanceWindowsPages(input *DescribeMaintenanceWindowsInput, fn func(*DescribeMaintenanceWindowsOutput, bool) bool) error { + return c.DescribeMaintenanceWindowsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeMaintenanceWindowsPagesWithContext same as DescribeMaintenanceWindowsPages 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 *SSM) DescribeMaintenanceWindowsPagesWithContext(ctx aws.Context, input *DescribeMaintenanceWindowsInput, fn func(*DescribeMaintenanceWindowsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeMaintenanceWindowsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeMaintenanceWindowsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeMaintenanceWindowsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeMaintenanceWindowsForTarget = "DescribeMaintenanceWindowsForTarget" // DescribeMaintenanceWindowsForTargetRequest generates a "aws/request.Request" representing the @@ -4619,6 +5726,12 @@ func (c *SSM) DescribeMaintenanceWindowsForTargetRequest(input *DescribeMaintena Name: opDescribeMaintenanceWindowsForTarget, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4668,6 +5781,58 @@ func (c *SSM) DescribeMaintenanceWindowsForTargetWithContext(ctx aws.Context, in return out, req.Send() } +// DescribeMaintenanceWindowsForTargetPages iterates over the pages of a DescribeMaintenanceWindowsForTarget operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeMaintenanceWindowsForTarget method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeMaintenanceWindowsForTarget operation. +// pageNum := 0 +// err := client.DescribeMaintenanceWindowsForTargetPages(params, +// func(page *ssm.DescribeMaintenanceWindowsForTargetOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeMaintenanceWindowsForTargetPages(input *DescribeMaintenanceWindowsForTargetInput, fn func(*DescribeMaintenanceWindowsForTargetOutput, bool) bool) error { + return c.DescribeMaintenanceWindowsForTargetPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeMaintenanceWindowsForTargetPagesWithContext same as DescribeMaintenanceWindowsForTargetPages 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 *SSM) DescribeMaintenanceWindowsForTargetPagesWithContext(ctx aws.Context, input *DescribeMaintenanceWindowsForTargetInput, fn func(*DescribeMaintenanceWindowsForTargetOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeMaintenanceWindowsForTargetInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeMaintenanceWindowsForTargetRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeMaintenanceWindowsForTargetOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeOpsItems = "DescribeOpsItems" // DescribeOpsItemsRequest generates a "aws/request.Request" representing the @@ -4699,6 +5864,12 @@ func (c *SSM) DescribeOpsItemsRequest(input *DescribeOpsItemsInput) (req *reques Name: opDescribeOpsItems, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4714,13 +5885,13 @@ func (c *SSM) DescribeOpsItemsRequest(input *DescribeOpsItemsInput) (req *reques // // Query a set of OpsItems. You must have permission in AWS Identity and Access // Management (IAM) to query a list of OpsItems. For more information, see Getting -// Started with OpsCenter (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-getting-started.html) +// started with OpsCenter (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-getting-started.html) // in the AWS Systems Manager User Guide. // // Operations engineers and IT professionals use OpsCenter to view, investigate, // and remediate operational issues impacting the performance and health of // their AWS resources. For more information, see AWS Systems Manager OpsCenter -// (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html) +// (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html) // in the AWS Systems Manager User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -4756,6 +5927,58 @@ func (c *SSM) DescribeOpsItemsWithContext(ctx aws.Context, input *DescribeOpsIte return out, req.Send() } +// DescribeOpsItemsPages iterates over the pages of a DescribeOpsItems operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeOpsItems method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeOpsItems operation. +// pageNum := 0 +// err := client.DescribeOpsItemsPages(params, +// func(page *ssm.DescribeOpsItemsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeOpsItemsPages(input *DescribeOpsItemsInput, fn func(*DescribeOpsItemsOutput, bool) bool) error { + return c.DescribeOpsItemsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeOpsItemsPagesWithContext same as DescribeOpsItemsPages 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 *SSM) DescribeOpsItemsPagesWithContext(ctx aws.Context, input *DescribeOpsItemsInput, fn func(*DescribeOpsItemsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeOpsItemsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeOpsItemsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeOpsItemsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeParameters = "DescribeParameters" // DescribeParametersRequest generates a "aws/request.Request" representing the @@ -4945,6 +6168,12 @@ func (c *SSM) DescribePatchBaselinesRequest(input *DescribePatchBaselinesInput) Name: opDescribePatchBaselines, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -4993,6 +6222,58 @@ func (c *SSM) DescribePatchBaselinesWithContext(ctx aws.Context, input *Describe return out, req.Send() } +// DescribePatchBaselinesPages iterates over the pages of a DescribePatchBaselines operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribePatchBaselines method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribePatchBaselines operation. +// pageNum := 0 +// err := client.DescribePatchBaselinesPages(params, +// func(page *ssm.DescribePatchBaselinesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribePatchBaselinesPages(input *DescribePatchBaselinesInput, fn func(*DescribePatchBaselinesOutput, bool) bool) error { + return c.DescribePatchBaselinesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribePatchBaselinesPagesWithContext same as DescribePatchBaselinesPages 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 *SSM) DescribePatchBaselinesPagesWithContext(ctx aws.Context, input *DescribePatchBaselinesInput, fn func(*DescribePatchBaselinesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribePatchBaselinesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribePatchBaselinesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribePatchBaselinesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribePatchGroupState = "DescribePatchGroupState" // DescribePatchGroupStateRequest generates a "aws/request.Request" representing the @@ -5106,6 +6387,12 @@ func (c *SSM) DescribePatchGroupsRequest(input *DescribePatchGroupsInput) (req * Name: opDescribePatchGroups, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -5154,6 +6441,58 @@ func (c *SSM) DescribePatchGroupsWithContext(ctx aws.Context, input *DescribePat return out, req.Send() } +// DescribePatchGroupsPages iterates over the pages of a DescribePatchGroups operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribePatchGroups method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribePatchGroups operation. +// pageNum := 0 +// err := client.DescribePatchGroupsPages(params, +// func(page *ssm.DescribePatchGroupsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribePatchGroupsPages(input *DescribePatchGroupsInput, fn func(*DescribePatchGroupsOutput, bool) bool) error { + return c.DescribePatchGroupsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribePatchGroupsPagesWithContext same as DescribePatchGroupsPages 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 *SSM) DescribePatchGroupsPagesWithContext(ctx aws.Context, input *DescribePatchGroupsInput, fn func(*DescribePatchGroupsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribePatchGroupsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribePatchGroupsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribePatchGroupsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribePatchProperties = "DescribePatchProperties" // DescribePatchPropertiesRequest generates a "aws/request.Request" representing the @@ -5185,6 +6524,12 @@ func (c *SSM) DescribePatchPropertiesRequest(input *DescribePatchPropertiesInput Name: opDescribePatchProperties, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -5207,10 +6552,6 @@ func (c *SSM) DescribePatchPropertiesRequest(input *DescribePatchPropertiesInput // The following section lists the properties that can be used in filters for // each major operating system type: // -// WINDOWS -// -// Valid properties: PRODUCT, PRODUCT_FAMILY, CLASSIFICATION, MSRC_SEVERITY -// // AMAZON_LINUX // // Valid properties: PRODUCT, CLASSIFICATION, SEVERITY @@ -5219,10 +6560,18 @@ func (c *SSM) DescribePatchPropertiesRequest(input *DescribePatchPropertiesInput // // Valid properties: PRODUCT, CLASSIFICATION, SEVERITY // -// UBUNTU +// CENTOS +// +// Valid properties: PRODUCT, CLASSIFICATION, SEVERITY +// +// DEBIAN // // Valid properties: PRODUCT, PRIORITY // +// ORACLE_LINUX +// +// Valid properties: PRODUCT, CLASSIFICATION, SEVERITY +// // REDHAT_ENTERPRISE_LINUX // // Valid properties: PRODUCT, CLASSIFICATION, SEVERITY @@ -5231,9 +6580,13 @@ func (c *SSM) DescribePatchPropertiesRequest(input *DescribePatchPropertiesInput // // Valid properties: PRODUCT, CLASSIFICATION, SEVERITY // -// CENTOS +// UBUNTU // -// Valid properties: PRODUCT, CLASSIFICATION, SEVERITY +// Valid properties: PRODUCT, PRIORITY +// +// WINDOWS +// +// Valid properties: PRODUCT, PRODUCT_FAMILY, CLASSIFICATION, MSRC_SEVERITY // // 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 @@ -5268,6 +6621,58 @@ func (c *SSM) DescribePatchPropertiesWithContext(ctx aws.Context, input *Describ return out, req.Send() } +// DescribePatchPropertiesPages iterates over the pages of a DescribePatchProperties operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribePatchProperties method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribePatchProperties operation. +// pageNum := 0 +// err := client.DescribePatchPropertiesPages(params, +// func(page *ssm.DescribePatchPropertiesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribePatchPropertiesPages(input *DescribePatchPropertiesInput, fn func(*DescribePatchPropertiesOutput, bool) bool) error { + return c.DescribePatchPropertiesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribePatchPropertiesPagesWithContext same as DescribePatchPropertiesPages 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 *SSM) DescribePatchPropertiesPagesWithContext(ctx aws.Context, input *DescribePatchPropertiesInput, fn func(*DescribePatchPropertiesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribePatchPropertiesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribePatchPropertiesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribePatchPropertiesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opDescribeSessions = "DescribeSessions" // DescribeSessionsRequest generates a "aws/request.Request" representing the @@ -5299,6 +6704,12 @@ func (c *SSM) DescribeSessionsRequest(input *DescribeSessionsInput) (req *reques Name: opDescribeSessions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -5354,6 +6765,58 @@ func (c *SSM) DescribeSessionsWithContext(ctx aws.Context, input *DescribeSessio return out, req.Send() } +// DescribeSessionsPages iterates over the pages of a DescribeSessions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See DescribeSessions method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a DescribeSessions operation. +// pageNum := 0 +// err := client.DescribeSessionsPages(params, +// func(page *ssm.DescribeSessionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) DescribeSessionsPages(input *DescribeSessionsInput, fn func(*DescribeSessionsOutput, bool) bool) error { + return c.DescribeSessionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// DescribeSessionsPagesWithContext same as DescribeSessionsPages 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 *SSM) DescribeSessionsPagesWithContext(ctx aws.Context, input *DescribeSessionsInput, fn func(*DescribeSessionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *DescribeSessionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.DescribeSessionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*DescribeSessionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetAutomationExecution = "GetAutomationExecution" // GetAutomationExecutionRequest generates a "aws/request.Request" representing the @@ -5486,8 +6949,14 @@ func (c *SSM) GetCalendarStateRequest(input *GetCalendarStateInput) (req *reques // of the calendar at a specific time, and returns the next time that the Change // Calendar state will transition. If you do not specify a time, GetCalendarState // assumes the current time. Change Calendar entries have two possible states: -// OPEN or CLOSED. For more information about Systems Manager Change Calendar, -// see AWS Systems Manager Change Calendar (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-change-calendar.html) +// OPEN or CLOSED. +// +// If you specify more than one calendar in a request, the command returns the +// status of OPEN only if all calendars in the request are open. If one or more +// calendars in the request are closed, the status returned is CLOSED. +// +// For more information about Systems Manager Change Calendar, see AWS Systems +// Manager Change Calendar (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-change-calendar.html) // in the AWS Systems Manager User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -5680,7 +7149,7 @@ func (c *SSM) GetConnectionStatusRequest(input *GetConnectionStatusInput) (req * // GetConnectionStatus API operation for Amazon Simple Systems Manager (SSM). // // Retrieves the Session Manager connection status for an instance to determine -// whether it is connected and ready to receive Session Manager connections. +// whether it is running and ready to receive Session Manager connections. // // 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 @@ -5859,14 +7328,13 @@ func (c *SSM) GetDeployablePatchSnapshotForInstanceRequest(input *GetDeployableP // // * UnsupportedOperatingSystem // The operating systems you specified is not supported, or the operation is -// not supported for the operating system. Valid operating systems include: -// Windows, AmazonLinux, RedhatEnterpriseLinux, and Ubuntu. +// not supported for the operating system. // // * UnsupportedFeatureRequiredException -// Microsoft application patching is only available on EC2 instances and Advanced -// Instances. To patch Microsoft applications on on-premises servers and VMs, -// you must enable Advanced Instances. For more information, see Using the Advanced-Instances -// Tier (http://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-managedinstances-advanced.html) +// Microsoft application patching is only available on EC2 instances and advanced +// instances. To patch Microsoft applications on on-premises servers and VMs, +// you must enable advanced instances. For more information, see Using the advanced-instances +// tier (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-managedinstances-advanced.html) // in the AWS Systems Manager User Guide. // // See also, https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06/GetDeployablePatchSnapshotForInstance @@ -6007,6 +7475,12 @@ func (c *SSM) GetInventoryRequest(input *GetInventoryInput) (req *request.Reques Name: opGetInventory, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -6075,6 +7549,58 @@ func (c *SSM) GetInventoryWithContext(ctx aws.Context, input *GetInventoryInput, return out, req.Send() } +// GetInventoryPages iterates over the pages of a GetInventory operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetInventory method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a GetInventory operation. +// pageNum := 0 +// err := client.GetInventoryPages(params, +// func(page *ssm.GetInventoryOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) GetInventoryPages(input *GetInventoryInput, fn func(*GetInventoryOutput, bool) bool) error { + return c.GetInventoryPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetInventoryPagesWithContext same as GetInventoryPages 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 *SSM) GetInventoryPagesWithContext(ctx aws.Context, input *GetInventoryInput, fn func(*GetInventoryOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetInventoryInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetInventoryRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetInventoryOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetInventorySchema = "GetInventorySchema" // GetInventorySchemaRequest generates a "aws/request.Request" representing the @@ -6106,6 +7632,12 @@ func (c *SSM) GetInventorySchemaRequest(input *GetInventorySchemaInput) (req *re Name: opGetInventorySchema, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -6161,6 +7693,58 @@ func (c *SSM) GetInventorySchemaWithContext(ctx aws.Context, input *GetInventory return out, req.Send() } +// GetInventorySchemaPages iterates over the pages of a GetInventorySchema operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetInventorySchema method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a GetInventorySchema operation. +// pageNum := 0 +// err := client.GetInventorySchemaPages(params, +// func(page *ssm.GetInventorySchemaOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) GetInventorySchemaPages(input *GetInventorySchemaInput, fn func(*GetInventorySchemaOutput, bool) bool) error { + return c.GetInventorySchemaPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetInventorySchemaPagesWithContext same as GetInventorySchemaPages 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 *SSM) GetInventorySchemaPagesWithContext(ctx aws.Context, input *GetInventorySchemaInput, fn func(*GetInventorySchemaOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetInventorySchemaInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetInventorySchemaRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetInventorySchemaOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetMaintenanceWindow = "GetMaintenanceWindow" // GetMaintenanceWindowRequest generates a "aws/request.Request" representing the @@ -6220,7 +7804,7 @@ func (c *SSM) GetMaintenanceWindowRequest(input *GetMaintenanceWindowInput) (req // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -6307,7 +7891,7 @@ func (c *SSM) GetMaintenanceWindowExecutionRequest(input *GetMaintenanceWindowEx // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -6395,7 +7979,7 @@ func (c *SSM) GetMaintenanceWindowExecutionTaskRequest(input *GetMaintenanceWind // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -6482,7 +8066,7 @@ func (c *SSM) GetMaintenanceWindowExecutionTaskInvocationRequest(input *GetMaint // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -6569,7 +8153,7 @@ func (c *SSM) GetMaintenanceWindowTaskRequest(input *GetMaintenanceWindowTaskInp // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -6643,13 +8227,13 @@ func (c *SSM) GetOpsItemRequest(input *GetOpsItemInput) (req *request.Request, o // // Get information about an OpsItem by using the ID. You must have permission // in AWS Identity and Access Management (IAM) to view information about an -// OpsItem. For more information, see Getting Started with OpsCenter (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-getting-started.html) +// OpsItem. For more information, see Getting started with OpsCenter (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-getting-started.html) // in the AWS Systems Manager User Guide. // // Operations engineers and IT professionals use OpsCenter to view, investigate, // and remediate operational issues impacting the performance and health of // their AWS resources. For more information, see AWS Systems Manager OpsCenter -// (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html) +// (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html) // in the AWS Systems Manager User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -6719,6 +8303,12 @@ func (c *SSM) GetOpsSummaryRequest(input *GetOpsSummaryInput) (req *request.Requ Name: opGetOpsSummary, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -6784,6 +8374,58 @@ func (c *SSM) GetOpsSummaryWithContext(ctx aws.Context, input *GetOpsSummaryInpu return out, req.Send() } +// GetOpsSummaryPages iterates over the pages of a GetOpsSummary operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See GetOpsSummary method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a GetOpsSummary operation. +// pageNum := 0 +// err := client.GetOpsSummaryPages(params, +// func(page *ssm.GetOpsSummaryOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) GetOpsSummaryPages(input *GetOpsSummaryInput, fn func(*GetOpsSummaryOutput, bool) bool) error { + return c.GetOpsSummaryPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// GetOpsSummaryPagesWithContext same as GetOpsSummaryPages 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 *SSM) GetOpsSummaryPagesWithContext(ctx aws.Context, input *GetOpsSummaryInput, fn func(*GetOpsSummaryOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *GetOpsSummaryInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetOpsSummaryRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*GetOpsSummaryOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opGetParameter = "GetParameter" // GetParameterRequest generates a "aws/request.Request" representing the @@ -7323,7 +8965,7 @@ func (c *SSM) GetPatchBaselineRequest(input *GetPatchBaselineInput) (req *reques // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InvalidResourceId @@ -7684,6 +9326,12 @@ func (c *SSM) ListAssociationVersionsRequest(input *ListAssociationVersionsInput Name: opListAssociationVersions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -7738,6 +9386,58 @@ func (c *SSM) ListAssociationVersionsWithContext(ctx aws.Context, input *ListAss return out, req.Send() } +// ListAssociationVersionsPages iterates over the pages of a ListAssociationVersions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListAssociationVersions method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a ListAssociationVersions operation. +// pageNum := 0 +// err := client.ListAssociationVersionsPages(params, +// func(page *ssm.ListAssociationVersionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) ListAssociationVersionsPages(input *ListAssociationVersionsInput, fn func(*ListAssociationVersionsOutput, bool) bool) error { + return c.ListAssociationVersionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListAssociationVersionsPagesWithContext same as ListAssociationVersionsPages 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 *SSM) ListAssociationVersionsPagesWithContext(ctx aws.Context, input *ListAssociationVersionsInput, fn func(*ListAssociationVersionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListAssociationVersionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListAssociationVersionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListAssociationVersionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListAssociations = "ListAssociations" // ListAssociationsRequest generates a "aws/request.Request" representing the @@ -8229,6 +9929,12 @@ func (c *SSM) ListComplianceItemsRequest(input *ListComplianceItemsInput) (req * Name: opListComplianceItems, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -8295,6 +10001,58 @@ func (c *SSM) ListComplianceItemsWithContext(ctx aws.Context, input *ListComplia return out, req.Send() } +// ListComplianceItemsPages iterates over the pages of a ListComplianceItems operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListComplianceItems method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a ListComplianceItems operation. +// pageNum := 0 +// err := client.ListComplianceItemsPages(params, +// func(page *ssm.ListComplianceItemsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) ListComplianceItemsPages(input *ListComplianceItemsInput, fn func(*ListComplianceItemsOutput, bool) bool) error { + return c.ListComplianceItemsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListComplianceItemsPagesWithContext same as ListComplianceItemsPages 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 *SSM) ListComplianceItemsPagesWithContext(ctx aws.Context, input *ListComplianceItemsInput, fn func(*ListComplianceItemsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListComplianceItemsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListComplianceItemsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListComplianceItemsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListComplianceSummaries = "ListComplianceSummaries" // ListComplianceSummariesRequest generates a "aws/request.Request" representing the @@ -8326,6 +10084,12 @@ func (c *SSM) ListComplianceSummariesRequest(input *ListComplianceSummariesInput Name: opListComplianceSummaries, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -8383,6 +10147,58 @@ func (c *SSM) ListComplianceSummariesWithContext(ctx aws.Context, input *ListCom return out, req.Send() } +// ListComplianceSummariesPages iterates over the pages of a ListComplianceSummaries operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListComplianceSummaries method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a ListComplianceSummaries operation. +// pageNum := 0 +// err := client.ListComplianceSummariesPages(params, +// func(page *ssm.ListComplianceSummariesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) ListComplianceSummariesPages(input *ListComplianceSummariesInput, fn func(*ListComplianceSummariesOutput, bool) bool) error { + return c.ListComplianceSummariesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListComplianceSummariesPagesWithContext same as ListComplianceSummariesPages 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 *SSM) ListComplianceSummariesPagesWithContext(ctx aws.Context, input *ListComplianceSummariesInput, fn func(*ListComplianceSummariesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListComplianceSummariesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListComplianceSummariesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListComplianceSummariesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListDocumentVersions = "ListDocumentVersions" // ListDocumentVersionsRequest generates a "aws/request.Request" representing the @@ -8414,6 +10230,12 @@ func (c *SSM) ListDocumentVersionsRequest(input *ListDocumentVersionsInput) (req Name: opListDocumentVersions, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -8468,6 +10290,58 @@ func (c *SSM) ListDocumentVersionsWithContext(ctx aws.Context, input *ListDocume return out, req.Send() } +// ListDocumentVersionsPages iterates over the pages of a ListDocumentVersions operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListDocumentVersions method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a ListDocumentVersions operation. +// pageNum := 0 +// err := client.ListDocumentVersionsPages(params, +// func(page *ssm.ListDocumentVersionsOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) ListDocumentVersionsPages(input *ListDocumentVersionsInput, fn func(*ListDocumentVersionsOutput, bool) bool) error { + return c.ListDocumentVersionsPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListDocumentVersionsPagesWithContext same as ListDocumentVersionsPages 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 *SSM) ListDocumentVersionsPagesWithContext(ctx aws.Context, input *ListDocumentVersionsInput, fn func(*ListDocumentVersionsOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListDocumentVersionsInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListDocumentVersionsRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListDocumentVersionsOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListDocuments = "ListDocuments" // ListDocumentsRequest generates a "aws/request.Request" representing the @@ -8744,6 +10618,12 @@ func (c *SSM) ListResourceComplianceSummariesRequest(input *ListResourceComplian Name: opListResourceComplianceSummaries, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -8801,6 +10681,58 @@ func (c *SSM) ListResourceComplianceSummariesWithContext(ctx aws.Context, input return out, req.Send() } +// ListResourceComplianceSummariesPages iterates over the pages of a ListResourceComplianceSummaries operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListResourceComplianceSummaries method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a ListResourceComplianceSummaries operation. +// pageNum := 0 +// err := client.ListResourceComplianceSummariesPages(params, +// func(page *ssm.ListResourceComplianceSummariesOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) ListResourceComplianceSummariesPages(input *ListResourceComplianceSummariesInput, fn func(*ListResourceComplianceSummariesOutput, bool) bool) error { + return c.ListResourceComplianceSummariesPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListResourceComplianceSummariesPagesWithContext same as ListResourceComplianceSummariesPages 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 *SSM) ListResourceComplianceSummariesPagesWithContext(ctx aws.Context, input *ListResourceComplianceSummariesInput, fn func(*ListResourceComplianceSummariesOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListResourceComplianceSummariesInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListResourceComplianceSummariesRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListResourceComplianceSummariesOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListResourceDataSync = "ListResourceDataSync" // ListResourceDataSyncRequest generates a "aws/request.Request" representing the @@ -8832,6 +10764,12 @@ func (c *SSM) ListResourceDataSyncRequest(input *ListResourceDataSyncInput) (req Name: opListResourceDataSync, HTTPMethod: "POST", HTTPPath: "/", + Paginator: &request.Paginator{ + InputTokens: []string{"NextToken"}, + OutputTokens: []string{"NextToken"}, + LimitToken: "MaxResults", + TruncationToken: "", + }, } if input == nil { @@ -8895,6 +10833,58 @@ func (c *SSM) ListResourceDataSyncWithContext(ctx aws.Context, input *ListResour return out, req.Send() } +// ListResourceDataSyncPages iterates over the pages of a ListResourceDataSync operation, +// calling the "fn" function with the response data for each page. To stop +// iterating, return false from the fn function. +// +// See ListResourceDataSync method for more information on how to use this operation. +// +// Note: This operation can generate multiple requests to a service. +// +// // Example iterating over at most 3 pages of a ListResourceDataSync operation. +// pageNum := 0 +// err := client.ListResourceDataSyncPages(params, +// func(page *ssm.ListResourceDataSyncOutput, lastPage bool) bool { +// pageNum++ +// fmt.Println(page) +// return pageNum <= 3 +// }) +// +func (c *SSM) ListResourceDataSyncPages(input *ListResourceDataSyncInput, fn func(*ListResourceDataSyncOutput, bool) bool) error { + return c.ListResourceDataSyncPagesWithContext(aws.BackgroundContext(), input, fn) +} + +// ListResourceDataSyncPagesWithContext same as ListResourceDataSyncPages 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 *SSM) ListResourceDataSyncPagesWithContext(ctx aws.Context, input *ListResourceDataSyncInput, fn func(*ListResourceDataSyncOutput, bool) bool, opts ...request.Option) error { + p := request.Pagination{ + NewRequest: func() (*request.Request, error) { + var inCpy *ListResourceDataSyncInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.ListResourceDataSyncRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + + for p.Next() { + if !fn(p.Page().(*ListResourceDataSyncOutput), !p.HasNextPage()) { + break + } + } + + return p.Err() +} + const opListTagsForResource = "ListTagsForResource" // ListTagsForResourceRequest generates a "aws/request.Request" representing the @@ -9424,7 +11414,7 @@ func (c *SSM) PutParameterRequest(input *PutParameterInput) (req *request.Reques // // * HierarchyLevelLimitExceededException // A hierarchy can have a maximum of 15 levels. For more information, see Requirements -// and Constraints for Parameter Names (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-parameter-name-constraints.html) +// and constraints for parameter names (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-parameter-name-constraints.html) // in the AWS Systems Manager User Guide. // // * HierarchyTypeMismatchException @@ -9550,7 +11540,7 @@ func (c *SSM) RegisterDefaultPatchBaselineRequest(input *RegisterDefaultPatchBas // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -9641,7 +11631,7 @@ func (c *SSM) RegisterPatchBaselineForPatchGroupRequest(input *RegisterPatchBase // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InvalidResourceId @@ -9653,7 +11643,7 @@ func (c *SSM) RegisterPatchBaselineForPatchGroupRequest(input *RegisterPatchBase // For example, too many maintenance windows or patch baselines have been created. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -9744,7 +11734,7 @@ func (c *SSM) RegisterTargetWithMaintenanceWindowRequest(input *RegisterTargetWi // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * ResourceLimitExceededException @@ -9752,7 +11742,7 @@ func (c *SSM) RegisterTargetWithMaintenanceWindowRequest(input *RegisterTargetWi // For example, too many maintenance windows or patch baselines have been created. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -9843,7 +11833,7 @@ func (c *SSM) RegisterTaskWithMaintenanceWindowRequest(input *RegisterTaskWithMa // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * ResourceLimitExceededException @@ -9851,7 +11841,7 @@ func (c *SSM) RegisterTaskWithMaintenanceWindowRequest(input *RegisterTaskWithMa // For example, too many maintenance windows or patch baselines have been created. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * FeatureNotAvailableException @@ -10140,7 +12130,7 @@ func (c *SSM) ResumeSessionRequest(input *ResumeSessionInput) (req *request.Requ // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -10357,7 +12347,7 @@ func (c *SSM) SendCommandRequest(input *SendCommandInput) (req *request.Request, // The role name can't contain invalid characters. Also verify that you specified // an IAM role for notifications that includes the required trust policy. For // information about configuring the IAM role for Run Command notifications, -// see Configuring Amazon SNS Notifications for Run Command (http://docs.aws.amazon.com/systems-manager/latest/userguide/rc-sns-notifications.html) +// see Configuring Amazon SNS Notifications for Run Command (https://docs.aws.amazon.com/systems-manager/latest/userguide/rc-sns-notifications.html) // in the AWS Systems Manager User Guide. // // * InvalidNotificationConfig @@ -10545,7 +12535,7 @@ func (c *SSM) StartAutomationExecutionRequest(input *StartAutomationExecutionInp // // * InvalidTarget // The target is not valid or does not exist. It might not be configured for -// EC2 Systems Manager or you might not have permission to perform the operation. +// Systems Manager or you might not have permission to perform the operation. // // * InternalServerError // An error occurred on the server side. @@ -10622,7 +12612,7 @@ func (c *SSM) StartSessionRequest(input *StartSessionInput) (req *request.Reques // // AWS CLI usage: start-session is an interactive command that requires the // Session Manager plugin to be installed on the client machine making the call. -// For information, see Install the Session Manager Plugin for the AWS CLI (http://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html) +// For information, see Install the Session Manager plugin for the AWS CLI (https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html) // in the AWS Systems Manager User Guide. // // AWS Tools for PowerShell usage: Start-SSMSession is not currently supported @@ -10641,8 +12631,8 @@ func (c *SSM) StartSessionRequest(input *StartSessionInput) (req *request.Reques // // * TargetNotConnected // The specified target instance for the session is not fully configured for -// use with Session Manager. For more information, see Getting Started with -// Session Manager (http://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started.html) +// use with Session Manager. For more information, see Getting started with +// Session Manager (https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started.html) // in the AWS Systems Manager User Guide. // // * InternalServerError @@ -10818,7 +12808,7 @@ func (c *SSM) TerminateSessionRequest(input *TerminateSessionInput) (req *reques // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -10943,7 +12933,7 @@ func (c *SSM) UpdateAssociationRequest(input *UpdateAssociationInput) (req *requ // // * InvalidTarget // The target is not valid or does not exist. It might not be configured for -// EC2 Systems Manager or you might not have permission to perform the operation. +// Systems Manager or you might not have permission to perform the operation. // // * InvalidAssociationVersion // The version you specified is not valid. Use ListAssociationVersions to view @@ -11345,7 +13335,7 @@ func (c *SSM) UpdateMaintenanceWindowRequest(input *UpdateMaintenanceWindowInput // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -11449,7 +13439,7 @@ func (c *SSM) UpdateMaintenanceWindowTargetRequest(input *UpdateMaintenanceWindo // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -11537,10 +13527,18 @@ func (c *SSM) UpdateMaintenanceWindowTaskRequest(input *UpdateMaintenanceWindowT // // * MaxErrors // -// If a parameter is null, then the corresponding field is not modified. Also, -// if you set Replace to true, then all fields required by the RegisterTaskWithMaintenanceWindow -// action are required for this request. Optional fields that aren't specified -// are set to null. +// If the value for a parameter in UpdateMaintenanceWindowTask is null, then +// the corresponding field is not modified. If you set Replace to true, then +// all fields required by the RegisterTaskWithMaintenanceWindow action are required +// for this request. Optional fields that aren't specified are set to null. +// +// When you update a maintenance window task that has options specified in TaskInvocationParameters, +// you must provide again all the TaskInvocationParameters values that you want +// to retain. The values you do not specify again are removed. For example, +// suppose that when you registered a Run Command task, you specified TaskInvocationParameters +// values for Comment, NotificationConfig, and OutputS3BucketName. If you update +// the maintenance window task and specify only a different OutputS3BucketName +// value, the values for Comment and NotificationConfig are removed. // // 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 @@ -11555,7 +13553,7 @@ func (c *SSM) UpdateMaintenanceWindowTaskRequest(input *UpdateMaintenanceWindowT // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -11628,8 +13626,10 @@ func (c *SSM) UpdateManagedInstanceRoleRequest(input *UpdateManagedInstanceRoleI // UpdateManagedInstanceRole API operation for Amazon Simple Systems Manager (SSM). // -// Assigns or changes an Amazon Identity and Access Management (IAM) role for -// the managed instance. +// Changes the Amazon Identity and Access Management (IAM) role that is assigned +// to the on-premises instance or virtual machines (VM). IAM roles are first +// assigned to these hybrid instances during the activation process. For more +// information, see CreateActivation. // // 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 @@ -11723,13 +13723,13 @@ func (c *SSM) UpdateOpsItemRequest(input *UpdateOpsItemInput) (req *request.Requ // // Edit or change an OpsItem. You must have permission in AWS Identity and Access // Management (IAM) to update an OpsItem. For more information, see Getting -// Started with OpsCenter (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-getting-started.html) +// started with OpsCenter (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-getting-started.html) // in the AWS Systems Manager User Guide. // // Operations engineers and IT professionals use OpsCenter to view, investigate, // and remediate operational issues impacting the performance and health of // their AWS resources. For more information, see AWS Systems Manager OpsCenter -// (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html) +// (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html) // in the AWS Systems Manager User Guide. // // Returns awserr.Error for service API and SDK errors. Use runtime type assertions @@ -11751,7 +13751,7 @@ func (c *SSM) UpdateOpsItemRequest(input *UpdateOpsItemInput) (req *request.Requ // // * OpsItemLimitExceededException // The request caused OpsItems to exceed one or more quotas. For information -// about OpsItem quotas, see What are the resource limits for OpsCenter? (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-learn-more.html#OpsCenter-learn-more-limits). +// about OpsItem quotas, see What are the resource limits for OpsCenter? (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-learn-more.html#OpsCenter-learn-more-limits). // // * OpsItemInvalidParameterException // A specified parameter argument isn't valid. Verify the available arguments @@ -11842,7 +13842,7 @@ func (c *SSM) UpdatePatchBaselineRequest(input *UpdatePatchBaselineInput) (req * // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. // // * InternalServerError @@ -11922,6 +13922,9 @@ func (c *SSM) UpdateResourceDataSyncRequest(input *UpdateResourceDataSyncInput) // the Include all accounts from my AWS Organizations configuration option. // Instead, you must delete the first resource data sync, and create a new one. // +// This API action only supports a resource data sync that was created with +// a SyncFromSource SyncType. +// // 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. @@ -12602,6 +14605,12 @@ func (s *AssociationAlreadyExists) RequestID() string { type AssociationDescription struct { _ struct{} `type:"structure"` + // By default, when you create a new associations, the system runs it immediately + // after it is created and then according to the schedule you specified. Specify + // this option if you don't want an association to run immediately after you + // create it. + ApplyOnlyAtCronInterval *bool `type:"boolean"` + // The association ID. AssociationId *string `type:"string"` @@ -12665,7 +14674,7 @@ type AssociationDescription struct { // The name of the Systems Manager document. Name *string `type:"string"` - // An Amazon S3 bucket where you want to store the output details of the request. + // An S3 bucket where you want to store the output details of the request. OutputLocation *InstanceAssociationOutputLocation `type:"structure"` // Information about the association. @@ -12680,6 +14689,20 @@ type AssociationDescription struct { // The association status. Status *AssociationStatus `type:"structure"` + // The mode for generating association compliance. You can specify AUTO or MANUAL. + // In AUTO mode, the system uses the status of the association execution to + // determine the compliance status. If the association execution runs successfully, + // then the association is COMPLIANT. If the association execution doesn't run + // successfully, the association is NON-COMPLIANT. + // + // In MANUAL mode, you must specify the AssociationId as a parameter for the + // PutComplianceItems API action. In this case, compliance data is not managed + // by State Manager. It is managed by your direct call to the PutComplianceItems + // API action. + // + // By default, all associations use AUTO mode. + SyncCompliance *string `type:"string" enum:"AssociationSyncCompliance"` + // The instances targeted by the request. Targets []*Target `type:"list"` } @@ -12694,6 +14717,12 @@ func (s AssociationDescription) GoString() string { return s.String() } +// SetApplyOnlyAtCronInterval sets the ApplyOnlyAtCronInterval field's value. +func (s *AssociationDescription) SetApplyOnlyAtCronInterval(v bool) *AssociationDescription { + s.ApplyOnlyAtCronInterval = &v + return s +} + // SetAssociationId sets the AssociationId field's value. func (s *AssociationDescription) SetAssociationId(v string) *AssociationDescription { s.AssociationId = &v @@ -12808,6 +14837,12 @@ func (s *AssociationDescription) SetStatus(v *AssociationStatus) *AssociationDes return s } +// SetSyncCompliance sets the SyncCompliance field's value. +func (s *AssociationDescription) SetSyncCompliance(v string) *AssociationDescription { + s.SyncCompliance = &v + return s +} + // SetTargets sets the Targets field's value. func (s *AssociationDescription) SetTargets(v []*Target) *AssociationDescription { s.Targets = v @@ -13475,6 +15510,12 @@ func (s *AssociationStatus) SetName(v string) *AssociationStatus { type AssociationVersionInfo struct { _ struct{} `type:"structure"` + // By default, when you create a new associations, the system runs it immediately + // after it is created and then according to the schedule you specified. Specify + // this option if you don't want an association to run immediately after you + // create it. + ApplyOnlyAtCronInterval *bool `type:"boolean"` + // The ID created by the system when the association was created. AssociationId *string `type:"string"` @@ -13535,6 +15576,20 @@ type AssociationVersionInfo struct { // version was created. ScheduleExpression *string `min:"1" type:"string"` + // The mode for generating association compliance. You can specify AUTO or MANUAL. + // In AUTO mode, the system uses the status of the association execution to + // determine the compliance status. If the association execution runs successfully, + // then the association is COMPLIANT. If the association execution doesn't run + // successfully, the association is NON-COMPLIANT. + // + // In MANUAL mode, you must specify the AssociationId as a parameter for the + // PutComplianceItems API action. In this case, compliance data is not managed + // by State Manager. It is managed by your direct call to the PutComplianceItems + // API action. + // + // By default, all associations use AUTO mode. + SyncCompliance *string `type:"string" enum:"AssociationSyncCompliance"` + // The targets specified for the association when the association version was // created. Targets []*Target `type:"list"` @@ -13550,6 +15605,12 @@ func (s AssociationVersionInfo) GoString() string { return s.String() } +// SetApplyOnlyAtCronInterval sets the ApplyOnlyAtCronInterval field's value. +func (s *AssociationVersionInfo) SetApplyOnlyAtCronInterval(v bool) *AssociationVersionInfo { + s.ApplyOnlyAtCronInterval = &v + return s +} + // SetAssociationId sets the AssociationId field's value. func (s *AssociationVersionInfo) SetAssociationId(v string) *AssociationVersionInfo { s.AssociationId = &v @@ -13622,6 +15683,12 @@ func (s *AssociationVersionInfo) SetScheduleExpression(v string) *AssociationVer return s } +// SetSyncCompliance sets the SyncCompliance field's value. +func (s *AssociationVersionInfo) SetSyncCompliance(v string) *AssociationVersionInfo { + s.SyncCompliance = &v + return s +} + // SetTargets sets the Targets field's value. func (s *AssociationVersionInfo) SetTargets(v []*Target) *AssociationVersionInfo { s.Targets = v @@ -13785,10 +15852,10 @@ type AttachmentsSource struct { // to a document. The format for Value depends on the type of key you specify. // // * For the key SourceUrl, the value is an S3 bucket location. For example: - // "Values": [ "s3://my-bucket/my-folder" ] + // "Values": [ "s3://doc-example-bucket/my-folder" ] // // * For the key S3FileUrl, the value is a file in an S3 bucket. For example: - // "Values": [ "s3://my-bucket/my-folder/my-file.py" ] + // "Values": [ "s3://doc-example-bucket/my-folder/my-file.py" ] // // * For the key AttachmentReference, the value is constructed from the name // of another SSM document in your account, a version number of that document, @@ -14331,8 +16398,8 @@ type AutomationExecutionMetadata struct { // Use this filter with DescribeAutomationExecutions. Specify either Local or // CrossAccount. CrossAccount is an Automation that runs in multiple AWS Regions - // and accounts. For more information, see Executing Automations in Multiple - // AWS Regions and Accounts (http://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-automation-multiple-accounts-and-regions.html) + // and accounts. For more information, see Running Automation workflows in multiple + // AWS Regions and accounts (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-automation-multiple-accounts-and-regions.html) // in the AWS Systems Manager User Guide. AutomationType *string `type:"string" enum:"AutomationType"` @@ -14361,7 +16428,7 @@ type AutomationExecutionMetadata struct { // The list of execution outputs as defined in the Automation document. FailureMessage *string `type:"string"` - // An Amazon S3 bucket where execution information is stored. + // An S3 bucket where execution information is stored. LogFile *string `type:"string"` // The MaxConcurrency value specified by the user when starting the Automation. @@ -14874,16 +16941,16 @@ type Command struct { // The maximum number of instances that are allowed to run the command at the // same time. You can specify a number of instances, such as 10, or a percentage // of instances, such as 10%. The default value is 50. For more information - // about how to use MaxConcurrency, see Running Commands Using Systems Manager - // Run Command (http://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html) + // about how to use MaxConcurrency, see Running commands using Systems Manager + // Run Command (https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html) // in the AWS Systems Manager User Guide. MaxConcurrency *string `min:"1" type:"string"` // The maximum number of errors allowed before the system stops sending the // command to additional targets. You can specify a number of errors, such as // 10, or a percentage or errors, such as 10%. The default value is 0. For more - // information about how to use MaxErrors, see Running Commands Using Systems - // Manager Run Command (http://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html) + // information about how to use MaxErrors, see Running commands using Systems + // Manager Run Command (https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html) // in the AWS Systems Manager User Guide. MaxErrors *string `min:"1" type:"string"` @@ -14899,8 +16966,8 @@ type Command struct { OutputS3KeyPrefix *string `type:"string"` // (Deprecated) You can no longer specify this parameter. The system ignores - // it. Instead, Systems Manager automatically determines the Amazon S3 bucket - // region. + // it. Instead, Systems Manager automatically determines the Region of the S3 + // bucket. OutputS3Region *string `min:"3" type:"string"` // The parameter values to be inserted in the document when running the command. @@ -14919,8 +16986,8 @@ type Command struct { // A detailed status of the command execution. StatusDetails includes more information // than Status because it includes states resulting from error and concurrency // control parameters. StatusDetails can show different results than Status. - // For more information about these statuses, see Understanding Command Statuses - // (http://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html) + // For more information about these statuses, see Understanding command statuses + // (https://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html) // in the AWS Systems Manager User Guide. StatusDetails can be one of the following // values: // @@ -14960,6 +17027,9 @@ type Command struct { // that you specify. Targets is required if you don't provide one or more instance // IDs in the call. Targets []*Target `type:"list"` + + // The TimeoutSeconds value specified for a command. + TimeoutSeconds *int64 `min:"30" type:"integer"` } // String returns the string representation @@ -15110,7 +17180,16 @@ func (s *Command) SetTargets(v []*Target) *Command { return s } +// SetTimeoutSeconds sets the TimeoutSeconds field's value. +func (s *Command) SetTimeoutSeconds(v int64) *Command { + s.TimeoutSeconds = &v + return s +} + // Describes a command filter. +// +// An instance ID can't be specified when a command status is Pending because +// the command hasn't run on the instance yet. type CommandFilter struct { _ struct{} `type:"structure"` @@ -15217,9 +17296,8 @@ type CommandInvocation struct { // The instance ID in which this invocation was requested. InstanceId *string `type:"string"` - // The name of the invocation target. For Amazon EC2 instances this is the value - // for the aws:Name tag. For on-premises instances, this is the name of the - // instance. + // The name of the invocation target. For EC2 instances this is the value for + // the aws:Name tag. For on-premises instances, this is the name of the instance. InstanceName *string `type:"string"` // Configurations for sending notifications about command status changes on @@ -15233,16 +17311,16 @@ type CommandInvocation struct { // notifications about command status changes on a per instance basis. ServiceRole *string `type:"string"` - // The URL to the plugin's StdErr file in Amazon S3, if the Amazon S3 bucket - // was defined for the parent command. For an invocation, StandardErrorUrl is - // populated if there is just one plugin defined for the command, and the Amazon - // S3 bucket was defined for the command. + // The URL to the plugin's StdErr file in Amazon S3, if the S3 bucket was defined + // for the parent command. For an invocation, StandardErrorUrl is populated + // if there is just one plugin defined for the command, and the S3 bucket was + // defined for the command. StandardErrorUrl *string `type:"string"` - // The URL to the plugin's StdOut file in Amazon S3, if the Amazon S3 bucket - // was defined for the parent command. For an invocation, StandardOutputUrl - // is populated if there is just one plugin defined for the command, and the - // Amazon S3 bucket was defined for the command. + // The URL to the plugin's StdOut file in Amazon S3, if the S3 bucket was defined + // for the parent command. For an invocation, StandardOutputUrl is populated + // if there is just one plugin defined for the command, and the S3 bucket was + // defined for the command. StandardOutputUrl *string `type:"string"` // Whether or not the invocation succeeded, failed, or is pending. @@ -15252,7 +17330,7 @@ type CommandInvocation struct { // targeted by the command). StatusDetails includes more information than Status // because it includes states resulting from error and concurrency control parameters. // StatusDetails can show different results than Status. For more information - // about these statuses, see Understanding Command Statuses (http://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html) + // about these statuses, see Understanding command statuses (https://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html) // in the AWS Systems Manager User Guide. StatusDetails can be one of the following // values: // @@ -15419,13 +17497,13 @@ type CommandPlugin struct { // This was requested when issuing the command. For example, in the following // response: // - // test_folder/ab19cb99-a030-46dd-9dfc-8eSAMPLEPre-Fix/i-1234567876543/awsrunShellScript + // doc-example-bucket/ab19cb99-a030-46dd-9dfc-8eSAMPLEPre-Fix/i-02573cafcfEXAMPLE/awsrunShellScript // - // test_folder is the name of the Amazon S3 bucket; + // doc-example-bucket is the name of the S3 bucket; // // ab19cb99-a030-46dd-9dfc-8eSAMPLEPre-Fix is the name of the S3 prefix; // - // i-1234567876543 is the instance ID; + // i-02573cafcfEXAMPLE is the instance ID; // // awsrunShellScript is the name of the plugin. OutputS3BucketName *string `min:"3" type:"string"` @@ -15434,20 +17512,19 @@ type CommandPlugin struct { // executions should be stored. This was requested when issuing the command. // For example, in the following response: // - // test_folder/ab19cb99-a030-46dd-9dfc-8eSAMPLEPre-Fix/i-1234567876543/awsrunShellScript + // doc-example-bucket/ab19cb99-a030-46dd-9dfc-8eSAMPLEPre-Fix/i-02573cafcfEXAMPLE/awsrunShellScript // - // test_folder is the name of the Amazon S3 bucket; + // doc-example-bucket is the name of the S3 bucket; // // ab19cb99-a030-46dd-9dfc-8eSAMPLEPre-Fix is the name of the S3 prefix; // - // i-1234567876543 is the instance ID; + // i-02573cafcfEXAMPLE is the instance ID; // // awsrunShellScript is the name of the plugin. OutputS3KeyPrefix *string `type:"string"` // (Deprecated) You can no longer specify this parameter. The system ignores - // it. Instead, Systems Manager automatically determines the Amazon S3 bucket - // region. + // it. Instead, Systems Manager automatically determines the S3 bucket region. OutputS3Region *string `min:"3" type:"string"` // A numeric response code generated after running the plugin. @@ -15465,8 +17542,7 @@ type CommandPlugin struct { StandardErrorUrl *string `type:"string"` // The URL for the complete text written by the plugin to stdout in Amazon S3. - // If the Amazon S3 bucket for the command was not specified, then this string - // is empty. + // If the S3 bucket for the command was not specified, then this string is empty. StandardOutputUrl *string `type:"string"` // The status of this plugin. You can run a document with multiple plugins. @@ -15475,8 +17551,8 @@ type CommandPlugin struct { // A detailed status of the plugin execution. StatusDetails includes more information // than Status because it includes states resulting from error and concurrency // control parameters. StatusDetails can show different results than Status. - // For more information about these statuses, see Understanding Command Statuses - // (http://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html) + // For more information about these statuses, see Understanding command statuses + // (https://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html) // in the AWS Systems Manager User Guide. StatusDetails can be one of the following // values: // @@ -15663,7 +17739,7 @@ func (s *ComplianceExecutionSummary) SetExecutionType(v string) *ComplianceExecu // Information about the compliance as defined by the resource type. For example, // for a patch resource type, Items includes information about the PatchSeverity, -// Classification, etc. +// Classification, and so on. type ComplianceItem struct { _ struct{} `type:"structure"` @@ -15783,7 +17859,8 @@ type ComplianceItemEntry struct { // Severity is a required field Severity *string `type:"string" required:"true" enum:"ComplianceSeverity"` - // The status of the compliance item. An item is either COMPLIANT or NON_COMPLIANT. + // The status of the compliance item. An item is either COMPLIANT, NON_COMPLIANT, + // or an empty string (for Windows patches that aren't applicable). // // Status is a required field Status *string `type:"string" required:"true" enum:"ComplianceStatus"` @@ -16066,7 +18143,7 @@ type CreateActivationInput struct { // The Amazon Identity and Access Management (IAM) role that you want to assign // to the managed instance. This IAM role must provide AssumeRole permissions // for the Systems Manager service principal ssm.amazonaws.com. For more information, - // see Create an IAM Service Role for a Hybrid Environment (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-service-role.html) + // see Create an IAM service role for a hybrid environment (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-service-role.html) // in the AWS Systems Manager User Guide. // // IamRole is a required field @@ -16294,6 +18371,12 @@ func (s *CreateAssociationBatchOutput) SetSuccessful(v []*AssociationDescription type CreateAssociationBatchRequestEntry struct { _ struct{} `type:"structure"` + // By default, when you create a new associations, the system runs it immediately + // after it is created and then according to the schedule you specified. Specify + // this option if you don't want an association to run immediately after you + // create it. + ApplyOnlyAtCronInterval *bool `type:"boolean"` + // Specify a descriptive name for the association. AssociationName *string `type:"string"` @@ -16358,7 +18441,7 @@ type CreateAssociationBatchRequestEntry struct { // Name is a required field Name *string `type:"string" required:"true"` - // An Amazon S3 bucket where you want to store the results of this request. + // An S3 bucket where you want to store the results of this request. OutputLocation *InstanceAssociationOutputLocation `type:"structure"` // A description of the parameters for a document. @@ -16367,6 +18450,20 @@ type CreateAssociationBatchRequestEntry struct { // A cron expression that specifies a schedule when the association runs. ScheduleExpression *string `min:"1" type:"string"` + // The mode for generating association compliance. You can specify AUTO or MANUAL. + // In AUTO mode, the system uses the status of the association execution to + // determine the compliance status. If the association execution runs successfully, + // then the association is COMPLIANT. If the association execution doesn't run + // successfully, the association is NON-COMPLIANT. + // + // In MANUAL mode, you must specify the AssociationId as a parameter for the + // PutComplianceItems API action. In this case, compliance data is not managed + // by State Manager. It is managed by your direct call to the PutComplianceItems + // API action. + // + // By default, all associations use AUTO mode. + SyncCompliance *string `type:"string" enum:"AssociationSyncCompliance"` + // The instances targeted by the request. Targets []*Target `type:"list"` } @@ -16421,6 +18518,12 @@ func (s *CreateAssociationBatchRequestEntry) Validate() error { return nil } +// SetApplyOnlyAtCronInterval sets the ApplyOnlyAtCronInterval field's value. +func (s *CreateAssociationBatchRequestEntry) SetApplyOnlyAtCronInterval(v bool) *CreateAssociationBatchRequestEntry { + s.ApplyOnlyAtCronInterval = &v + return s +} + // SetAssociationName sets the AssociationName field's value. func (s *CreateAssociationBatchRequestEntry) SetAssociationName(v string) *CreateAssociationBatchRequestEntry { s.AssociationName = &v @@ -16487,6 +18590,12 @@ func (s *CreateAssociationBatchRequestEntry) SetScheduleExpression(v string) *Cr return s } +// SetSyncCompliance sets the SyncCompliance field's value. +func (s *CreateAssociationBatchRequestEntry) SetSyncCompliance(v string) *CreateAssociationBatchRequestEntry { + s.SyncCompliance = &v + return s +} + // SetTargets sets the Targets field's value. func (s *CreateAssociationBatchRequestEntry) SetTargets(v []*Target) *CreateAssociationBatchRequestEntry { s.Targets = v @@ -16496,6 +18605,12 @@ func (s *CreateAssociationBatchRequestEntry) SetTargets(v []*Target) *CreateAsso type CreateAssociationInput struct { _ struct{} `type:"structure"` + // By default, when you create a new associations, the system runs it immediately + // after it is created and then according to the schedule you specified. Specify + // this option if you don't want an association to run immediately after you + // create it. + ApplyOnlyAtCronInterval *bool `type:"boolean"` + // Specify a descriptive name for the association. AssociationName *string `type:"string"` @@ -16568,7 +18683,7 @@ type CreateAssociationInput struct { // Name is a required field Name *string `type:"string" required:"true"` - // An Amazon S3 bucket where you want to store the output details of the request. + // An S3 bucket where you want to store the output details of the request. OutputLocation *InstanceAssociationOutputLocation `type:"structure"` // The parameters for the runtime configuration of the document. @@ -16577,8 +18692,25 @@ type CreateAssociationInput struct { // A cron expression when the association will be applied to the target(s). ScheduleExpression *string `min:"1" type:"string"` - // The targets (either instances or tags) for the association. You must specify - // a value for Targets if you don't specify a value for InstanceId. + // The mode for generating association compliance. You can specify AUTO or MANUAL. + // In AUTO mode, the system uses the status of the association execution to + // determine the compliance status. If the association execution runs successfully, + // then the association is COMPLIANT. If the association execution doesn't run + // successfully, the association is NON-COMPLIANT. + // + // In MANUAL mode, you must specify the AssociationId as a parameter for the + // PutComplianceItems API action. In this case, compliance data is not managed + // by State Manager. It is managed by your direct call to the PutComplianceItems + // API action. + // + // By default, all associations use AUTO mode. + SyncCompliance *string `type:"string" enum:"AssociationSyncCompliance"` + + // The targets for the association. You can target instances by using tags, + // AWS Resource Groups, all instances in an AWS account, or individual instance + // IDs. For more information about choosing targets for an association, see + // Using targets and rate controls with State Manager associations (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-state-manager-targets-and-rate-controls.html) + // in the AWS Systems Manager User Guide. Targets []*Target `type:"list"` } @@ -16632,6 +18764,12 @@ func (s *CreateAssociationInput) Validate() error { return nil } +// SetApplyOnlyAtCronInterval sets the ApplyOnlyAtCronInterval field's value. +func (s *CreateAssociationInput) SetApplyOnlyAtCronInterval(v bool) *CreateAssociationInput { + s.ApplyOnlyAtCronInterval = &v + return s +} + // SetAssociationName sets the AssociationName field's value. func (s *CreateAssociationInput) SetAssociationName(v string) *CreateAssociationInput { s.AssociationName = &v @@ -16698,6 +18836,12 @@ func (s *CreateAssociationInput) SetScheduleExpression(v string) *CreateAssociat return s } +// SetSyncCompliance sets the SyncCompliance field's value. +func (s *CreateAssociationInput) SetSyncCompliance(v string) *CreateAssociationInput { + s.SyncCompliance = &v + return s +} + // SetTargets sets the Targets field's value. func (s *CreateAssociationInput) SetTargets(v []*Target) *CreateAssociationInput { s.Targets = v @@ -16734,7 +18878,17 @@ type CreateDocumentInput struct { // document. Attachments []*AttachmentsSource `type:"list"` - // A valid JSON or YAML string. + // The content for the new SSM document in JSON or YAML format. We recommend + // storing the contents for your new document in an external JSON or YAML file + // and referencing the file in a command. + // + // For examples, see the following topics in the AWS Systems Manager User Guide. + // + // * Create an SSM document (AWS API) (https://docs.aws.amazon.com/systems-manager/latest/userguide/create-ssm-document-api.html) + // + // * Create an SSM document (AWS CLI) (https://docs.aws.amazon.com/systems-manager/latest/userguide/create-ssm-document-cli.html) + // + // * Create an SSM document (API) (https://docs.aws.amazon.com/systems-manager/latest/userguide/create-ssm-document-api.html) // // Content is a required field Content *string `min:"1" type:"string" required:"true"` @@ -16748,10 +18902,10 @@ type CreateDocumentInput struct { // A name for the Systems Manager document. // - // Do not use the following to begin the names of documents you create. They - // are reserved by AWS for use as document prefixes: + // You can't use the following strings as document name prefixes. These are + // reserved by AWS for use as document name prefixes: // - // * aws + // * aws- // // * amazon // @@ -16760,8 +18914,13 @@ type CreateDocumentInput struct { // Name is a required field Name *string `type:"string" required:"true"` - // A list of SSM documents required by a document. For example, an ApplicationConfiguration - // document requires an ApplicationConfigurationSchema document. + // A list of SSM documents required by a document. This parameter is used exclusively + // by AWS AppConfig. When a user creates an AppConfig configuration in an SSM + // document, the user must also specify a required document for validation purposes. + // In this case, an ApplicationConfiguration document requires an ApplicationConfigurationSchema + // document for validation purposes. For more information, see AWS AppConfig + // (https://docs.aws.amazon.com/systems-manager/latest/userguide/appconfig.html) + // in the AWS Systems Manager User Guide. Requires []*DocumentRequires `min:"1" type:"list"` // Optional metadata that you assign to a resource. Tags enable you to categorize @@ -16781,8 +18940,8 @@ type CreateDocumentInput struct { // on. For example, to run a document on EC2 instances, specify the following // value: /AWS::EC2::Instance. If you specify a value of '/' the document can // run on all types of resources. If you don't specify a value, the document - // can't run on any resources. For a list of valid resource types, see AWS Resource - // Types Reference (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) + // can't run on any resources. For a list of valid resource types, see AWS resource + // and property types reference (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) // in the AWS CloudFormation User Guide. TargetType *string `type:"string"` @@ -16978,6 +19137,18 @@ type CreateMaintenanceWindowInput struct { // Schedule is a required field Schedule *string `min:"1" type:"string" required:"true"` + // The number of days to wait after the date and time specified by a CRON expression + // before running the maintenance window. + // + // For example, the following cron expression schedules a maintenance window + // to run on the third Tuesday of every month at 11:30 PM. + // + // cron(0 30 23 ? * TUE#3 *) + // + // If the schedule offset is 2, the maintenance window won't run until two days + // later. + ScheduleOffset *int64 `min:"1" type:"integer"` + // The time zone that the scheduled maintenance window executions are based // on, in Internet Assigned Numbers Authority (IANA) format. For example: "America/Los_Angeles", // "etc/UTC", or "Asia/Seoul". For more information, see the Time Zone Database @@ -17049,6 +19220,9 @@ func (s *CreateMaintenanceWindowInput) Validate() error { if s.Schedule != nil && len(*s.Schedule) < 1 { invalidParams.Add(request.NewErrParamMinLen("Schedule", 1)) } + if s.ScheduleOffset != nil && *s.ScheduleOffset < 1 { + invalidParams.Add(request.NewErrParamMinValue("ScheduleOffset", 1)) + } if s.Tags != nil { for i, v := range s.Tags { if v == nil { @@ -17114,6 +19288,12 @@ func (s *CreateMaintenanceWindowInput) SetSchedule(v string) *CreateMaintenanceW return s } +// SetScheduleOffset sets the ScheduleOffset field's value. +func (s *CreateMaintenanceWindowInput) SetScheduleOffset(v int64) *CreateMaintenanceWindowInput { + s.ScheduleOffset = &v + return s +} + // SetScheduleTimezone sets the ScheduleTimezone field's value. func (s *CreateMaintenanceWindowInput) SetScheduleTimezone(v string) *CreateMaintenanceWindowInput { s.ScheduleTimezone = &v @@ -17189,7 +19369,7 @@ type CreateOpsItemInput struct { // Use the /aws/resources key in OperationalData to specify a related resource // in the request. Use the /aws/automations key in OperationalData to associate // an Automation runbook with the OpsItem. To view AWS CLI example commands - // that use these keys, see Creating OpsItems Manually (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems) + // that use these keys, see Creating OpsItems manually (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems) // in the AWS Systems Manager User Guide. OperationalData map[string]*OpsItemDataValue `type:"map"` @@ -17204,14 +19384,16 @@ type CreateOpsItemInput struct { // Specify a severity to assign to an OpsItem. Severity *string `min:"1" type:"string"` - // The origin of the OpsItem, such as Amazon EC2 or AWS Systems Manager. + // The origin of the OpsItem, such as Amazon EC2 or Systems Manager. + // + // The source name can't contain the following strings: aws, amazon, and amzn. // // Source is a required field Source *string `min:"1" type:"string" required:"true"` // Optional metadata that you assign to a resource. You can restrict access // to OpsItems by using an inline IAM policy that specifies tags. For more information, - // see Getting Started with OpsCenter (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-getting-started.html#OpsCenter-getting-started-user-permissions) + // see Getting started with OpsCenter (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-getting-started.html#OpsCenter-getting-started-user-permissions) // in the AWS Systems Manager User Guide. // // Tags use a key-value pair. For example: @@ -17387,8 +19569,8 @@ type CreatePatchBaselineInput struct { // A list of explicitly approved patches for the baseline. // // For information about accepted formats for lists of approved patches and - // rejected patches, see Package Name Formats for Approved and Rejected Patch - // Lists (https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html) + // rejected patches, see About package name formats for approved and rejected + // patch lists (https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html) // in the AWS Systems Manager User Guide. ApprovedPatches []*string `type:"list"` @@ -17423,8 +19605,8 @@ type CreatePatchBaselineInput struct { // A list of explicitly rejected patches for the baseline. // // For information about accepted formats for lists of approved patches and - // rejected patches, see Package Name Formats for Approved and Rejected Patch - // Lists (https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html) + // rejected patches, see About package name formats for approved and rejected + // patch lists (https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html) // in the AWS Systems Manager User Guide. RejectedPatches []*string `type:"list"` @@ -17627,7 +19809,8 @@ func (s *CreatePatchBaselineOutput) SetBaselineId(v string) *CreatePatchBaseline type CreateResourceDataSyncInput struct { _ struct{} `type:"structure"` - // Amazon S3 configuration details for the sync. + // Amazon S3 configuration details for the sync. This parameter is required + // if the SyncType value is SyncToDestination. S3Destination *ResourceDataSyncS3Destination `type:"structure"` // A name for the configuration. @@ -17635,13 +19818,17 @@ type CreateResourceDataSyncInput struct { // SyncName is a required field SyncName *string `min:"1" type:"string" required:"true"` - // Specify information about the data sources to synchronize. + // Specify information about the data sources to synchronize. This parameter + // is required if the SyncType value is SyncFromSource. SyncSource *ResourceDataSyncSource `type:"structure"` // Specify SyncToDestination to create a resource data sync that synchronizes - // data from multiple AWS Regions to an Amazon S3 bucket. Specify SyncFromSource - // to synchronize data from multiple AWS accounts and Regions, as listed in - // AWS Organizations. + // data to an S3 bucket for Inventory. If you specify SyncToDestination, you + // must provide a value for S3Destination. Specify SyncFromSource to synchronize + // data from a single account and multiple Regions, or multiple AWS accounts + // and Regions, as listed in AWS Organizations for Explorer. If you specify + // SyncFromSource, you must provide a value for SyncSource. The default value + // is SyncToDestination. SyncType *string `min:"1" type:"string"` } @@ -17974,7 +20161,7 @@ type DeleteInventoryInput struct { _ struct{} `type:"structure"` // User-provided idempotency token. - ClientToken *string `min:"1" type:"string" idempotencyToken:"true"` + ClientToken *string `type:"string" idempotencyToken:"true"` // Use this option to view a summary of the deletion request without deleting // any data or the data type. This option is useful when you only want to understand @@ -17998,7 +20185,7 @@ type DeleteInventoryInput struct { SchemaDeleteOption *string `type:"string" enum:"InventorySchemaDeleteOption"` // The name of the custom inventory type for which you want to delete either - // all previously collected data, or the inventory type itself. + // all previously collected data or the inventory type itself. // // TypeName is a required field TypeName *string `min:"1" type:"string" required:"true"` @@ -18017,9 +20204,6 @@ func (s DeleteInventoryInput) GoString() string { // Validate inspects the fields of the type to determine if they are valid. func (s *DeleteInventoryInput) Validate() error { invalidParams := request.ErrInvalidParams{Context: "DeleteInventoryInput"} - if s.ClientToken != nil && len(*s.ClientToken) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ClientToken", 1)) - } if s.TypeName == nil { invalidParams.Add(request.NewErrParamRequired("TypeName")) } @@ -18067,7 +20251,7 @@ type DeleteInventoryOutput struct { DeletionId *string `type:"string"` // A summary of the delete operation. For more information about this summary, - // see Understanding the Delete Inventory Summary (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-inventory-delete.html#sysman-inventory-delete-summary) + // see Deleting custom inventory (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-inventory-custom.html#sysman-inventory-delete-summary) // in the AWS Systems Manager User Guide. DeletionSummary *InventoryDeletionSummary `type:"structure"` @@ -19692,7 +21876,7 @@ type DescribeDocumentPermissionOutput struct { // either an AWS account or All. AccountIds []*string `type:"list"` - // A list of of AWS accounts where the current document is shared and the version + // A list of AWS accounts where the current document is shared and the version // shared with each account. AccountSharingInfoList []*AccountSharingInfo `type:"list"` } @@ -20009,17 +22193,16 @@ type DescribeInstanceInformationInput struct { _ struct{} `type:"structure"` // One or more filters. Use a filter to return a more specific list of instances. - // You can filter on Amazon EC2 tag. Specify tags by using a key-value mapping. + // You can filter based on tags applied to EC2 instances. Use this Filters data + // type instead of InstanceInformationFilterList, which is deprecated. Filters []*InstanceInformationStringFilter `type:"list"` // This is a legacy method. We recommend that you don't use this method. Instead, - // use the InstanceInformationFilter action. The InstanceInformationFilter action - // enables you to return instance information by using tags that are specified - // as a key-value mapping. + // use the Filters data type. Filters enables you to return instance information + // by filtering based on tags applied to managed instances. // - // If you do use this method, then you can't use the InstanceInformationFilter - // action. Using this method and the InstanceInformationFilter action causes - // an exception error. + // Attempting to use InstanceInformationFilterList and Filters leads to an exception + // error. InstanceInformationFilterList []*InstanceInformationFilter `type:"list"` // The maximum number of items to return for this call. The call also returns @@ -21559,7 +23742,7 @@ type DescribeOpsItemsInput struct { // A token to start the list. Use this token to get the next set of results. NextToken *string `type:"string"` - // One or more filters to limit the reponse. + // One or more filters to limit the response. // // * Key: CreatedTime Operations: GreaterThan, LessThan // @@ -22046,6 +24229,15 @@ type DescribePatchGroupsInput struct { _ struct{} `type:"structure"` // One or more filters. Use a filter to return a more specific list of results. + // + // For DescribePatchGroups,valid filter keys include the following: + // + // * NAME_PREFIX: The name of the patch group. Wildcards (*) are accepted. + // + // * OPERATING_SYSTEM: The supported operating system type to return results + // for. For valid operating system values, see GetDefaultPatchBaselineRequest$OperatingSystem + // in CreatePatchBaseline. Examples: --filters Key=NAME_PREFIX,Values=MyPatchGroup* + // --filters Key=OPERATING_SYSTEM,Values=AMAZON_LINUX_2 Filters []*PatchOrchestratorFilter `type:"list"` // The maximum number of patch groups to return (per page). @@ -22483,7 +24675,7 @@ type DocumentDescription struct { _ struct{} `type:"structure"` // Details about the document attachments, including names, locations, sizes, - // etc. + // and so on. AttachmentsInformation []*AttachmentInformation `type:"list"` // The date when the document was created. @@ -22553,7 +24745,7 @@ type DocumentDescription struct { // The target type which defines the kinds of resources the document can run // on. For example, /AWS::EC2::Instance. For a list of valid resource types, - // see AWS Resource Types Reference (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) + // see AWS resource and property types reference (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) // in the AWS CloudFormation User Guide. TargetType *string `type:"string"` @@ -22703,7 +24895,7 @@ func (s *DocumentDescription) SetVersionName(v string) *DocumentDescription { return s } -// Describes a filter. +// This data type is deprecated. Instead, use DocumentKeyValuesFilter. type DocumentFilter struct { _ struct{} `type:"structure"` @@ -22793,7 +24985,7 @@ type DocumentIdentifier struct { // The target type which defines the kinds of resources the document can run // on. For example, /AWS::EC2::Instance. For a list of valid resource types, - // see AWS Resource Types Reference (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) + // see AWS resource and property types reference (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) // in the AWS CloudFormation User Guide. TargetType *string `type:"string"` @@ -22883,24 +25075,68 @@ func (s *DocumentIdentifier) SetVersionName(v string) *DocumentIdentifier { // // For keys, you can specify one or more tags that have been applied to a document. // -// Other valid values include Owner, Name, PlatformTypes, and DocumentType. +// You can also use AWS-provided keys, some of which have specific allowed values. +// These keys and their associated values are as follows: +// +// DocumentType +// +// * ApplicationConfiguration +// +// * ApplicationConfigurationSchema +// +// * Automation +// +// * ChangeCalendar +// +// * Command +// +// * DeploymentStrategy +// +// * Package +// +// * Policy +// +// * Session +// +// Owner // // Note that only one Owner can be specified in a request. For example: Key=Owner,Values=Self. // -// If you use Name as a key, you can use a name prefix to return a list of documents. -// For example, in the AWS CLI, to return a list of all documents that begin -// with Te, run the following command: +// * Amazon +// +// * Private +// +// * Public +// +// * Self +// +// * ThirdParty +// +// PlatformTypes +// +// * Linux +// +// * Windows +// +// Name is another AWS-provided key. If you use Name as a key, you can use a +// name prefix to return a list of documents. For example, in the AWS CLI, to +// return a list of all documents that begin with Te, run the following command: // // aws ssm list-documents --filters Key=Name,Values=Te // +// You can also use the TargetType AWS-provided key. For a list of valid resource +// type values that can be used with this key, see AWS resource and property +// types reference (http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) +// in the AWS CloudFormation User Guide. +// // If you specify more than two keys, only documents that are identified by // all the tags are returned in the results. If you specify more than two values // for a key, documents that are identified by any of the values are returned // in the results. // -// To specify a custom key and value pair, use the format Key=tag:[tagName],Values=[valueName]. +// To specify a custom key and value pair, use the format Key=tag:tagName,Values=valueName. // -// For example, if you created a Key called region and are using the AWS CLI +// For example, if you created a key called region and are using the AWS CLI // to call the list-documents command: // // aws ssm list-documents --filters Key=tag:region,Values=east,west Key=Owner,Values=Self @@ -23320,7 +25556,7 @@ func (s *DocumentVersionLimitExceeded) RequestID() string { // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. type DoesNotExistException struct { _ struct{} `type:"structure"` @@ -23904,7 +26140,7 @@ type GetCommandInvocationInput struct { CommandId *string `min:"36" type:"string" required:"true"` // (Required) The ID of the managed instance targeted by the command. A managed - // instance can be an Amazon EC2 instance or an instance in your hybrid environment + // instance can be an EC2 instance or an instance in your hybrid environment // that is configured for Systems Manager. // // InstanceId is a required field @@ -23913,6 +26149,8 @@ type GetCommandInvocationInput struct { // (Optional) The name of the plugin for which you want detailed results. If // the document contains only one plugin, the name can be omitted and the details // will be returned. + // + // Plugin names are also referred to as step names in Systems Manager documents. PluginName *string `min:"4" type:"string"` } @@ -24006,8 +26244,8 @@ type GetCommandInvocationOutput struct { ExecutionStartDateTime *string `type:"string"` // The ID of the managed instance targeted by the command. A managed instance - // can be an Amazon EC2 instance or an instance in your hybrid environment that - // is configured for Systems Manager. + // can be an EC2 instance or an instance in your hybrid environment that is + // configured for Systems Manager. InstanceId *string `type:"string"` // The name of the plugin for which you want detailed results. For example, @@ -24033,7 +26271,7 @@ type GetCommandInvocationOutput struct { StandardOutputContent *string `type:"string"` // The URL for the complete text written by the plugin to stdout in Amazon S3. - // If an Amazon S3 bucket was not specified, then this string is empty. + // If an S3 bucket was not specified, then this string is empty. StandardOutputUrl *string `type:"string"` // The status of this invocation plugin. This status can be different than StatusDetails. @@ -24043,7 +26281,7 @@ type GetCommandInvocationOutput struct { // includes more information than Status because it includes states resulting // from error and concurrency control parameters. StatusDetails can show different // results than Status. For more information about these statuses, see Understanding - // Command Statuses (http://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html) + // command statuses (https://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html) // in the AWS Systems Manager User Guide. StatusDetails can be one of the following // values: // @@ -24054,10 +26292,10 @@ type GetCommandInvocationOutput struct { // // * Delayed: The system attempted to send the command to the target, but // the target was not available. The instance might not be available because - // of network issues, the instance was stopped, etc. The system will try - // to deliver the command again. + // of network issues, because the instance was stopped, or for similar reasons. + // The system will try to send the command again. // - // * Success: The command or plugin was run successfully. This is a terminal + // * Success: The command or plugin ran successfully. This is a terminal // state. // // * Delivery Timed Out: The command was not delivered to the instance before @@ -24455,7 +26693,7 @@ type GetDocumentInput struct { // An optional field specifying the version of the artifact associated with // the document. For example, "Release 12, Update 6". This value is unique across - // all versions of a document, and cannot be changed. + // all versions of a document and can't be changed. VersionName *string `type:"string"` } @@ -24510,7 +26748,7 @@ type GetDocumentOutput struct { _ struct{} `type:"structure"` // A description of the document attachments, including names, locations, sizes, - // etc. + // and so on. AttachmentsContent []*AttachmentContent `type:"list"` // The contents of the Systems Manager document. @@ -25473,6 +27711,10 @@ type GetMaintenanceWindowOutput struct { // The schedule of the maintenance window in the form of a cron or rate expression. Schedule *string `min:"1" type:"string"` + // The number of days to wait to run a maintenance window after the scheduled + // CRON expression date and time. + ScheduleOffset *int64 `min:"1" type:"integer"` + // The time zone that the scheduled maintenance window executions are based // on, in Internet Assigned Numbers Authority (IANA) format. For example: "America/Los_Angeles", // "etc/UTC", or "Asia/Seoul". For more information, see the Time Zone Database @@ -25564,6 +27806,12 @@ func (s *GetMaintenanceWindowOutput) SetSchedule(v string) *GetMaintenanceWindow return s } +// SetScheduleOffset sets the ScheduleOffset field's value. +func (s *GetMaintenanceWindowOutput) SetScheduleOffset(v int64) *GetMaintenanceWindowOutput { + s.ScheduleOffset = &v + return s +} + // SetScheduleTimezone sets the ScheduleTimezone field's value. func (s *GetMaintenanceWindowOutput) SetScheduleTimezone(v string) *GetMaintenanceWindowOutput { s.ScheduleTimezone = &v @@ -26209,6 +28457,12 @@ type GetParametersByPathInput struct { NextToken *string `type:"string"` // Filters to limit the request results. + // + // For GetParametersByPath, the following filter Key names are supported: Type, + // KeyId, Label, and DataType. + // + // The following Key values are not supported for GetParametersByPath: tag, + // Name, Path, and Tier. ParameterFilters []*ParameterStringFilter `type:"list"` // The hierarchy for the parameter. Hierarchies start with a forward slash (/) @@ -26716,7 +28970,8 @@ func (s *GetPatchBaselineOutput) SetSources(v []*PatchSource) *GetPatchBaselineO type GetServiceSettingInput struct { _ struct{} `type:"structure"` - // The ID of the service setting to get. + // The ID of the service setting to get. The setting ID can be /ssm/parameter-store/default-parameter-tier, + // /ssm/parameter-store/high-throughput-enabled, or /ssm/managed-instance/activation-tier. // // SettingId is a required field SettingId *string `min:"1" type:"string" required:"true"` @@ -26779,14 +29034,14 @@ func (s *GetServiceSettingOutput) SetServiceSetting(v *ServiceSetting) *GetServi } // A hierarchy can have a maximum of 15 levels. For more information, see Requirements -// and Constraints for Parameter Names (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-parameter-name-constraints.html) +// and constraints for parameter names (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-parameter-name-constraints.html) // in the AWS Systems Manager User Guide. type HierarchyLevelLimitExceededException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` // A hierarchy can have a maximum of 15 levels. For more information, see Requirements - // and Constraints for Parameter Names (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-parameter-name-constraints.html) + // and constraints for parameter names (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-parameter-name-constraints.html) // in the AWS Systems Manager User Guide. Message_ *string `locationName:"message" type:"string"` } @@ -27099,11 +29354,11 @@ func (s *InstanceAssociation) SetInstanceId(v string) *InstanceAssociation { return s } -// An Amazon S3 bucket where you want to store the results of this request. +// An S3 bucket where you want to store the results of this request. type InstanceAssociationOutputLocation struct { _ struct{} `type:"structure"` - // An Amazon S3 bucket where you want to store the results of this request. + // An S3 bucket where you want to store the results of this request. S3Location *S3OutputLocation `type:"structure"` } @@ -27138,11 +29393,11 @@ func (s *InstanceAssociationOutputLocation) SetS3Location(v *S3OutputLocation) * return s } -// The URL of Amazon S3 bucket where you want to store the results of this request. +// The URL of S3 bucket where you want to store the results of this request. type InstanceAssociationOutputUrl struct { _ struct{} `type:"structure"` - // The URL of Amazon S3 bucket where you want to store the results of this request. + // The URL of S3 bucket where you want to store the results of this request. S3OutputUrl *S3OutputUrl `type:"structure"` } @@ -27196,8 +29451,7 @@ type InstanceAssociationStatusInfo struct { // The name of the association. Name *string `type:"string"` - // A URL for an Amazon S3 bucket where you want to store the results of this - // request. + // A URL for an S3 bucket where you want to store the results of this request. OutputUrl *InstanceAssociationOutputUrl `type:"structure"` // Status information about the instance association. @@ -27309,8 +29563,12 @@ type InstanceInformation struct { IPAddress *string `min:"1" type:"string"` // The Amazon Identity and Access Management (IAM) role assigned to the on-premises - // Systems Manager managed instances. This call does not return the IAM role - // for Amazon EC2 instances. + // Systems Manager managed instance. This call does not return the IAM role + // for EC2 instances. To retrieve the IAM role for an EC2 instance, use the + // Amazon EC2 DescribeInstances action. For information, see DescribeInstances + // (http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html) + // in the Amazon EC2 API Reference or describe-instances (http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html) + // in the AWS CLI Command Reference. IamRole *string `type:"string"` // The instance ID. @@ -27331,7 +29589,17 @@ type InstanceInformation struct { // The last date the association was successfully run. LastSuccessfulAssociationExecutionDate *time.Time `type:"timestamp"` - // The name of the managed instance. + // The name assigned to an on-premises server or virtual machine (VM) when it + // is activated as a Systems Manager managed instance. The name is specified + // as the DefaultInstanceName property using the CreateActivation command. It + // is applied to the managed instance by specifying the Activation Code and + // Activation ID when you install SSM Agent on the instance, as explained in + // Install SSM Agent for a hybrid environment (Linux) (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-install-managed-linux.html) + // and Install SSM Agent for a hybrid environment (Windows) (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-install-managed-win.html). + // To retrieve the Name tag of an EC2 instance, use the Amazon EC2 DescribeInstances + // action. For information, see DescribeInstances (http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html) + // in the Amazon EC2 API Reference or describe-instances (http://docs.aws.amazon.com/cli/latest/reference/ec2/describe-instances.html) + // in the AWS CLI Command Reference. Name *string `type:"string"` // Connection status of SSM Agent. @@ -27617,12 +29885,12 @@ type InstancePatchState struct { FailedCount *int64 `type:"integer"` // An https URL or an Amazon S3 path-style URL to a list of patches to be installed. - // This patch installation list, which you maintain in an Amazon S3 bucket in - // YAML format and specify in the SSM document AWS-RunPatchBaseline, overrides - // the patches specified by the default patch baseline. + // This patch installation list, which you maintain in an S3 bucket in YAML + // format and specify in the SSM document AWS-RunPatchBaseline, overrides the + // patches specified by the default patch baseline. // // For more information about the InstallOverrideList parameter, see About the - // SSM Document AWS-RunPatchBaseline (http://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-about-aws-runpatchbaseline.html) + // SSM document AWS-RunPatchBaseline (https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-about-aws-runpatchbaseline.html) // in the AWS Systems Manager User Guide. InstallOverrideList *string `min:"1" type:"string"` @@ -27637,7 +29905,7 @@ type InstancePatchState struct { // instance was rebooted. InstalledPendingRebootCount *int64 `type:"integer"` - // The number of instances with patches installed that are specified in a RejectedPatches + // The number of patches installed on an instance that are specified in a RejectedPatches // list. Patches with a status of InstalledRejected were typically installed // before they were added to a RejectedPatches list. // @@ -30364,7 +32632,7 @@ func (s *InvalidResultAttributeException) RequestID() string { // The role name can't contain invalid characters. Also verify that you specified // an IAM role for notifications that includes the required trust policy. For // information about configuring the IAM role for Run Command notifications, -// see Configuring Amazon SNS Notifications for Run Command (http://docs.aws.amazon.com/systems-manager/latest/userguide/rc-sns-notifications.html) +// see Configuring Amazon SNS Notifications for Run Command (https://docs.aws.amazon.com/systems-manager/latest/userguide/rc-sns-notifications.html) // in the AWS Systems Manager User Guide. type InvalidRole struct { _ struct{} `type:"structure"` @@ -30478,7 +32746,7 @@ func (s *InvalidSchedule) RequestID() string { } // The target is not valid or does not exist. It might not be configured for -// EC2 Systems Manager or you might not have permission to perform the operation. +// Systems Manager or you might not have permission to perform the operation. type InvalidTarget struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -30740,7 +33008,7 @@ type InventoryDeletionStatusItem struct { DeletionStartTime *time.Time `type:"timestamp"` // Information about the delete operation. For more information about this summary, - // see Understanding the Delete Inventory Summary (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-inventory-custom.html#sysman-inventory-delete) + // see Understanding the delete inventory summary (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-inventory-custom.html#sysman-inventory-delete) // in the AWS Systems Manager User Guide. DeletionSummary *InventoryDeletionSummary `type:"structure"` @@ -30905,6 +33173,10 @@ type InventoryFilter struct { Key *string `min:"1" type:"string" required:"true"` // The type of filter. + // + // The Exists filter must be used with aggregators. For more information, see + // Aggregating inventory data (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-inventory-aggregate.html) + // in the AWS Systems Manager User Guide. Type *string `type:"string" enum:"InventoryQueryOperatorType"` // Inventory filter values. Example: inventory filter where instance IDs are @@ -31594,7 +33866,7 @@ type LabelParameterVersionOutput struct { _ struct{} `type:"structure"` // The label does not meet the requirements. For information about parameter - // label requirements, see Labeling Parameters (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-labels.html) + // label requirements, see Labeling parameters (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-labels.html) // in the AWS Systems Manager User Guide. InvalidLabels []*string `min:"1" type:"list"` @@ -31833,7 +34105,7 @@ type ListCommandInvocationsInput struct { Details *bool `type:"boolean"` // (Optional) One or more filters. Use a filter to return a more specific list - // of results. Note that the DocumentName filter is not supported for ListCommandInvocations. + // of results. Filters []*CommandFilter `min:"1" type:"list"` // (Optional) The command execution details for a specific instance ID. @@ -31968,6 +34240,9 @@ type ListCommandsInput struct { Filters []*CommandFilter `min:"1" type:"list"` // (Optional) Lists commands issued against this instance ID. + // + // You can't specify an instance ID in the same command that you specify Status + // = Pending. This is because the command has not reached the instance yet. InstanceId *string `type:"string"` // (Optional) The maximum number of items to return for this call. The call @@ -32408,10 +34683,15 @@ func (s *ListDocumentVersionsOutput) SetNextToken(v string) *ListDocumentVersion type ListDocumentsInput struct { _ struct{} `type:"structure"` - // One or more filters. Use a filter to return a more specific list of results. + // This data type is deprecated. Instead, use Filters. DocumentFilterList []*DocumentFilter `min:"1" type:"list"` - // One or more filters. Use a filter to return a more specific list of results. + // One or more DocumentKeyValuesFilter objects. Use a filter to return a more + // specific list of results. For keys, you can specify one or more key-value + // pair tags that have been applied to a document. Other valid keys include + // Owner, Name, PlatformTypes, DocumentType, and TargetType. For example, to + // return documents you own use Key=Owner,Values=Self. To specify a custom key-value + // pair, use the format Key=tag:tagName,Values=valueName. Filters []*DocumentKeyValuesFilter `type:"list"` // The maximum number of items to return for this call. The call also returns @@ -32810,7 +35090,7 @@ type ListResourceDataSyncInput struct { NextToken *string `type:"string"` // View a list of resource data syncs according to the sync type. Specify SyncToDestination - // to view resource data syncs that synchronize data to an Amazon S3 buckets. + // to view resource data syncs that synchronize data to an Amazon S3 bucket. // Specify SyncFromSource to view resource data syncs from AWS Organizations // or from multiple AWS Regions. SyncType *string `min:"1" type:"string"` @@ -32968,7 +35248,7 @@ func (s *ListTagsForResourceOutput) SetTagList(v []*Tag) *ListTagsForResourceOut return s } -// Information about an Amazon S3 bucket to write instance-level logs to. +// Information about an S3 bucket to write instance-level logs to. // // LoggingInfo has been deprecated. To specify an S3 bucket to contain logs, // instead use the OutputS3BucketName and OutputS3KeyPrefix options in the TaskInvocationParameters @@ -32977,15 +35257,15 @@ func (s *ListTagsForResourceOutput) SetTagList(v []*Tag) *ListTagsForResourceOut type LoggingInfo struct { _ struct{} `type:"structure"` - // The name of an Amazon S3 bucket where execution logs are stored . + // The name of an S3 bucket where execution logs are stored . // // S3BucketName is a required field S3BucketName *string `min:"3" type:"string" required:"true"` - // (Optional) The Amazon S3 bucket subfolder. + // (Optional) The S3 bucket subfolder. S3KeyPrefix *string `type:"string"` - // The region where the Amazon S3 bucket is located. + // The Region where the S3 bucket is located. // // S3Region is a required field S3Region *string `min:"3" type:"string" required:"true"` @@ -33467,6 +35747,10 @@ type MaintenanceWindowIdentity struct { // The schedule of the maintenance window in the form of a cron or rate expression. Schedule *string `min:"1" type:"string"` + // The number of days to wait to run a maintenance window after the scheduled + // CRON expression date and time. + ScheduleOffset *int64 `min:"1" type:"integer"` + // The time zone that the scheduled maintenance window executions are based // on, in Internet Assigned Numbers Authority (IANA) format. ScheduleTimezone *string `type:"string"` @@ -33537,6 +35821,12 @@ func (s *MaintenanceWindowIdentity) SetSchedule(v string) *MaintenanceWindowIden return s } +// SetScheduleOffset sets the ScheduleOffset field's value. +func (s *MaintenanceWindowIdentity) SetScheduleOffset(v int64) *MaintenanceWindowIdentity { + s.ScheduleOffset = &v + return s +} + // SetScheduleTimezone sets the ScheduleTimezone field's value. func (s *MaintenanceWindowIdentity) SetScheduleTimezone(v string) *MaintenanceWindowIdentity { s.ScheduleTimezone = &v @@ -33719,10 +36009,10 @@ type MaintenanceWindowRunCommandParameters struct { // a per-instance basis. NotificationConfig *NotificationConfig `type:"structure"` - // The name of the Amazon S3 bucket. + // The name of the S3 bucket. OutputS3BucketName *string `min:"3" type:"string"` - // The Amazon S3 bucket subfolder. + // The S3 bucket subfolder. OutputS3KeyPrefix *string `type:"string"` // The parameters for the RUN_COMMAND task execution. @@ -33990,7 +36280,7 @@ type MaintenanceWindowTask struct { // A description of the task. Description *string `min:"1" type:"string" sensitive:"true"` - // Information about an Amazon S3 bucket to write task-level logs to. + // Information about an S3 bucket to write task-level logs to. // // LoggingInfo has been deprecated. To specify an S3 bucket to contain logs, // instead use the OutputS3BucketName and OutputS3KeyPrefix options in the TaskInvocationParameters @@ -34438,8 +36728,8 @@ type NotificationConfig struct { // The different events for which you can receive notifications. These events // include the following: All (events), InProgress, Success, TimedOut, Cancelled, - // Failed. To learn more about these events, see Configuring Amazon SNS Notifications - // for AWS Systems Manager (http://docs.aws.amazon.com/systems-manager/latest/userguide/monitoring-sns-notifications.html) + // Failed. To learn more about these events, see Monitoring Systems Manager + // status changes using Amazon SNS notifications (https://docs.aws.amazon.com/systems-manager/latest/userguide/monitoring-sns-notifications.html) // in the AWS Systems Manager User Guide. NotificationEvents []*string `type:"list"` @@ -34489,7 +36779,7 @@ type OpsAggregator struct { Aggregators []*OpsAggregator `min:"1" type:"list"` // The name of an OpsItem attribute on which to limit the count of OpsItems. - AttributeName *string `type:"string"` + AttributeName *string `min:"1" type:"string"` // The aggregator filters. Filters []*OpsFilter `min:"1" type:"list"` @@ -34520,6 +36810,9 @@ func (s *OpsAggregator) Validate() error { if s.Aggregators != nil && len(s.Aggregators) < 1 { invalidParams.Add(request.NewErrParamMinLen("Aggregators", 1)) } + if s.AttributeName != nil && len(*s.AttributeName) < 1 { + invalidParams.Add(request.NewErrParamMinLen("AttributeName", 1)) + } if s.Filters != nil && len(s.Filters) < 1 { invalidParams.Add(request.NewErrParamMinLen("Filters", 1)) } @@ -34726,7 +37019,7 @@ func (s *OpsFilter) SetValues(v []*string) *OpsFilter { // Operations engineers and IT professionals use OpsCenter to view, investigate, // and remediate operational issues impacting the performance and health of // their AWS resources. For more information, see AWS Systems Manager OpsCenter -// (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html) +// (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter.html) // in the AWS Systems Manager User Guide. type OpsItem struct { _ struct{} `type:"structure"` @@ -34773,7 +37066,7 @@ type OpsItem struct { // Use the /aws/resources key in OperationalData to specify a related resource // in the request. Use the /aws/automations key in OperationalData to associate // an Automation runbook with the OpsItem. To view AWS CLI example commands - // that use these keys, see Creating OpsItems Manually (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems) + // that use these keys, see Creating OpsItems manually (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems) // in the AWS Systems Manager User Guide. OperationalData map[string]*OpsItemDataValue `type:"map"` @@ -34791,12 +37084,12 @@ type OpsItem struct { // The severity of the OpsItem. Severity options range from 1 to 4. Severity *string `min:"1" type:"string"` - // The origin of the OpsItem, such as Amazon EC2 or AWS Systems Manager. The - // impacted resource is a subset of source. + // The origin of the OpsItem, such as Amazon EC2 or Systems Manager. The impacted + // resource is a subset of source. Source *string `min:"1" type:"string"` // The OpsItem status. Status can be Open, In Progress, or Resolved. For more - // information, see Editing OpsItem Details (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems-editing-details.html) + // information, see Editing OpsItem details (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems-editing-details.html) // in the AWS Systems Manager User Guide. Status *string `type:"string" enum:"OpsItemStatus"` @@ -35134,7 +37427,7 @@ func (s *OpsItemInvalidParameterException) RequestID() string { } // The request caused OpsItems to exceed one or more quotas. For information -// about OpsItem quotas, see What are the resource limits for OpsCenter? (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-learn-more.html#OpsCenter-learn-more-limits). +// about OpsItem quotas, see What are the resource limits for OpsCenter? (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-learn-more.html#OpsCenter-learn-more-limits). type OpsItemLimitExceededException struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -35450,7 +37743,7 @@ func (s *OpsResultAttribute) SetTypeName(v string) *OpsResultAttribute { type OutputSource struct { _ struct{} `type:"structure"` - // The ID of the output source, for example the URL of an Amazon S3 bucket. + // The ID of the output source, for example the URL of an S3 bucket. OutputSourceId *string `min:"36" type:"string"` // The type of source where the association execution details are stored, for @@ -35480,13 +37773,17 @@ func (s *OutputSource) SetOutputSourceType(v string) *OutputSource { return s } -// An Amazon EC2 Systems Manager parameter in Parameter Store. +// An Systems Manager parameter in Parameter Store. type Parameter struct { _ struct{} `type:"structure"` // The Amazon Resource Name (ARN) of the parameter. ARN *string `type:"string"` + // The data type of the parameter, such as text or aws:ec2:image. The default + // is text. + DataType *string `type:"string"` + // Date the parameter was last changed or updated and the parameter version // was created. LastModifiedDate *time.Time `type:"timestamp"` @@ -35506,8 +37803,8 @@ type Parameter struct { // is the raw result or response from the source. SourceResult *string `type:"string"` - // The type of parameter. Valid values include the following: String, String - // list, Secure string. + // The type of parameter. Valid values include the following: String, StringList, + // and SecureString. Type *string `type:"string" enum:"ParameterType"` // The parameter value. @@ -35533,6 +37830,12 @@ func (s *Parameter) SetARN(v string) *Parameter { return s } +// SetDataType sets the DataType field's value. +func (s *Parameter) SetDataType(v string) *Parameter { + s.DataType = &v + return s +} + // SetLastModifiedDate sets the LastModifiedDate field's value. func (s *Parameter) SetLastModifiedDate(v time.Time) *Parameter { s.LastModifiedDate = &v @@ -35640,6 +37943,10 @@ type ParameterHistory struct { // a-zA-Z0-9_.- AllowedPattern *string `type:"string"` + // The data type of the parameter, such as text or aws:ec2:image. The default + // is text. + DataType *string `type:"string"` + // Information about the parameter. Description *string `type:"string"` @@ -35660,7 +37967,7 @@ type ParameterHistory struct { // Information about the policies assigned to a parameter. // - // Working with Parameter Policies (https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-policies.html) + // Assigning parameter policies (https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-policies.html) // in the AWS Systems Manager User Guide. Policies []*ParameterInlinePolicy `type:"list"` @@ -35693,6 +38000,12 @@ func (s *ParameterHistory) SetAllowedPattern(v string) *ParameterHistory { return s } +// SetDataType sets the DataType field's value. +func (s *ParameterHistory) SetDataType(v string) *ParameterHistory { + s.DataType = &v + return s +} + // SetDescription sets the Description field's value. func (s *ParameterHistory) SetDescription(v string) *ParameterHistory { s.Description = &v @@ -35928,6 +38241,10 @@ type ParameterMetadata struct { // a-zA-Z0-9_.- AllowedPattern *string `type:"string"` + // The data type of the parameter, such as text or aws:ec2:image. The default + // is text. + DataType *string `type:"string"` + // Description of the parameter actions. Description *string `type:"string"` @@ -35950,7 +38267,7 @@ type ParameterMetadata struct { Tier *string `type:"string" enum:"ParameterTier"` // The type of parameter. Valid parameter types include the following: String, - // String list, Secure string. + // StringList, and SecureString. Type *string `type:"string" enum:"ParameterType"` // The parameter version. @@ -35973,6 +38290,12 @@ func (s *ParameterMetadata) SetAllowedPattern(v string) *ParameterMetadata { return s } +// SetDataType sets the DataType field's value. +func (s *ParameterMetadata) SetDataType(v string) *ParameterMetadata { + s.DataType = &v + return s +} + // SetDescription sets the Description field's value. func (s *ParameterMetadata) SetDescription(v string) *ParameterMetadata { s.Description = &v @@ -36141,25 +38464,25 @@ func (s *ParameterPatternMismatchException) RequestID() string { } // One or more filters. Use a filter to return a more specific list of results. -// -// The ParameterStringFilter object is used by the DescribeParameters and GetParametersByPath -// API actions. However, not all of the pattern values listed for Key can be -// used with both actions. -// -// For DescribeActions, all of the listed patterns are valid, with the exception -// of Label. -// -// For GetParametersByPath, the following patterns listed for Key are not valid: -// Name, Path, and Tier. -// -// For examples of CLI commands demonstrating valid parameter filter constructions, -// see Searching for Systems Manager Parameters (http://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-search.html) -// in the AWS Systems Manager User Guide. type ParameterStringFilter struct { _ struct{} `type:"structure"` // The name of the filter. // + // The ParameterStringFilter object is used by the DescribeParameters and GetParametersByPath + // API actions. However, not all of the pattern values listed for Key can be + // used with both actions. + // + // For DescribeActions, all of the listed patterns are valid, with the exception + // of Label. + // + // For GetParametersByPath, the following patterns listed for Key are not valid: + // tag, Name, Path, and Tier. + // + // For examples of CLI commands demonstrating valid parameter filter constructions, + // see Searching for Systems Manager parameters (https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-search.html) + // in the AWS Systems Manager User Guide. + // // Key is a required field Key *string `min:"1" type:"string" required:"true"` @@ -36169,8 +38492,8 @@ type ParameterStringFilter struct { // and OneLevel.) // // For filters used with GetParametersByPath, valid options include Equals and - // BeginsWith. (Exception: For filters using the key Label, the only valid option - // is Equals.) + // BeginsWith. (Exception: For filters using Label as the Key name, the only + // valid option is Equals.) Option *string `min:"1" type:"string"` // The value you want to search for. @@ -36620,7 +38943,7 @@ type PatchComplianceData struct { // The state of the patch on the instance, such as INSTALLED or FAILED. // - // For descriptions of each patch state, see About Patch Compliance (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-compliance-about.html#sysman-compliance-monitor-patch) + // For descriptions of each patch state, see About patch compliance (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-compliance-about.html#sysman-compliance-monitor-patch) // in the AWS Systems Manager User Guide. // // State is a required field @@ -36890,14 +39213,17 @@ type PatchRule struct { // The number of days after the release date of each patch matched by the rule // that the patch is marked as approved in the patch baseline. For example, // a value of 7 means that patches are approved seven days after they are released. + // Not supported on Ubuntu Server. ApproveAfterDays *int64 `type:"integer"` - // Example API + // The cutoff date for auto approval of released patches. Any patches released + // on or before this date are installed automatically. Not supported on Ubuntu + // Server. + // + // Enter dates in the format YYYY-MM-DD. For example, 2020-12-31. ApproveUntilDate *string `min:"1" type:"string"` // A compliance severity level for all approved patches in a patch baseline. - // Valid compliance severity levels include the following: Unspecified, Critical, - // High, Medium, Low, and Informational. ComplianceLevel *string `type:"string" enum:"PatchComplianceLevel"` // For instances identified by the approval rule filters, enables a patch baseline @@ -37294,7 +39620,7 @@ type PutComplianceItemsInput struct { // Information about the compliance as defined by the resource type. For example, // for a patch compliance type, Items includes information about the PatchSeverity, - // Classification, etc. + // Classification, and so on. // // Items is a required field Items []*ComplianceItemEntry `type:"list" required:"true"` @@ -37310,6 +39636,18 @@ type PutComplianceItemsInput struct { // // ResourceType is a required field ResourceType *string `min:"1" type:"string" required:"true"` + + // The mode for uploading compliance items. You can specify COMPLETE or PARTIAL. + // In COMPLETE mode, the system overwrites all existing compliance information + // for the resource. You must provide a full list of compliance items each time + // you send the request. + // + // In PARTIAL mode, the system overwrites compliance information for a specific + // association. The association must be configured with SyncCompliance set to + // MANUAL. By default, all requests use COMPLETE mode. + // + // This attribute is only valid for association compliance. + UploadType *string `type:"string" enum:"ComplianceUploadType"` } // String returns the string representation @@ -37407,6 +39745,12 @@ func (s *PutComplianceItemsInput) SetResourceType(v string) *PutComplianceItemsI return s } +// SetUploadType sets the UploadType field's value. +func (s *PutComplianceItemsInput) SetUploadType(v string) *PutComplianceItemsInput { + s.UploadType = &v + return s +} + type PutComplianceItemsOutput struct { _ struct{} `type:"structure"` } @@ -37517,6 +39861,22 @@ type PutParameterInput struct { // AllowedPattern=^\d+$ AllowedPattern *string `type:"string"` + // The data type for a String parameter. Supported data types include plain + // text and Amazon Machine Image IDs. + // + // The following data type values are supported. + // + // * text + // + // * aws:ec2:image + // + // When you create a String parameter and specify aws:ec2:image, Systems Manager + // validates the parameter value is in the required format, such as ami-12345abcdeEXAMPLE, + // and that the specified AMI is available in your AWS account. For more information, + // see Native parameter support for Amazon Machine Image IDs (http://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-ec2-aliases.html) + // in the AWS Systems Manager User Guide. + DataType *string `type:"string"` + // Information about the parameter that you want to add to the system. Optional // but recommended. // @@ -37560,8 +39920,8 @@ type PutParameterInput struct { // // * Parameter hierarchies are limited to a maximum depth of fifteen levels. // - // For additional information about valid values for parameter names, see Requirements - // and Constraints for Parameter Names (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-parameter-name-constraints.html) + // For additional information about valid values for parameter names, see About + // requirements and constraints for parameter names (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-parameter-name-constraints.html) // in the AWS Systems Manager User Guide. // // The maximum length constraint listed below includes capacity for additional @@ -37598,8 +39958,8 @@ type PutParameterInput struct { // time, but it has not been changed. // // All existing policies are preserved until you send new policies or an empty - // policy. For more information about parameter policies, see Working with Parameter - // Policies (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-su-policies.html). + // policy. For more information about parameter policies, see Assigning parameter + // policies (https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-policies.html). Policies *string `min:"1" type:"string"` // Optional metadata that you assign to a resource. Tags enable you to categorize @@ -37630,7 +39990,7 @@ type PutParameterInput struct { // Advanced parameters have a content size limit of 8 KB and can be configured // to use parameter policies. You can create a maximum of 100,000 advanced parameters // for each Region in an AWS account. Advanced parameters incur a charge. For - // more information, see About Advanced Parameters (http://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html) + // more information, see Standard and advanced parameter tiers (https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html) // in the AWS Systems Manager User Guide. // // You can change a standard parameter to an advanced parameter any time. But @@ -37678,25 +40038,29 @@ type PutParameterInput struct { // current Region. // // For more information about configuring the default tier option, see Specifying - // a Default Parameter Tier (http://docs.aws.amazon.com/systems-manager/latest/userguide/ps-default-tier.html) + // a default parameter tier (https://docs.aws.amazon.com/systems-manager/latest/userguide/ps-default-tier.html) // in the AWS Systems Manager User Guide. Tier *string `type:"string" enum:"ParameterTier"` // The type of parameter that you want to add to the system. // + // SecureString is not currently supported for AWS CloudFormation templates + // or in the China Regions. + // // Items in a StringList must be separated by a comma (,). You can't use other // punctuation or special character to escape items in the list. If you have // a parameter value that requires a comma, then use the String data type. // - // SecureString is not currently supported for AWS CloudFormation templates - // or in the China Regions. - // - // Type is a required field - Type *string `type:"string" required:"true" enum:"ParameterType"` + // Specifying a parameter type is not required when updating a parameter. You + // must specify a parameter type when creating a parameter. + Type *string `type:"string" enum:"ParameterType"` // The parameter value that you want to add to the system. Standard parameters // have a value limit of 4 KB. Advanced parameters have a value limit of 8 KB. // + // Parameters can't be referenced or nested in the values of other parameters. + // You can't include {{}} or {{ssm:parameter-name}} in a parameter value. + // // Value is a required field Value *string `type:"string" required:"true"` } @@ -37726,9 +40090,6 @@ func (s *PutParameterInput) Validate() error { if s.Policies != nil && len(*s.Policies) < 1 { invalidParams.Add(request.NewErrParamMinLen("Policies", 1)) } - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) - } if s.Value == nil { invalidParams.Add(request.NewErrParamRequired("Value")) } @@ -37755,6 +40116,12 @@ func (s *PutParameterInput) SetAllowedPattern(v string) *PutParameterInput { return s } +// SetDataType sets the DataType field's value. +func (s *PutParameterInput) SetDataType(v string) *PutParameterInput { + s.DataType = &v + return s +} + // SetDescription sets the Description field's value. func (s *PutParameterInput) SetDescription(v string) *PutParameterInput { s.Description = &v @@ -38053,7 +40420,7 @@ type RegisterTargetWithMaintenanceWindowInput struct { // Key=resource-groups:ResourceTypeFilters,Values=AWS::EC2::INSTANCE,AWS::EC2::VPC // // For more information about these examples formats, including the best use - // case for each one, see Examples: Register Targets with a Maintenance Window + // case for each one, see Examples: Register targets with a maintenance window // (https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-targets-examples.html) // in the AWS Systems Manager User Guide. // @@ -38194,7 +40561,7 @@ type RegisterTaskWithMaintenanceWindowInput struct { // An optional description for the task. Description *string `min:"1" type:"string" sensitive:"true"` - // A structure containing information about an Amazon S3 bucket to write instance-level + // A structure containing information about an S3 bucket to write instance-level // logs to. // // LoggingInfo has been deprecated. To specify an S3 bucket to contain logs, @@ -38229,10 +40596,10 @@ type RegisterTaskWithMaintenanceWindowInput struct { // For more information, see the following topics in the in the AWS Systems // Manager User Guide: // - // * Service-Linked Role Permissions for Systems Manager (http://docs.aws.amazon.com/systems-manager/latest/userguide/using-service-linked-roles.html#slr-permissions) + // * Using service-linked roles for Systems Manager (https://docs.aws.amazon.com/systems-manager/latest/userguide/using-service-linked-roles.html#slr-permissions) // - // * Should I Use a Service-Linked Role or a Custom Service Role to Run Maintenance - // Window Tasks? (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-maintenance-permissions.html#maintenance-window-tasks-service-role) + // * Should I use a service-linked role or a custom service role to run maintenance + // window tasks? (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-maintenance-permissions.html#maintenance-window-tasks-service-role) ServiceRoleArn *string `type:"string"` // The targets (either instances or maintenance window targets). @@ -38603,7 +40970,9 @@ func (s RemoveTagsFromResourceOutput) GoString() string { type ResetServiceSettingInput struct { _ struct{} `type:"structure"` - // The ID of the service setting to reset. + // The Amazon Resource Name (ARN) of the service setting to reset. The setting + // ID can be /ssm/parameter-store/default-parameter-tier, /ssm/parameter-store/high-throughput-enabled, + // or /ssm/managed-instance/activation-tier. For example, arn:aws:ssm:us-east-1:111122223333:servicesetting/ssm/parameter-store/high-throughput-enabled. // // SettingId is a required field SettingId *string `min:"1" type:"string" required:"true"` @@ -39029,8 +41398,8 @@ func (s *ResourceDataSyncCountExceededException) RequestID() string { } // Synchronize Systems Manager Inventory data from multiple AWS accounts defined -// in AWS Organizations to a centralized Amazon S3 bucket. Data is synchronized -// to individual key prefixes in the central bucket. Each key prefix represents +// in AWS Organizations to a centralized S3 bucket. Data is synchronized to +// individual key prefixes in the central bucket. Each key prefix represents // a different AWS account ID. type ResourceDataSyncDestinationDataSharing struct { _ struct{} `type:"structure"` @@ -39141,7 +41510,7 @@ type ResourceDataSyncItem struct { // The last time the configuration attempted to sync (UTC). LastSyncTime *time.Time `type:"timestamp"` - // Configuration information for the target Amazon S3 bucket. + // Configuration information for the target S3 bucket. S3Destination *ResourceDataSyncS3Destination `type:"structure"` // The date and time the configuration was created (UTC). @@ -39157,9 +41526,9 @@ type ResourceDataSyncItem struct { SyncSource *ResourceDataSyncSourceWithState `type:"structure"` // The type of resource data sync. If SyncType is SyncToDestination, then the - // resource data sync synchronizes data to an Amazon S3 bucket. If the SyncType - // is SyncFromSource then the resource data sync synchronizes data from AWS - // Organizations or from multiple AWS Regions. + // resource data sync synchronizes data to an S3 bucket. If the SyncType is + // SyncFromSource then the resource data sync synchronizes data from AWS Organizations + // or from multiple AWS Regions. SyncType *string `min:"1" type:"string"` } @@ -39330,15 +41699,15 @@ func (s *ResourceDataSyncOrganizationalUnit) SetOrganizationalUnitId(v string) * return s } -// Information about the target Amazon S3 bucket for the Resource Data Sync. +// Information about the target S3 bucket for the Resource Data Sync. type ResourceDataSyncS3Destination struct { _ struct{} `type:"structure"` // The ARN of an encryption key for a destination in Amazon S3. Must belong - // to the same Region as the destination Amazon S3 bucket. + // to the same Region as the destination S3 bucket. AWSKMSKeyARN *string `min:"1" type:"string"` - // The name of the Amazon S3 bucket where the aggregated data is stored. + // The name of the S3 bucket where the aggregated data is stored. // // BucketName is a required field BucketName *string `min:"1" type:"string" required:"true"` @@ -39349,7 +41718,7 @@ type ResourceDataSyncS3Destination struct { // An Amazon S3 prefix for the bucket. Prefix *string `min:"1" type:"string"` - // The AWS Region with the Amazon S3 bucket targeted by the Resource Data Sync. + // The AWS Region with the S3 bucket targeted by the Resource Data Sync. // // Region is a required field Region *string `min:"1" type:"string" required:"true"` @@ -39674,7 +42043,7 @@ func (s *ResourceInUseException) RequestID() string { // For example, too many maintenance windows or patch baselines have been created. // // For information about resource quotas in Systems Manager, see Systems Manager -// Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) +// service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. type ResourceLimitExceededException struct { _ struct{} `type:"structure"` @@ -39826,8 +42195,8 @@ type ResumeSessionOutput struct { // // region represents the Region identifier for an AWS Region supported by AWS // Systems Manager, such as us-east-2 for the US East (Ohio) Region. For a list - // of supported region values, see the Region column in Systems Manager Service - // Endpoints (http://docs.aws.amazon.com/general/latest/gr/ssm.html#ssm_region) + // of supported region values, see the Region column in Systems Manager service + // endpoints (http://docs.aws.amazon.com/general/latest/gr/ssm.html#ssm_region) // in the AWS General Reference. // // session-id represents the ID of a Session Manager session, such as 1a2b3c4dEXAMPLE. @@ -39866,19 +42235,19 @@ func (s *ResumeSessionOutput) SetTokenValue(v string) *ResumeSessionOutput { return s } -// An Amazon S3 bucket where you want to store the results of this request. +// An S3 bucket where you want to store the results of this request. type S3OutputLocation struct { _ struct{} `type:"structure"` - // The name of the Amazon S3 bucket. + // The name of the S3 bucket. OutputS3BucketName *string `min:"3" type:"string"` - // The Amazon S3 bucket subfolder. + // The S3 bucket subfolder. OutputS3KeyPrefix *string `type:"string"` // (Deprecated) You can no longer specify this parameter. The system ignores - // it. Instead, Systems Manager automatically determines the Amazon S3 bucket - // region. + // it. Instead, Systems Manager automatically determines the Region of the S3 + // bucket. OutputS3Region *string `min:"3" type:"string"` } @@ -39926,13 +42295,11 @@ func (s *S3OutputLocation) SetOutputS3Region(v string) *S3OutputLocation { return s } -// A URL for the Amazon S3 bucket where you want to store the results of this -// request. +// A URL for the S3 bucket where you want to store the results of this request. type S3OutputUrl struct { _ struct{} `type:"structure"` - // A URL for an Amazon S3 bucket where you want to store the results of this - // request. + // A URL for an S3 bucket where you want to store the results of this request. OutputUrl *string `type:"string"` } @@ -40132,18 +42499,25 @@ type SendCommandInput struct { // --document-version "3" DocumentVersion *string `type:"string"` - // The instance IDs where the command should run. You can specify a maximum - // of 50 IDs. If you prefer not to list individual instance IDs, you can instead - // send commands to a fleet of instances using the Targets parameter, which - // accepts EC2 tags. For more information about how to use targets, see Sending - // Commands to a Fleet (http://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html) + // The IDs of the instances where the command should run. Specifying instance + // IDs is most useful when you are targeting a limited number of instances, + // though you can specify up to 50 IDs. + // + // To target a larger number of instances, or if you prefer not to list individual + // instance IDs, we recommend using the Targets option instead. Using Targets, + // which accepts tag key-value pairs to identify the instances to send commands + // to, you can a send command to tens, hundreds, or thousands of instances at + // once. + // + // For more information about how to use targets, see Using targets and rate + // controls to send commands to a fleet (https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html) // in the AWS Systems Manager User Guide. InstanceIds []*string `type:"list"` // (Optional) The maximum number of instances that are allowed to run the command // at the same time. You can specify a number such as 10 or a percentage such // as 10%. The default value is 50. For more information about how to use MaxConcurrency, - // see Using Concurrency Controls (http://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html#send-commands-velocity) + // see Using concurrency controls (https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html#send-commands-velocity) // in the AWS Systems Manager User Guide. MaxConcurrency *string `min:"1" type:"string"` @@ -40151,7 +42525,7 @@ type SendCommandInput struct { // command fails one more time beyond the value of MaxErrors, the systems stops // sending the command to additional targets. You can specify a number like // 10 or a percentage like 10%. The default value is 0. For more information - // about how to use MaxErrors, see Using Error Controls (http://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html#send-commands-maxerrors) + // about how to use MaxErrors, see Using error controls (https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html#send-commands-maxerrors) // in the AWS Systems Manager User Guide. MaxErrors *string `min:"1" type:"string"` @@ -40166,8 +42540,8 @@ type SendCommandInput struct { OutputS3KeyPrefix *string `type:"string"` // (Deprecated) You can no longer specify this parameter. The system ignores - // it. Instead, Systems Manager automatically determines the Amazon S3 bucket - // region. + // it. Instead, Systems Manager automatically determines the Region of the S3 + // bucket. OutputS3Region *string `min:"3" type:"string"` // The required and optional parameters specified in the document being run. @@ -40177,10 +42551,17 @@ type SendCommandInput struct { // Service (Amazon SNS) notifications for Run Command commands. ServiceRoleArn *string `type:"string"` - // (Optional) An array of search criteria that targets instances using a Key,Value - // combination that you specify. Targets is required if you don't provide one - // or more instance IDs in the call. For more information about how to use targets, - // see Sending Commands to a Fleet (http://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html) + // An array of search criteria that targets instances using a Key,Value combination + // that you specify. Specifying targets is most useful when you want to send + // a command to a large number of instances at once. Using Targets, which accepts + // tag key-value pairs to identify instances, you can send a command to tens, + // hundreds, or thousands of instances at once. + // + // To send a command to a smaller number of instances, you can use the InstanceIds + // option instead. + // + // For more information about how to use targets, see Sending commands to a + // fleet (https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html) // in the AWS Systems Manager User Guide. Targets []*Target `type:"list"` @@ -40918,8 +43299,8 @@ type StartAutomationExecutionInput struct { // A location is a combination of AWS Regions and/or AWS accounts where you // want to run the Automation. Use this action to start an Automation in multiple - // Regions and multiple accounts. For more information, see Executing Automations - // in Multiple AWS Regions and Accounts (http://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-automation-multiple-accounts-and-regions.html) + // Regions and multiple accounts. For more information, see Running Automation + // workflows in multiple AWS Regions and accounts (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-automation-multiple-accounts-and-regions.html) // in the AWS Systems Manager User Guide. TargetLocations []*TargetLocation `min:"1" type:"list"` @@ -41105,8 +43486,10 @@ type StartSessionInput struct { _ struct{} `type:"structure"` // The name of the SSM document to define the parameters and plugin settings - // for the session. For example, SSM-SessionManagerRunShell. If no document - // name is provided, a shell to the instance is launched by default. + // for the session. For example, SSM-SessionManagerRunShell. You can call the + // GetDocument API to verify the document exists before attempting to start + // a session. If no document name is provided, a shell to the instance is launched + // by default. DocumentName *string `type:"string"` // Reserved for future use. @@ -41173,8 +43556,8 @@ type StartSessionOutput struct { // // region represents the Region identifier for an AWS Region supported by AWS // Systems Manager, such as us-east-2 for the US East (Ohio) Region. For a list - // of supported region values, see the Region column in Systems Manager Service - // Endpoints (http://docs.aws.amazon.com/general/latest/gr/ssm.html#ssm_region) + // of supported region values, see the Region column in Systems Manager service + // endpoints (http://docs.aws.amazon.com/general/latest/gr/ssm.html#ssm_region) // in the AWS General Reference. // // session-id represents the ID of a Session Manager session, such as 1a2b3c4dEXAMPLE. @@ -41746,9 +44129,11 @@ func (s *Tag) SetValue(v string) *Tag { // // * Key=tag-key,Values=my-tag-key-1,my-tag-key-2 // -// * (Maintenance window targets only) Key=resource-groups:Name,Values=resource-group-name +// * Run Command and Maintenance window targets only: Key=resource-groups:Name,Values=resource-group-name // -// * (Maintenance window targets only) Key=resource-groups:ResourceTypeFilters,Values=resource-type-1,resource-type-2 +// * Maintenance window targets only: Key=resource-groups:ResourceTypeFilters,Values=resource-type-1,resource-type-2 +// +// * Automation targets only: Key=ResourceGroup;Values=resource-group-name // // For example: // @@ -41758,21 +44143,22 @@ func (s *Tag) SetValue(v string) *Tag { // // * Key=tag-key,Values=Name,Instance-Type,CostCenter // -// * (Maintenance window targets only) Key=resource-groups:Name,Values=ProductionResourceGroup +// * Run Command and Maintenance window targets only: Key=resource-groups:Name,Values=ProductionResourceGroup // This example demonstrates how to target all resources in the resource // group ProductionResourceGroup in your maintenance window. // -// * (Maintenance window targets only) Key=resource-groups:ResourceTypeFilters,Values=AWS::EC2::INSTANCE,AWS::EC2::VPC -// This example demonstrates how to target only Amazon EC2 instances and -// VPCs in your maintenance window. +// * Maintenance window targets only: Key=resource-groups:ResourceTypeFilters,Values=AWS::EC2::INSTANCE,AWS::EC2::VPC +// This example demonstrates how to target only EC2 instances and VPCs in +// your maintenance window. // -// * (State Manager association targets only) Key=InstanceIds,Values=* This +// * Automation targets only: Key=ResourceGroup,Values=MyResourceGroup +// +// * State Manager association targets only: Key=InstanceIds,Values=* This // example demonstrates how to target all managed instances in the AWS Region // where the association was created. // -// For information about how to send commands that target instances using Key,Value -// parameters, see Using Targets and Rate Controls to Send Commands to a Fleet -// (https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html#send-commands-targeting) +// For more information about how to send commands that target instances using +// Key,Value parameters, see Targeting multiple instances (https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html#send-commands-targeting) // in the AWS Systems Manager User Guide. type Target struct { _ struct{} `type:"structure"` @@ -41783,7 +44169,7 @@ type Target struct { // User-defined criteria that maps to Key. For example, if you specified tag:ServerRole, // you could specify value:WebServer to run a command on instances that include - // Amazon EC2 tags of ServerRole,WebServer. + // EC2 tags of ServerRole,WebServer. Values []*string `type:"list"` } @@ -41968,8 +44354,8 @@ func (s *TargetLocation) SetTargetLocationMaxErrors(v string) *TargetLocation { } // The specified target instance for the session is not fully configured for -// use with Session Manager. For more information, see Getting Started with -// Session Manager (http://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started.html) +// use with Session Manager. For more information, see Getting started with +// Session Manager (https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started.html) // in the AWS Systems Manager User Guide. type TargetNotConnected struct { _ struct{} `type:"structure"` @@ -42317,10 +44703,10 @@ func (s *UnsupportedCalendarException) RequestID() string { return s.RespMetadata.RequestID } -// Microsoft application patching is only available on EC2 instances and Advanced -// Instances. To patch Microsoft applications on on-premises servers and VMs, -// you must enable Advanced Instances. For more information, see Using the Advanced-Instances -// Tier (http://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-managedinstances-advanced.html) +// Microsoft application patching is only available on EC2 instances and advanced +// instances. To patch Microsoft applications on on-premises servers and VMs, +// you must enable advanced instances. For more information, see Using the advanced-instances +// tier (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-managedinstances-advanced.html) // in the AWS Systems Manager User Guide. type UnsupportedFeatureRequiredException struct { _ struct{} `type:"structure"` @@ -42496,8 +44882,7 @@ func (s *UnsupportedInventorySchemaVersionException) RequestID() string { } // The operating systems you specified is not supported, or the operation is -// not supported for the operating system. Valid operating systems include: -// Windows, AmazonLinux, RedhatEnterpriseLinux, and Ubuntu. +// not supported for the operating system. type UnsupportedOperatingSystem struct { _ struct{} `type:"structure"` RespMetadata protocol.ResponseMetadata `json:"-" xml:"-"` @@ -42669,6 +45054,18 @@ func (s *UnsupportedPlatformType) RequestID() string { type UpdateAssociationInput struct { _ struct{} `type:"structure"` + // By default, when you update an association, the system runs it immediately + // after it is updated and then according to the schedule you specified. Specify + // this option if you don't want an association to run immediately after you + // update it. + // + // Also, if you specified this option when you created the association, you + // can reset it. To do so, specify the no-apply-only-at-cron-interval parameter + // when you update the association from the command line. This parameter forces + // the association to run immediately after updating it and according to the + // interval specified. + ApplyOnlyAtCronInterval *bool `type:"boolean"` + // The ID of the association you want to update. // // AssociationId is a required field @@ -42738,7 +45135,7 @@ type UpdateAssociationInput struct { // or My-Document. Name *string `type:"string"` - // An Amazon S3 bucket where you want to store the results of this request. + // An S3 bucket where you want to store the results of this request. OutputLocation *InstanceAssociationOutputLocation `type:"structure"` // The parameters you want to update for the association. If you create a parameter @@ -42748,6 +45145,20 @@ type UpdateAssociationInput struct { // The cron expression used to schedule the association that you want to update. ScheduleExpression *string `min:"1" type:"string"` + // The mode for generating association compliance. You can specify AUTO or MANUAL. + // In AUTO mode, the system uses the status of the association execution to + // determine the compliance status. If the association execution runs successfully, + // then the association is COMPLIANT. If the association execution doesn't run + // successfully, the association is NON-COMPLIANT. + // + // In MANUAL mode, you must specify the AssociationId as a parameter for the + // PutComplianceItems API action. In this case, compliance data is not managed + // by State Manager. It is managed by your direct call to the PutComplianceItems + // API action. + // + // By default, all associations use AUTO mode. + SyncCompliance *string `type:"string" enum:"AssociationSyncCompliance"` + // The targets of the association. Targets []*Target `type:"list"` } @@ -42802,6 +45213,12 @@ func (s *UpdateAssociationInput) Validate() error { return nil } +// SetApplyOnlyAtCronInterval sets the ApplyOnlyAtCronInterval field's value. +func (s *UpdateAssociationInput) SetApplyOnlyAtCronInterval(v bool) *UpdateAssociationInput { + s.ApplyOnlyAtCronInterval = &v + return s +} + // SetAssociationId sets the AssociationId field's value. func (s *UpdateAssociationInput) SetAssociationId(v string) *UpdateAssociationInput { s.AssociationId = &v @@ -42874,6 +45291,12 @@ func (s *UpdateAssociationInput) SetScheduleExpression(v string) *UpdateAssociat return s } +// SetSyncCompliance sets the SyncCompliance field's value. +func (s *UpdateAssociationInput) SetSyncCompliance(v string) *UpdateAssociationInput { + s.SyncCompliance = &v + return s +} + // SetTargets sets the Targets field's value. func (s *UpdateAssociationInput) SetTargets(v []*Target) *UpdateAssociationInput { s.Targets = v @@ -43089,7 +45512,9 @@ type UpdateDocumentInput struct { // supports JSON and YAML documents. JSON is the default format. DocumentFormat *string `type:"string" enum:"DocumentFormat"` - // (Required) The version of the document that you want to update. + // (Required) The latest version of the document that you want to update. The + // latest document version can be specified using the $LATEST variable or by + // the version number. Updating a previous version of a document is not supported. DocumentVersion *string `type:"string"` // The name of the document that you want to update. @@ -43246,6 +45671,18 @@ type UpdateMaintenanceWindowInput struct { // The schedule of the maintenance window in the form of a cron or rate expression. Schedule *string `min:"1" type:"string"` + // The number of days to wait after the date and time specified by a CRON expression + // before running the maintenance window. + // + // For example, the following cron expression schedules a maintenance window + // to run the third Tuesday of every month at 11:30 PM. + // + // cron(0 30 23 ? * TUE#3 *) + // + // If the schedule offset is 2, the maintenance window won't run until two days + // later. + ScheduleOffset *int64 `min:"1" type:"integer"` + // The time zone that the scheduled maintenance window executions are based // on, in Internet Assigned Numbers Authority (IANA) format. For example: "America/Los_Angeles", // "etc/UTC", or "Asia/Seoul". For more information, see the Time Zone Database @@ -43289,6 +45726,9 @@ func (s *UpdateMaintenanceWindowInput) Validate() error { if s.Schedule != nil && len(*s.Schedule) < 1 { invalidParams.Add(request.NewErrParamMinLen("Schedule", 1)) } + if s.ScheduleOffset != nil && *s.ScheduleOffset < 1 { + invalidParams.Add(request.NewErrParamMinValue("ScheduleOffset", 1)) + } if s.WindowId == nil { invalidParams.Add(request.NewErrParamRequired("WindowId")) } @@ -43356,6 +45796,12 @@ func (s *UpdateMaintenanceWindowInput) SetSchedule(v string) *UpdateMaintenanceW return s } +// SetScheduleOffset sets the ScheduleOffset field's value. +func (s *UpdateMaintenanceWindowInput) SetScheduleOffset(v int64) *UpdateMaintenanceWindowInput { + s.ScheduleOffset = &v + return s +} + // SetScheduleTimezone sets the ScheduleTimezone field's value. func (s *UpdateMaintenanceWindowInput) SetScheduleTimezone(v string) *UpdateMaintenanceWindowInput { s.ScheduleTimezone = &v @@ -43405,6 +45851,10 @@ type UpdateMaintenanceWindowOutput struct { // The schedule of the maintenance window in the form of a cron or rate expression. Schedule *string `min:"1" type:"string"` + // The number of days to wait to run a maintenance window after the scheduled + // CRON expression date and time. + ScheduleOffset *int64 `min:"1" type:"integer"` + // The time zone that the scheduled maintenance window executions are based // on, in Internet Assigned Numbers Authority (IANA) format. For example: "America/Los_Angeles", // "etc/UTC", or "Asia/Seoul". For more information, see the Time Zone Database @@ -43478,6 +45928,12 @@ func (s *UpdateMaintenanceWindowOutput) SetSchedule(v string) *UpdateMaintenance return s } +// SetScheduleOffset sets the ScheduleOffset field's value. +func (s *UpdateMaintenanceWindowOutput) SetScheduleOffset(v int64) *UpdateMaintenanceWindowOutput { + s.ScheduleOffset = &v + return s +} + // SetScheduleTimezone sets the ScheduleTimezone field's value. func (s *UpdateMaintenanceWindowOutput) SetScheduleTimezone(v string) *UpdateMaintenanceWindowOutput { s.ScheduleTimezone = &v @@ -43718,7 +46174,7 @@ type UpdateMaintenanceWindowTaskInput struct { // Tasks that have the same priority are scheduled in parallel. Priority *int64 `type:"integer"` - // If True, then all fields that are required by the RegisterTaskWithMaintenanceWndow + // If True, then all fields that are required by the RegisterTaskWithMaintenanceWindow // action are also required for this API request. Optional fields that are not // specified are set to null. Replace *bool `type:"boolean"` @@ -43731,10 +46187,10 @@ type UpdateMaintenanceWindowTaskInput struct { // For more information, see the following topics in the in the AWS Systems // Manager User Guide: // - // * Service-Linked Role Permissions for Systems Manager (http://docs.aws.amazon.com/systems-manager/latest/userguide/using-service-linked-roles.html#slr-permissions) + // * Using service-linked roles for Systems Manager (https://docs.aws.amazon.com/systems-manager/latest/userguide/using-service-linked-roles.html#slr-permissions) // - // * Should I Use a Service-Linked Role or a Custom Service Role to Run Maintenance - // Window Tasks? (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-maintenance-permissions.html#maintenance-window-tasks-service-role) + // * Should I use a service-linked role or a custom service role to run maintenance + // window tasks? (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-maintenance-permissions.html#maintenance-window-tasks-service-role) ServiceRoleArn *string `type:"string"` // The targets (either instances or tags) to modify. Instances are specified @@ -43747,6 +46203,14 @@ type UpdateMaintenanceWindowTaskInput struct { // The parameters that the task should use during execution. Populate only the // fields that match the task type. All other fields should be empty. + // + // When you update a maintenance window task that has options specified in TaskInvocationParameters, + // you must provide again all the TaskInvocationParameters values that you want + // to retain. The values you do not specify again are removed. For example, + // suppose that when you registered a Run Command task, you specified TaskInvocationParameters + // values for Comment, NotificationConfig, and OutputS3BucketName. If you update + // the maintenance window task and specify only a different OutputS3BucketName + // value, the values for Comment and NotificationConfig are removed. TaskInvocationParameters *MaintenanceWindowTaskInvocationParameters `type:"structure"` // The parameters to modify. @@ -44169,7 +46633,7 @@ type UpdateOpsItemInput struct { // Use the /aws/resources key in OperationalData to specify a related resource // in the request. Use the /aws/automations key in OperationalData to associate // an Automation runbook with the OpsItem. To view AWS CLI example commands - // that use these keys, see Creating OpsItems Manually (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems) + // that use these keys, see Creating OpsItems manually (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html#OpsCenter-manually-create-OpsItems) // in the AWS Systems Manager User Guide. OperationalData map[string]*OpsItemDataValue `type:"map"` @@ -44193,7 +46657,7 @@ type UpdateOpsItemInput struct { Severity *string `min:"1" type:"string"` // The OpsItem status. Status can be Open, In Progress, or Resolved. For more - // information, see Editing OpsItem Details (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems-editing-details.html) + // information, see Editing OpsItem details (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems.html#OpsCenter-working-with-OpsItems-editing-details) // in the AWS Systems Manager User Guide. Status *string `type:"string" enum:"OpsItemStatus"` @@ -44339,8 +46803,8 @@ type UpdatePatchBaselineInput struct { // A list of explicitly approved patches for the baseline. // // For information about accepted formats for lists of approved patches and - // rejected patches, see Package Name Formats for Approved and Rejected Patch - // Lists (https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html) + // rejected patches, see About package name formats for approved and rejected + // patch lists (https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html) // in the AWS Systems Manager User Guide. ApprovedPatches []*string `type:"list"` @@ -44369,8 +46833,8 @@ type UpdatePatchBaselineInput struct { // A list of explicitly rejected patches for the baseline. // // For information about accepted formats for lists of approved patches and - // rejected patches, see Package Name Formats for Approved and Rejected Patch - // Lists (https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html) + // rejected patches, see About package name formats for approved and rejected + // patch lists (https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-approved-rejected-package-name-formats.html) // in the AWS Systems Manager User Guide. RejectedPatches []*string `type:"list"` @@ -44682,10 +47146,7 @@ type UpdateResourceDataSyncInput struct { // SyncSource is a required field SyncSource *ResourceDataSyncSource `type:"structure" required:"true"` - // The type of resource data sync. If SyncType is SyncToDestination, then the - // resource data sync synchronizes data to an Amazon S3 bucket. If the SyncType - // is SyncFromSource then the resource data sync synchronizes data from AWS - // Organizations or from multiple AWS Regions. + // The type of resource data sync. The supported SyncType is SyncFromSource. // // SyncType is a required field SyncType *string `min:"1" type:"string" required:"true"` @@ -44767,12 +47228,30 @@ func (s UpdateResourceDataSyncOutput) GoString() string { type UpdateServiceSettingInput struct { _ struct{} `type:"structure"` - // The ID of the service setting to update. + // The Amazon Resource Name (ARN) of the service setting to reset. For example, + // arn:aws:ssm:us-east-1:111122223333:servicesetting/ssm/parameter-store/high-throughput-enabled. + // The setting ID can be one of the following. + // + // * /ssm/parameter-store/default-parameter-tier + // + // * /ssm/parameter-store/high-throughput-enabled + // + // * /ssm/managed-instance/activation-tier // // SettingId is a required field SettingId *string `min:"1" type:"string" required:"true"` - // The new value to specify for the service setting. + // The new value to specify for the service setting. For the /ssm/parameter-store/default-parameter-tier + // setting ID, the setting value can be one of the following. + // + // * Standard + // + // * Advanced + // + // * Intelligent-Tiering + // + // For the /ssm/parameter-store/high-throughput-enabled, and /ssm/managed-instance/activation-tier + // setting IDs, the setting value can be true or false. // // SettingValue is a required field SettingValue *string `min:"1" type:"string" required:"true"` @@ -44854,6 +47333,17 @@ const ( AssociationComplianceSeverityUnspecified = "UNSPECIFIED" ) +// AssociationComplianceSeverity_Values returns all elements of the AssociationComplianceSeverity enum +func AssociationComplianceSeverity_Values() []string { + return []string{ + AssociationComplianceSeverityCritical, + AssociationComplianceSeverityHigh, + AssociationComplianceSeverityMedium, + AssociationComplianceSeverityLow, + AssociationComplianceSeverityUnspecified, + } +} + const ( // AssociationExecutionFilterKeyExecutionId is a AssociationExecutionFilterKey enum value AssociationExecutionFilterKeyExecutionId = "ExecutionId" @@ -44865,6 +47355,15 @@ const ( AssociationExecutionFilterKeyCreatedTime = "CreatedTime" ) +// AssociationExecutionFilterKey_Values returns all elements of the AssociationExecutionFilterKey enum +func AssociationExecutionFilterKey_Values() []string { + return []string{ + AssociationExecutionFilterKeyExecutionId, + AssociationExecutionFilterKeyStatus, + AssociationExecutionFilterKeyCreatedTime, + } +} + const ( // AssociationExecutionTargetsFilterKeyStatus is a AssociationExecutionTargetsFilterKey enum value AssociationExecutionTargetsFilterKeyStatus = "Status" @@ -44876,6 +47375,15 @@ const ( AssociationExecutionTargetsFilterKeyResourceType = "ResourceType" ) +// AssociationExecutionTargetsFilterKey_Values returns all elements of the AssociationExecutionTargetsFilterKey enum +func AssociationExecutionTargetsFilterKey_Values() []string { + return []string{ + AssociationExecutionTargetsFilterKeyStatus, + AssociationExecutionTargetsFilterKeyResourceId, + AssociationExecutionTargetsFilterKeyResourceType, + } +} + const ( // AssociationFilterKeyInstanceId is a AssociationFilterKey enum value AssociationFilterKeyInstanceId = "InstanceId" @@ -44897,8 +47405,25 @@ const ( // AssociationFilterKeyAssociationName is a AssociationFilterKey enum value AssociationFilterKeyAssociationName = "AssociationName" + + // AssociationFilterKeyResourceGroupName is a AssociationFilterKey enum value + AssociationFilterKeyResourceGroupName = "ResourceGroupName" ) +// AssociationFilterKey_Values returns all elements of the AssociationFilterKey enum +func AssociationFilterKey_Values() []string { + return []string{ + AssociationFilterKeyInstanceId, + AssociationFilterKeyName, + AssociationFilterKeyAssociationId, + AssociationFilterKeyAssociationStatusName, + AssociationFilterKeyLastExecutedBefore, + AssociationFilterKeyLastExecutedAfter, + AssociationFilterKeyAssociationName, + AssociationFilterKeyResourceGroupName, + } +} + const ( // AssociationFilterOperatorTypeEqual is a AssociationFilterOperatorType enum value AssociationFilterOperatorTypeEqual = "EQUAL" @@ -44910,6 +47435,15 @@ const ( AssociationFilterOperatorTypeGreaterThan = "GREATER_THAN" ) +// AssociationFilterOperatorType_Values returns all elements of the AssociationFilterOperatorType enum +func AssociationFilterOperatorType_Values() []string { + return []string{ + AssociationFilterOperatorTypeEqual, + AssociationFilterOperatorTypeLessThan, + AssociationFilterOperatorTypeGreaterThan, + } +} + const ( // AssociationStatusNamePending is a AssociationStatusName enum value AssociationStatusNamePending = "Pending" @@ -44921,11 +47455,43 @@ const ( AssociationStatusNameFailed = "Failed" ) +// AssociationStatusName_Values returns all elements of the AssociationStatusName enum +func AssociationStatusName_Values() []string { + return []string{ + AssociationStatusNamePending, + AssociationStatusNameSuccess, + AssociationStatusNameFailed, + } +} + +const ( + // AssociationSyncComplianceAuto is a AssociationSyncCompliance enum value + AssociationSyncComplianceAuto = "AUTO" + + // AssociationSyncComplianceManual is a AssociationSyncCompliance enum value + AssociationSyncComplianceManual = "MANUAL" +) + +// AssociationSyncCompliance_Values returns all elements of the AssociationSyncCompliance enum +func AssociationSyncCompliance_Values() []string { + return []string{ + AssociationSyncComplianceAuto, + AssociationSyncComplianceManual, + } +} + const ( // AttachmentHashTypeSha256 is a AttachmentHashType enum value AttachmentHashTypeSha256 = "Sha256" ) +// AttachmentHashType_Values returns all elements of the AttachmentHashType enum +func AttachmentHashType_Values() []string { + return []string{ + AttachmentHashTypeSha256, + } +} + const ( // AttachmentsSourceKeySourceUrl is a AttachmentsSourceKey enum value AttachmentsSourceKeySourceUrl = "SourceUrl" @@ -44937,6 +47503,15 @@ const ( AttachmentsSourceKeyAttachmentReference = "AttachmentReference" ) +// AttachmentsSourceKey_Values returns all elements of the AttachmentsSourceKey enum +func AttachmentsSourceKey_Values() []string { + return []string{ + AttachmentsSourceKeySourceUrl, + AttachmentsSourceKeyS3fileUrl, + AttachmentsSourceKeyAttachmentReference, + } +} + const ( // AutomationExecutionFilterKeyDocumentNamePrefix is a AutomationExecutionFilterKey enum value AutomationExecutionFilterKeyDocumentNamePrefix = "DocumentNamePrefix" @@ -44966,6 +47541,21 @@ const ( AutomationExecutionFilterKeyTagKey = "TagKey" ) +// AutomationExecutionFilterKey_Values returns all elements of the AutomationExecutionFilterKey enum +func AutomationExecutionFilterKey_Values() []string { + return []string{ + AutomationExecutionFilterKeyDocumentNamePrefix, + AutomationExecutionFilterKeyExecutionStatus, + AutomationExecutionFilterKeyExecutionId, + AutomationExecutionFilterKeyParentExecutionId, + AutomationExecutionFilterKeyCurrentAction, + AutomationExecutionFilterKeyStartTimeBefore, + AutomationExecutionFilterKeyStartTimeAfter, + AutomationExecutionFilterKeyAutomationType, + AutomationExecutionFilterKeyTagKey, + } +} + const ( // AutomationExecutionStatusPending is a AutomationExecutionStatus enum value AutomationExecutionStatusPending = "Pending" @@ -44992,6 +47582,20 @@ const ( AutomationExecutionStatusFailed = "Failed" ) +// AutomationExecutionStatus_Values returns all elements of the AutomationExecutionStatus enum +func AutomationExecutionStatus_Values() []string { + return []string{ + AutomationExecutionStatusPending, + AutomationExecutionStatusInProgress, + AutomationExecutionStatusWaiting, + AutomationExecutionStatusSuccess, + AutomationExecutionStatusTimedOut, + AutomationExecutionStatusCancelling, + AutomationExecutionStatusCancelled, + AutomationExecutionStatusFailed, + } +} + const ( // AutomationTypeCrossAccount is a AutomationType enum value AutomationTypeCrossAccount = "CrossAccount" @@ -45000,6 +47604,14 @@ const ( AutomationTypeLocal = "Local" ) +// AutomationType_Values returns all elements of the AutomationType enum +func AutomationType_Values() []string { + return []string{ + AutomationTypeCrossAccount, + AutomationTypeLocal, + } +} + const ( // CalendarStateOpen is a CalendarState enum value CalendarStateOpen = "OPEN" @@ -45008,6 +47620,14 @@ const ( CalendarStateClosed = "CLOSED" ) +// CalendarState_Values returns all elements of the CalendarState enum +func CalendarState_Values() []string { + return []string{ + CalendarStateOpen, + CalendarStateClosed, + } +} + const ( // CommandFilterKeyInvokedAfter is a CommandFilterKey enum value CommandFilterKeyInvokedAfter = "InvokedAfter" @@ -45025,6 +47645,17 @@ const ( CommandFilterKeyDocumentName = "DocumentName" ) +// CommandFilterKey_Values returns all elements of the CommandFilterKey enum +func CommandFilterKey_Values() []string { + return []string{ + CommandFilterKeyInvokedAfter, + CommandFilterKeyInvokedBefore, + CommandFilterKeyStatus, + CommandFilterKeyExecutionStage, + CommandFilterKeyDocumentName, + } +} + const ( // CommandInvocationStatusPending is a CommandInvocationStatus enum value CommandInvocationStatusPending = "Pending" @@ -45051,6 +47682,20 @@ const ( CommandInvocationStatusCancelling = "Cancelling" ) +// CommandInvocationStatus_Values returns all elements of the CommandInvocationStatus enum +func CommandInvocationStatus_Values() []string { + return []string{ + CommandInvocationStatusPending, + CommandInvocationStatusInProgress, + CommandInvocationStatusDelayed, + CommandInvocationStatusSuccess, + CommandInvocationStatusCancelled, + CommandInvocationStatusTimedOut, + CommandInvocationStatusFailed, + CommandInvocationStatusCancelling, + } +} + const ( // CommandPluginStatusPending is a CommandPluginStatus enum value CommandPluginStatusPending = "Pending" @@ -45071,6 +47716,18 @@ const ( CommandPluginStatusFailed = "Failed" ) +// CommandPluginStatus_Values returns all elements of the CommandPluginStatus enum +func CommandPluginStatus_Values() []string { + return []string{ + CommandPluginStatusPending, + CommandPluginStatusInProgress, + CommandPluginStatusSuccess, + CommandPluginStatusTimedOut, + CommandPluginStatusCancelled, + CommandPluginStatusFailed, + } +} + const ( // CommandStatusPending is a CommandStatus enum value CommandStatusPending = "Pending" @@ -45094,6 +47751,19 @@ const ( CommandStatusCancelling = "Cancelling" ) +// CommandStatus_Values returns all elements of the CommandStatus enum +func CommandStatus_Values() []string { + return []string{ + CommandStatusPending, + CommandStatusInProgress, + CommandStatusSuccess, + CommandStatusCancelled, + CommandStatusFailed, + CommandStatusTimedOut, + CommandStatusCancelling, + } +} + const ( // ComplianceQueryOperatorTypeEqual is a ComplianceQueryOperatorType enum value ComplianceQueryOperatorTypeEqual = "EQUAL" @@ -45111,6 +47781,17 @@ const ( ComplianceQueryOperatorTypeGreaterThan = "GREATER_THAN" ) +// ComplianceQueryOperatorType_Values returns all elements of the ComplianceQueryOperatorType enum +func ComplianceQueryOperatorType_Values() []string { + return []string{ + ComplianceQueryOperatorTypeEqual, + ComplianceQueryOperatorTypeNotEqual, + ComplianceQueryOperatorTypeBeginWith, + ComplianceQueryOperatorTypeLessThan, + ComplianceQueryOperatorTypeGreaterThan, + } +} + const ( // ComplianceSeverityCritical is a ComplianceSeverity enum value ComplianceSeverityCritical = "CRITICAL" @@ -45131,6 +47812,18 @@ const ( ComplianceSeverityUnspecified = "UNSPECIFIED" ) +// ComplianceSeverity_Values returns all elements of the ComplianceSeverity enum +func ComplianceSeverity_Values() []string { + return []string{ + ComplianceSeverityCritical, + ComplianceSeverityHigh, + ComplianceSeverityMedium, + ComplianceSeverityLow, + ComplianceSeverityInformational, + ComplianceSeverityUnspecified, + } +} + const ( // ComplianceStatusCompliant is a ComplianceStatus enum value ComplianceStatusCompliant = "COMPLIANT" @@ -45139,6 +47832,30 @@ const ( ComplianceStatusNonCompliant = "NON_COMPLIANT" ) +// ComplianceStatus_Values returns all elements of the ComplianceStatus enum +func ComplianceStatus_Values() []string { + return []string{ + ComplianceStatusCompliant, + ComplianceStatusNonCompliant, + } +} + +const ( + // ComplianceUploadTypeComplete is a ComplianceUploadType enum value + ComplianceUploadTypeComplete = "COMPLETE" + + // ComplianceUploadTypePartial is a ComplianceUploadType enum value + ComplianceUploadTypePartial = "PARTIAL" +) + +// ComplianceUploadType_Values returns all elements of the ComplianceUploadType enum +func ComplianceUploadType_Values() []string { + return []string{ + ComplianceUploadTypeComplete, + ComplianceUploadTypePartial, + } +} + const ( // ConnectionStatusConnected is a ConnectionStatus enum value ConnectionStatusConnected = "Connected" @@ -45147,6 +47864,14 @@ const ( ConnectionStatusNotConnected = "NotConnected" ) +// ConnectionStatus_Values returns all elements of the ConnectionStatus enum +func ConnectionStatus_Values() []string { + return []string{ + ConnectionStatusConnected, + ConnectionStatusNotConnected, + } +} + const ( // DescribeActivationsFilterKeysActivationIds is a DescribeActivationsFilterKeys enum value DescribeActivationsFilterKeysActivationIds = "ActivationIds" @@ -45158,6 +47883,15 @@ const ( DescribeActivationsFilterKeysIamRole = "IamRole" ) +// DescribeActivationsFilterKeys_Values returns all elements of the DescribeActivationsFilterKeys enum +func DescribeActivationsFilterKeys_Values() []string { + return []string{ + DescribeActivationsFilterKeysActivationIds, + DescribeActivationsFilterKeysDefaultInstanceName, + DescribeActivationsFilterKeysIamRole, + } +} + const ( // DocumentFilterKeyName is a DocumentFilterKey enum value DocumentFilterKeyName = "Name" @@ -45172,6 +47906,16 @@ const ( DocumentFilterKeyDocumentType = "DocumentType" ) +// DocumentFilterKey_Values returns all elements of the DocumentFilterKey enum +func DocumentFilterKey_Values() []string { + return []string{ + DocumentFilterKeyName, + DocumentFilterKeyOwner, + DocumentFilterKeyPlatformTypes, + DocumentFilterKeyDocumentType, + } +} + const ( // DocumentFormatYaml is a DocumentFormat enum value DocumentFormatYaml = "YAML" @@ -45183,6 +47927,15 @@ const ( DocumentFormatText = "TEXT" ) +// DocumentFormat_Values returns all elements of the DocumentFormat enum +func DocumentFormat_Values() []string { + return []string{ + DocumentFormatYaml, + DocumentFormatJson, + DocumentFormatText, + } +} + const ( // DocumentHashTypeSha256 is a DocumentHashType enum value DocumentHashTypeSha256 = "Sha256" @@ -45191,6 +47944,14 @@ const ( DocumentHashTypeSha1 = "Sha1" ) +// DocumentHashType_Values returns all elements of the DocumentHashType enum +func DocumentHashType_Values() []string { + return []string{ + DocumentHashTypeSha256, + DocumentHashTypeSha1, + } +} + const ( // DocumentParameterTypeString is a DocumentParameterType enum value DocumentParameterTypeString = "String" @@ -45199,11 +47960,26 @@ const ( DocumentParameterTypeStringList = "StringList" ) +// DocumentParameterType_Values returns all elements of the DocumentParameterType enum +func DocumentParameterType_Values() []string { + return []string{ + DocumentParameterTypeString, + DocumentParameterTypeStringList, + } +} + const ( // DocumentPermissionTypeShare is a DocumentPermissionType enum value DocumentPermissionTypeShare = "Share" ) +// DocumentPermissionType_Values returns all elements of the DocumentPermissionType enum +func DocumentPermissionType_Values() []string { + return []string{ + DocumentPermissionTypeShare, + } +} + // The status of a document. const ( // DocumentStatusCreating is a DocumentStatus enum value @@ -45222,6 +47998,17 @@ const ( DocumentStatusFailed = "Failed" ) +// DocumentStatus_Values returns all elements of the DocumentStatus enum +func DocumentStatus_Values() []string { + return []string{ + DocumentStatusCreating, + DocumentStatusActive, + DocumentStatusUpdating, + DocumentStatusDeleting, + DocumentStatusFailed, + } +} + const ( // DocumentTypeCommand is a DocumentType enum value DocumentTypeCommand = "Command" @@ -45251,6 +48038,21 @@ const ( DocumentTypeChangeCalendar = "ChangeCalendar" ) +// DocumentType_Values returns all elements of the DocumentType enum +func DocumentType_Values() []string { + return []string{ + DocumentTypeCommand, + DocumentTypePolicy, + DocumentTypeAutomation, + DocumentTypeSession, + DocumentTypePackage, + DocumentTypeApplicationConfiguration, + DocumentTypeApplicationConfigurationSchema, + DocumentTypeDeploymentStrategy, + DocumentTypeChangeCalendar, + } +} + const ( // ExecutionModeAuto is a ExecutionMode enum value ExecutionModeAuto = "Auto" @@ -45259,6 +48061,14 @@ const ( ExecutionModeInteractive = "Interactive" ) +// ExecutionMode_Values returns all elements of the ExecutionMode enum +func ExecutionMode_Values() []string { + return []string{ + ExecutionModeAuto, + ExecutionModeInteractive, + } +} + const ( // FaultClient is a Fault enum value FaultClient = "Client" @@ -45270,6 +48080,15 @@ const ( FaultUnknown = "Unknown" ) +// Fault_Values returns all elements of the Fault enum +func Fault_Values() []string { + return []string{ + FaultClient, + FaultServer, + FaultUnknown, + } +} + const ( // InstanceInformationFilterKeyInstanceIds is a InstanceInformationFilterKey enum value InstanceInformationFilterKeyInstanceIds = "InstanceIds" @@ -45296,6 +48115,20 @@ const ( InstanceInformationFilterKeyAssociationStatus = "AssociationStatus" ) +// InstanceInformationFilterKey_Values returns all elements of the InstanceInformationFilterKey enum +func InstanceInformationFilterKey_Values() []string { + return []string{ + InstanceInformationFilterKeyInstanceIds, + InstanceInformationFilterKeyAgentVersion, + InstanceInformationFilterKeyPingStatus, + InstanceInformationFilterKeyPlatformTypes, + InstanceInformationFilterKeyActivationIds, + InstanceInformationFilterKeyIamRole, + InstanceInformationFilterKeyResourceType, + InstanceInformationFilterKeyAssociationStatus, + } +} + const ( // InstancePatchStateOperatorTypeEqual is a InstancePatchStateOperatorType enum value InstancePatchStateOperatorTypeEqual = "Equal" @@ -45310,6 +48143,16 @@ const ( InstancePatchStateOperatorTypeGreaterThan = "GreaterThan" ) +// InstancePatchStateOperatorType_Values returns all elements of the InstancePatchStateOperatorType enum +func InstancePatchStateOperatorType_Values() []string { + return []string{ + InstancePatchStateOperatorTypeEqual, + InstancePatchStateOperatorTypeNotEqual, + InstancePatchStateOperatorTypeLessThan, + InstancePatchStateOperatorTypeGreaterThan, + } +} + const ( // InventoryAttributeDataTypeString is a InventoryAttributeDataType enum value InventoryAttributeDataTypeString = "string" @@ -45318,6 +48161,14 @@ const ( InventoryAttributeDataTypeNumber = "number" ) +// InventoryAttributeDataType_Values returns all elements of the InventoryAttributeDataType enum +func InventoryAttributeDataType_Values() []string { + return []string{ + InventoryAttributeDataTypeString, + InventoryAttributeDataTypeNumber, + } +} + const ( // InventoryDeletionStatusInProgress is a InventoryDeletionStatus enum value InventoryDeletionStatusInProgress = "InProgress" @@ -45326,6 +48177,14 @@ const ( InventoryDeletionStatusComplete = "Complete" ) +// InventoryDeletionStatus_Values returns all elements of the InventoryDeletionStatus enum +func InventoryDeletionStatus_Values() []string { + return []string{ + InventoryDeletionStatusInProgress, + InventoryDeletionStatusComplete, + } +} + const ( // InventoryQueryOperatorTypeEqual is a InventoryQueryOperatorType enum value InventoryQueryOperatorTypeEqual = "Equal" @@ -45346,6 +48205,18 @@ const ( InventoryQueryOperatorTypeExists = "Exists" ) +// InventoryQueryOperatorType_Values returns all elements of the InventoryQueryOperatorType enum +func InventoryQueryOperatorType_Values() []string { + return []string{ + InventoryQueryOperatorTypeEqual, + InventoryQueryOperatorTypeNotEqual, + InventoryQueryOperatorTypeBeginWith, + InventoryQueryOperatorTypeLessThan, + InventoryQueryOperatorTypeGreaterThan, + InventoryQueryOperatorTypeExists, + } +} + const ( // InventorySchemaDeleteOptionDisableSchema is a InventorySchemaDeleteOption enum value InventorySchemaDeleteOptionDisableSchema = "DisableSchema" @@ -45354,6 +48225,14 @@ const ( InventorySchemaDeleteOptionDeleteSchema = "DeleteSchema" ) +// InventorySchemaDeleteOption_Values returns all elements of the InventorySchemaDeleteOption enum +func InventorySchemaDeleteOption_Values() []string { + return []string{ + InventorySchemaDeleteOptionDisableSchema, + InventorySchemaDeleteOptionDeleteSchema, + } +} + const ( // LastResourceDataSyncStatusSuccessful is a LastResourceDataSyncStatus enum value LastResourceDataSyncStatusSuccessful = "Successful" @@ -45365,6 +48244,15 @@ const ( LastResourceDataSyncStatusInProgress = "InProgress" ) +// LastResourceDataSyncStatus_Values returns all elements of the LastResourceDataSyncStatus enum +func LastResourceDataSyncStatus_Values() []string { + return []string{ + LastResourceDataSyncStatusSuccessful, + LastResourceDataSyncStatusFailed, + LastResourceDataSyncStatusInProgress, + } +} + const ( // MaintenanceWindowExecutionStatusPending is a MaintenanceWindowExecutionStatus enum value MaintenanceWindowExecutionStatusPending = "PENDING" @@ -45391,6 +48279,20 @@ const ( MaintenanceWindowExecutionStatusSkippedOverlapping = "SKIPPED_OVERLAPPING" ) +// MaintenanceWindowExecutionStatus_Values returns all elements of the MaintenanceWindowExecutionStatus enum +func MaintenanceWindowExecutionStatus_Values() []string { + return []string{ + MaintenanceWindowExecutionStatusPending, + MaintenanceWindowExecutionStatusInProgress, + MaintenanceWindowExecutionStatusSuccess, + MaintenanceWindowExecutionStatusFailed, + MaintenanceWindowExecutionStatusTimedOut, + MaintenanceWindowExecutionStatusCancelling, + MaintenanceWindowExecutionStatusCancelled, + MaintenanceWindowExecutionStatusSkippedOverlapping, + } +} + const ( // MaintenanceWindowResourceTypeInstance is a MaintenanceWindowResourceType enum value MaintenanceWindowResourceTypeInstance = "INSTANCE" @@ -45399,6 +48301,14 @@ const ( MaintenanceWindowResourceTypeResourceGroup = "RESOURCE_GROUP" ) +// MaintenanceWindowResourceType_Values returns all elements of the MaintenanceWindowResourceType enum +func MaintenanceWindowResourceType_Values() []string { + return []string{ + MaintenanceWindowResourceTypeInstance, + MaintenanceWindowResourceTypeResourceGroup, + } +} + const ( // MaintenanceWindowTaskTypeRunCommand is a MaintenanceWindowTaskType enum value MaintenanceWindowTaskTypeRunCommand = "RUN_COMMAND" @@ -45413,6 +48323,16 @@ const ( MaintenanceWindowTaskTypeLambda = "LAMBDA" ) +// MaintenanceWindowTaskType_Values returns all elements of the MaintenanceWindowTaskType enum +func MaintenanceWindowTaskType_Values() []string { + return []string{ + MaintenanceWindowTaskTypeRunCommand, + MaintenanceWindowTaskTypeAutomation, + MaintenanceWindowTaskTypeStepFunctions, + MaintenanceWindowTaskTypeLambda, + } +} + const ( // NotificationEventAll is a NotificationEvent enum value NotificationEventAll = "All" @@ -45433,6 +48353,18 @@ const ( NotificationEventFailed = "Failed" ) +// NotificationEvent_Values returns all elements of the NotificationEvent enum +func NotificationEvent_Values() []string { + return []string{ + NotificationEventAll, + NotificationEventInProgress, + NotificationEventSuccess, + NotificationEventTimedOut, + NotificationEventCancelled, + NotificationEventFailed, + } +} + const ( // NotificationTypeCommand is a NotificationType enum value NotificationTypeCommand = "Command" @@ -45441,6 +48373,14 @@ const ( NotificationTypeInvocation = "Invocation" ) +// NotificationType_Values returns all elements of the NotificationType enum +func NotificationType_Values() []string { + return []string{ + NotificationTypeCommand, + NotificationTypeInvocation, + } +} + const ( // OperatingSystemWindows is a OperatingSystem enum value OperatingSystemWindows = "WINDOWS" @@ -45462,8 +48402,29 @@ const ( // OperatingSystemCentos is a OperatingSystem enum value OperatingSystemCentos = "CENTOS" + + // OperatingSystemOracleLinux is a OperatingSystem enum value + OperatingSystemOracleLinux = "ORACLE_LINUX" + + // OperatingSystemDebian is a OperatingSystem enum value + OperatingSystemDebian = "DEBIAN" ) +// OperatingSystem_Values returns all elements of the OperatingSystem enum +func OperatingSystem_Values() []string { + return []string{ + OperatingSystemWindows, + OperatingSystemAmazonLinux, + OperatingSystemAmazonLinux2, + OperatingSystemUbuntu, + OperatingSystemRedhatEnterpriseLinux, + OperatingSystemSuse, + OperatingSystemCentos, + OperatingSystemOracleLinux, + OperatingSystemDebian, + } +} + const ( // OpsFilterOperatorTypeEqual is a OpsFilterOperatorType enum value OpsFilterOperatorTypeEqual = "Equal" @@ -45484,6 +48445,18 @@ const ( OpsFilterOperatorTypeExists = "Exists" ) +// OpsFilterOperatorType_Values returns all elements of the OpsFilterOperatorType enum +func OpsFilterOperatorType_Values() []string { + return []string{ + OpsFilterOperatorTypeEqual, + OpsFilterOperatorTypeNotEqual, + OpsFilterOperatorTypeBeginWith, + OpsFilterOperatorTypeLessThan, + OpsFilterOperatorTypeGreaterThan, + OpsFilterOperatorTypeExists, + } +} + const ( // OpsItemDataTypeSearchableString is a OpsItemDataType enum value OpsItemDataTypeSearchableString = "SearchableString" @@ -45492,6 +48465,14 @@ const ( OpsItemDataTypeString = "String" ) +// OpsItemDataType_Values returns all elements of the OpsItemDataType enum +func OpsItemDataType_Values() []string { + return []string{ + OpsItemDataTypeSearchableString, + OpsItemDataTypeString, + } +} + const ( // OpsItemFilterKeyStatus is a OpsItemFilterKey enum value OpsItemFilterKeyStatus = "Status" @@ -45539,6 +48520,27 @@ const ( OpsItemFilterKeySeverity = "Severity" ) +// OpsItemFilterKey_Values returns all elements of the OpsItemFilterKey enum +func OpsItemFilterKey_Values() []string { + return []string{ + OpsItemFilterKeyStatus, + OpsItemFilterKeyCreatedBy, + OpsItemFilterKeySource, + OpsItemFilterKeyPriority, + OpsItemFilterKeyTitle, + OpsItemFilterKeyOpsItemId, + OpsItemFilterKeyCreatedTime, + OpsItemFilterKeyLastModifiedTime, + OpsItemFilterKeyOperationalData, + OpsItemFilterKeyOperationalDataKey, + OpsItemFilterKeyOperationalDataValue, + OpsItemFilterKeyResourceId, + OpsItemFilterKeyAutomationId, + OpsItemFilterKeyCategory, + OpsItemFilterKeySeverity, + } +} + const ( // OpsItemFilterOperatorEqual is a OpsItemFilterOperator enum value OpsItemFilterOperatorEqual = "Equal" @@ -45553,6 +48555,16 @@ const ( OpsItemFilterOperatorLessThan = "LessThan" ) +// OpsItemFilterOperator_Values returns all elements of the OpsItemFilterOperator enum +func OpsItemFilterOperator_Values() []string { + return []string{ + OpsItemFilterOperatorEqual, + OpsItemFilterOperatorContains, + OpsItemFilterOperatorGreaterThan, + OpsItemFilterOperatorLessThan, + } +} + const ( // OpsItemStatusOpen is a OpsItemStatus enum value OpsItemStatusOpen = "Open" @@ -45564,6 +48576,15 @@ const ( OpsItemStatusResolved = "Resolved" ) +// OpsItemStatus_Values returns all elements of the OpsItemStatus enum +func OpsItemStatus_Values() []string { + return []string{ + OpsItemStatusOpen, + OpsItemStatusInProgress, + OpsItemStatusResolved, + } +} + const ( // ParameterTierStandard is a ParameterTier enum value ParameterTierStandard = "Standard" @@ -45575,6 +48596,15 @@ const ( ParameterTierIntelligentTiering = "Intelligent-Tiering" ) +// ParameterTier_Values returns all elements of the ParameterTier enum +func ParameterTier_Values() []string { + return []string{ + ParameterTierStandard, + ParameterTierAdvanced, + ParameterTierIntelligentTiering, + } +} + const ( // ParameterTypeString is a ParameterType enum value ParameterTypeString = "String" @@ -45586,6 +48616,15 @@ const ( ParameterTypeSecureString = "SecureString" ) +// ParameterType_Values returns all elements of the ParameterType enum +func ParameterType_Values() []string { + return []string{ + ParameterTypeString, + ParameterTypeStringList, + ParameterTypeSecureString, + } +} + const ( // ParametersFilterKeyName is a ParametersFilterKey enum value ParametersFilterKeyName = "Name" @@ -45597,6 +48636,15 @@ const ( ParametersFilterKeyKeyId = "KeyId" ) +// ParametersFilterKey_Values returns all elements of the ParametersFilterKey enum +func ParametersFilterKey_Values() []string { + return []string{ + ParametersFilterKeyName, + ParametersFilterKeyType, + ParametersFilterKeyKeyId, + } +} + const ( // PatchActionAllowAsDependency is a PatchAction enum value PatchActionAllowAsDependency = "ALLOW_AS_DEPENDENCY" @@ -45605,6 +48653,14 @@ const ( PatchActionBlock = "BLOCK" ) +// PatchAction_Values returns all elements of the PatchAction enum +func PatchAction_Values() []string { + return []string{ + PatchActionAllowAsDependency, + PatchActionBlock, + } +} + const ( // PatchComplianceDataStateInstalled is a PatchComplianceDataState enum value PatchComplianceDataStateInstalled = "INSTALLED" @@ -45628,6 +48684,19 @@ const ( PatchComplianceDataStateFailed = "FAILED" ) +// PatchComplianceDataState_Values returns all elements of the PatchComplianceDataState enum +func PatchComplianceDataState_Values() []string { + return []string{ + PatchComplianceDataStateInstalled, + PatchComplianceDataStateInstalledOther, + PatchComplianceDataStateInstalledPendingReboot, + PatchComplianceDataStateInstalledRejected, + PatchComplianceDataStateMissing, + PatchComplianceDataStateNotApplicable, + PatchComplianceDataStateFailed, + } +} + const ( // PatchComplianceLevelCritical is a PatchComplianceLevel enum value PatchComplianceLevelCritical = "CRITICAL" @@ -45648,6 +48717,18 @@ const ( PatchComplianceLevelUnspecified = "UNSPECIFIED" ) +// PatchComplianceLevel_Values returns all elements of the PatchComplianceLevel enum +func PatchComplianceLevel_Values() []string { + return []string{ + PatchComplianceLevelCritical, + PatchComplianceLevelHigh, + PatchComplianceLevelMedium, + PatchComplianceLevelLow, + PatchComplianceLevelInformational, + PatchComplianceLevelUnspecified, + } +} + const ( // PatchDeploymentStatusApproved is a PatchDeploymentStatus enum value PatchDeploymentStatusApproved = "APPROVED" @@ -45662,6 +48743,16 @@ const ( PatchDeploymentStatusExplicitRejected = "EXPLICIT_REJECTED" ) +// PatchDeploymentStatus_Values returns all elements of the PatchDeploymentStatus enum +func PatchDeploymentStatus_Values() []string { + return []string{ + PatchDeploymentStatusApproved, + PatchDeploymentStatusPendingApproval, + PatchDeploymentStatusExplicitApproved, + PatchDeploymentStatusExplicitRejected, + } +} + const ( // PatchFilterKeyPatchSet is a PatchFilterKey enum value PatchFilterKeyPatchSet = "PATCH_SET" @@ -45691,6 +48782,21 @@ const ( PatchFilterKeySeverity = "SEVERITY" ) +// PatchFilterKey_Values returns all elements of the PatchFilterKey enum +func PatchFilterKey_Values() []string { + return []string{ + PatchFilterKeyPatchSet, + PatchFilterKeyProduct, + PatchFilterKeyProductFamily, + PatchFilterKeyClassification, + PatchFilterKeyMsrcSeverity, + PatchFilterKeyPatchId, + PatchFilterKeySection, + PatchFilterKeyPriority, + PatchFilterKeySeverity, + } +} + const ( // PatchOperationTypeScan is a PatchOperationType enum value PatchOperationTypeScan = "Scan" @@ -45699,6 +48805,14 @@ const ( PatchOperationTypeInstall = "Install" ) +// PatchOperationType_Values returns all elements of the PatchOperationType enum +func PatchOperationType_Values() []string { + return []string{ + PatchOperationTypeScan, + PatchOperationTypeInstall, + } +} + const ( // PatchPropertyProduct is a PatchProperty enum value PatchPropertyProduct = "PRODUCT" @@ -45719,6 +48833,18 @@ const ( PatchPropertySeverity = "SEVERITY" ) +// PatchProperty_Values returns all elements of the PatchProperty enum +func PatchProperty_Values() []string { + return []string{ + PatchPropertyProduct, + PatchPropertyProductFamily, + PatchPropertyClassification, + PatchPropertyMsrcSeverity, + PatchPropertyPriority, + PatchPropertySeverity, + } +} + const ( // PatchSetOs is a PatchSet enum value PatchSetOs = "OS" @@ -45727,6 +48853,14 @@ const ( PatchSetApplication = "APPLICATION" ) +// PatchSet_Values returns all elements of the PatchSet enum +func PatchSet_Values() []string { + return []string{ + PatchSetOs, + PatchSetApplication, + } +} + const ( // PingStatusOnline is a PingStatus enum value PingStatusOnline = "Online" @@ -45738,6 +48872,15 @@ const ( PingStatusInactive = "Inactive" ) +// PingStatus_Values returns all elements of the PingStatus enum +func PingStatus_Values() []string { + return []string{ + PingStatusOnline, + PingStatusConnectionLost, + PingStatusInactive, + } +} + const ( // PlatformTypeWindows is a PlatformType enum value PlatformTypeWindows = "Windows" @@ -45746,6 +48889,14 @@ const ( PlatformTypeLinux = "Linux" ) +// PlatformType_Values returns all elements of the PlatformType enum +func PlatformType_Values() []string { + return []string{ + PlatformTypeWindows, + PlatformTypeLinux, + } +} + const ( // RebootOptionRebootIfNeeded is a RebootOption enum value RebootOptionRebootIfNeeded = "RebootIfNeeded" @@ -45754,11 +48905,26 @@ const ( RebootOptionNoReboot = "NoReboot" ) +// RebootOption_Values returns all elements of the RebootOption enum +func RebootOption_Values() []string { + return []string{ + RebootOptionRebootIfNeeded, + RebootOptionNoReboot, + } +} + const ( // ResourceDataSyncS3FormatJsonSerDe is a ResourceDataSyncS3Format enum value ResourceDataSyncS3FormatJsonSerDe = "JsonSerDe" ) +// ResourceDataSyncS3Format_Values returns all elements of the ResourceDataSyncS3Format enum +func ResourceDataSyncS3Format_Values() []string { + return []string{ + ResourceDataSyncS3FormatJsonSerDe, + } +} + const ( // ResourceTypeManagedInstance is a ResourceType enum value ResourceTypeManagedInstance = "ManagedInstance" @@ -45770,6 +48936,15 @@ const ( ResourceTypeEc2instance = "EC2Instance" ) +// ResourceType_Values returns all elements of the ResourceType enum +func ResourceType_Values() []string { + return []string{ + ResourceTypeManagedInstance, + ResourceTypeDocument, + ResourceTypeEc2instance, + } +} + const ( // ResourceTypeForTaggingDocument is a ResourceTypeForTagging enum value ResourceTypeForTaggingDocument = "Document" @@ -45790,6 +48965,18 @@ const ( ResourceTypeForTaggingOpsItem = "OpsItem" ) +// ResourceTypeForTagging_Values returns all elements of the ResourceTypeForTagging enum +func ResourceTypeForTagging_Values() []string { + return []string{ + ResourceTypeForTaggingDocument, + ResourceTypeForTaggingManagedInstance, + ResourceTypeForTaggingMaintenanceWindow, + ResourceTypeForTaggingParameter, + ResourceTypeForTaggingPatchBaseline, + ResourceTypeForTaggingOpsItem, + } +} + const ( // SessionFilterKeyInvokedAfter is a SessionFilterKey enum value SessionFilterKeyInvokedAfter = "InvokedAfter" @@ -45807,6 +48994,17 @@ const ( SessionFilterKeyStatus = "Status" ) +// SessionFilterKey_Values returns all elements of the SessionFilterKey enum +func SessionFilterKey_Values() []string { + return []string{ + SessionFilterKeyInvokedAfter, + SessionFilterKeyInvokedBefore, + SessionFilterKeyTarget, + SessionFilterKeyOwner, + SessionFilterKeyStatus, + } +} + const ( // SessionStateActive is a SessionState enum value SessionStateActive = "Active" @@ -45815,6 +49013,14 @@ const ( SessionStateHistory = "History" ) +// SessionState_Values returns all elements of the SessionState enum +func SessionState_Values() []string { + return []string{ + SessionStateActive, + SessionStateHistory, + } +} + const ( // SessionStatusConnected is a SessionStatus enum value SessionStatusConnected = "Connected" @@ -45835,6 +49041,18 @@ const ( SessionStatusFailed = "Failed" ) +// SessionStatus_Values returns all elements of the SessionStatus enum +func SessionStatus_Values() []string { + return []string{ + SessionStatusConnected, + SessionStatusConnecting, + SessionStatusDisconnected, + SessionStatusTerminated, + SessionStatusTerminating, + SessionStatusFailed, + } +} + const ( // SignalTypeApprove is a SignalType enum value SignalTypeApprove = "Approve" @@ -45852,6 +49070,17 @@ const ( SignalTypeResume = "Resume" ) +// SignalType_Values returns all elements of the SignalType enum +func SignalType_Values() []string { + return []string{ + SignalTypeApprove, + SignalTypeReject, + SignalTypeStartStep, + SignalTypeStopStep, + SignalTypeResume, + } +} + const ( // StepExecutionFilterKeyStartTimeBefore is a StepExecutionFilterKey enum value StepExecutionFilterKeyStartTimeBefore = "StartTimeBefore" @@ -45872,6 +49101,18 @@ const ( StepExecutionFilterKeyAction = "Action" ) +// StepExecutionFilterKey_Values returns all elements of the StepExecutionFilterKey enum +func StepExecutionFilterKey_Values() []string { + return []string{ + StepExecutionFilterKeyStartTimeBefore, + StepExecutionFilterKeyStartTimeAfter, + StepExecutionFilterKeyStepExecutionStatus, + StepExecutionFilterKeyStepExecutionId, + StepExecutionFilterKeyStepName, + StepExecutionFilterKeyAction, + } +} + const ( // StopTypeComplete is a StopType enum value StopTypeComplete = "Complete" @@ -45879,3 +49120,11 @@ const ( // StopTypeCancel is a StopType enum value StopTypeCancel = "Cancel" ) + +// StopType_Values returns all elements of the StopType enum +func StopType_Values() []string { + return []string{ + StopTypeComplete, + StopTypeCancel, + } +} diff --git a/vendor/github.com/aws/aws-sdk-go/service/ssm/doc.go b/vendor/github.com/aws/aws-sdk-go/service/ssm/doc.go index 48d6d3ee3..2fe2457ca 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ssm/doc.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ssm/doc.go @@ -8,19 +8,20 @@ // system (OS) patches, automating the creation of Amazon Machine Images (AMIs), // and configuring operating systems (OSs) and applications at scale. Systems // Manager lets you remotely and securely manage the configuration of your managed -// instances. A managed instance is any Amazon EC2 instance or on-premises machine -// in your hybrid environment that has been configured for Systems Manager. +// instances. A managed instance is any Amazon Elastic Compute Cloud instance +// (EC2 instance), or any on-premises server or virtual machine (VM) in your +// hybrid environment that has been configured for Systems Manager. // // This reference is intended to be used with the AWS Systems Manager User Guide -// (http://docs.aws.amazon.com/systems-manager/latest/userguide/). +// (https://docs.aws.amazon.com/systems-manager/latest/userguide/). // // To get started, verify prerequisites and configure managed instances. For -// more information, see Setting Up AWS Systems Manager (http://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-setting-up.html) +// more information, see Setting up AWS Systems Manager (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-setting-up.html) // in the AWS Systems Manager User Guide. // -// For information about other API actions you can perform on Amazon EC2 instances, -// see the Amazon EC2 API Reference (http://docs.aws.amazon.com/AWSEC2/latest/APIReference/). -// For information about how to use a Query API, see Making API Requests (http://docs.aws.amazon.com/AWSEC2/latest/APIReference/making-api-requests.html). +// For information about other API actions you can perform on EC2 instances, +// see the Amazon EC2 API Reference (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/). +// For information about how to use a Query API, see Making API requests (https://docs.aws.amazon.com/AWSEC2/latest/APIReference/making-api-requests.html). // // See https://docs.aws.amazon.com/goto/WebAPI/ssm-2014-11-06 for more information on this service. // diff --git a/vendor/github.com/aws/aws-sdk-go/service/ssm/errors.go b/vendor/github.com/aws/aws-sdk-go/service/ssm/errors.go index 8e3eb9ba3..0e4b87e50 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ssm/errors.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ssm/errors.go @@ -134,7 +134,7 @@ const ( // window or Patch baseline, doesn't exist. // // For information about resource quotas in Systems Manager, see Systems Manager - // Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) + // service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. ErrCodeDoesNotExistException = "DoesNotExistException" @@ -169,7 +169,7 @@ const ( // "HierarchyLevelLimitExceededException". // // A hierarchy can have a maximum of 15 levels. For more information, see Requirements - // and Constraints for Parameter Names (http://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-parameter-name-constraints.html) + // and constraints for parameter names (https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-parameter-name-constraints.html) // in the AWS Systems Manager User Guide. ErrCodeHierarchyLevelLimitExceededException = "HierarchyLevelLimitExceededException" @@ -489,7 +489,7 @@ const ( // The role name can't contain invalid characters. Also verify that you specified // an IAM role for notifications that includes the required trust policy. For // information about configuring the IAM role for Run Command notifications, - // see Configuring Amazon SNS Notifications for Run Command (http://docs.aws.amazon.com/systems-manager/latest/userguide/rc-sns-notifications.html) + // see Configuring Amazon SNS Notifications for Run Command (https://docs.aws.amazon.com/systems-manager/latest/userguide/rc-sns-notifications.html) // in the AWS Systems Manager User Guide. ErrCodeInvalidRole = "InvalidRole" @@ -503,7 +503,7 @@ const ( // "InvalidTarget". // // The target is not valid or does not exist. It might not be configured for - // EC2 Systems Manager or you might not have permission to perform the operation. + // Systems Manager or you might not have permission to perform the operation. ErrCodeInvalidTarget = "InvalidTarget" // ErrCodeInvalidTypeNameException for service response error code @@ -560,7 +560,7 @@ const ( // "OpsItemLimitExceededException". // // The request caused OpsItems to exceed one or more quotas. For information - // about OpsItem quotas, see What are the resource limits for OpsCenter? (http://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-learn-more.html#OpsCenter-learn-more-limits). + // about OpsItem quotas, see What are the resource limits for OpsCenter? (https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-learn-more.html#OpsCenter-learn-more-limits). ErrCodeOpsItemLimitExceededException = "OpsItemLimitExceededException" // ErrCodeOpsItemNotFoundException for service response error code @@ -665,7 +665,7 @@ const ( // For example, too many maintenance windows or patch baselines have been created. // // For information about resource quotas in Systems Manager, see Systems Manager - // Service Quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) + // service quotas (http://docs.aws.amazon.com/general/latest/gr/ssm.html#limits_ssm) // in the AWS General Reference. ErrCodeResourceLimitExceededException = "ResourceLimitExceededException" @@ -699,8 +699,8 @@ const ( // "TargetNotConnected". // // The specified target instance for the session is not fully configured for - // use with Session Manager. For more information, see Getting Started with - // Session Manager (http://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started.html) + // use with Session Manager. For more information, see Getting started with + // Session Manager (https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started.html) // in the AWS Systems Manager User Guide. ErrCodeTargetNotConnected = "TargetNotConnected" @@ -734,10 +734,10 @@ const ( // ErrCodeUnsupportedFeatureRequiredException for service response error code // "UnsupportedFeatureRequiredException". // - // Microsoft application patching is only available on EC2 instances and Advanced - // Instances. To patch Microsoft applications on on-premises servers and VMs, - // you must enable Advanced Instances. For more information, see Using the Advanced-Instances - // Tier (http://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-managedinstances-advanced.html) + // Microsoft application patching is only available on EC2 instances and advanced + // instances. To patch Microsoft applications on on-premises servers and VMs, + // you must enable advanced instances. For more information, see Using the advanced-instances + // tier (https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-managedinstances-advanced.html) // in the AWS Systems Manager User Guide. ErrCodeUnsupportedFeatureRequiredException = "UnsupportedFeatureRequiredException" @@ -761,8 +761,7 @@ const ( // "UnsupportedOperatingSystem". // // The operating systems you specified is not supported, or the operation is - // not supported for the operating system. Valid operating systems include: - // Windows, AmazonLinux, RedhatEnterpriseLinux, and Ubuntu. + // not supported for the operating system. ErrCodeUnsupportedOperatingSystem = "UnsupportedOperatingSystem" // ErrCodeUnsupportedParameterType for service response error code diff --git a/vendor/github.com/aws/aws-sdk-go/service/ssm/ssmiface/interface.go b/vendor/github.com/aws/aws-sdk-go/service/ssm/ssmiface/interface.go index 8469ff527..c21a8a358 100644 --- a/vendor/github.com/aws/aws-sdk-go/service/ssm/ssmiface/interface.go +++ b/vendor/github.com/aws/aws-sdk-go/service/ssm/ssmiface/interface.go @@ -171,22 +171,37 @@ type SSMAPI interface { DescribeAssociationExecutionTargetsWithContext(aws.Context, *ssm.DescribeAssociationExecutionTargetsInput, ...request.Option) (*ssm.DescribeAssociationExecutionTargetsOutput, error) DescribeAssociationExecutionTargetsRequest(*ssm.DescribeAssociationExecutionTargetsInput) (*request.Request, *ssm.DescribeAssociationExecutionTargetsOutput) + DescribeAssociationExecutionTargetsPages(*ssm.DescribeAssociationExecutionTargetsInput, func(*ssm.DescribeAssociationExecutionTargetsOutput, bool) bool) error + DescribeAssociationExecutionTargetsPagesWithContext(aws.Context, *ssm.DescribeAssociationExecutionTargetsInput, func(*ssm.DescribeAssociationExecutionTargetsOutput, bool) bool, ...request.Option) error + DescribeAssociationExecutions(*ssm.DescribeAssociationExecutionsInput) (*ssm.DescribeAssociationExecutionsOutput, error) DescribeAssociationExecutionsWithContext(aws.Context, *ssm.DescribeAssociationExecutionsInput, ...request.Option) (*ssm.DescribeAssociationExecutionsOutput, error) DescribeAssociationExecutionsRequest(*ssm.DescribeAssociationExecutionsInput) (*request.Request, *ssm.DescribeAssociationExecutionsOutput) + DescribeAssociationExecutionsPages(*ssm.DescribeAssociationExecutionsInput, func(*ssm.DescribeAssociationExecutionsOutput, bool) bool) error + DescribeAssociationExecutionsPagesWithContext(aws.Context, *ssm.DescribeAssociationExecutionsInput, func(*ssm.DescribeAssociationExecutionsOutput, bool) bool, ...request.Option) error + DescribeAutomationExecutions(*ssm.DescribeAutomationExecutionsInput) (*ssm.DescribeAutomationExecutionsOutput, error) DescribeAutomationExecutionsWithContext(aws.Context, *ssm.DescribeAutomationExecutionsInput, ...request.Option) (*ssm.DescribeAutomationExecutionsOutput, error) DescribeAutomationExecutionsRequest(*ssm.DescribeAutomationExecutionsInput) (*request.Request, *ssm.DescribeAutomationExecutionsOutput) + DescribeAutomationExecutionsPages(*ssm.DescribeAutomationExecutionsInput, func(*ssm.DescribeAutomationExecutionsOutput, bool) bool) error + DescribeAutomationExecutionsPagesWithContext(aws.Context, *ssm.DescribeAutomationExecutionsInput, func(*ssm.DescribeAutomationExecutionsOutput, bool) bool, ...request.Option) error + DescribeAutomationStepExecutions(*ssm.DescribeAutomationStepExecutionsInput) (*ssm.DescribeAutomationStepExecutionsOutput, error) DescribeAutomationStepExecutionsWithContext(aws.Context, *ssm.DescribeAutomationStepExecutionsInput, ...request.Option) (*ssm.DescribeAutomationStepExecutionsOutput, error) DescribeAutomationStepExecutionsRequest(*ssm.DescribeAutomationStepExecutionsInput) (*request.Request, *ssm.DescribeAutomationStepExecutionsOutput) + DescribeAutomationStepExecutionsPages(*ssm.DescribeAutomationStepExecutionsInput, func(*ssm.DescribeAutomationStepExecutionsOutput, bool) bool) error + DescribeAutomationStepExecutionsPagesWithContext(aws.Context, *ssm.DescribeAutomationStepExecutionsInput, func(*ssm.DescribeAutomationStepExecutionsOutput, bool) bool, ...request.Option) error + DescribeAvailablePatches(*ssm.DescribeAvailablePatchesInput) (*ssm.DescribeAvailablePatchesOutput, error) DescribeAvailablePatchesWithContext(aws.Context, *ssm.DescribeAvailablePatchesInput, ...request.Option) (*ssm.DescribeAvailablePatchesOutput, error) DescribeAvailablePatchesRequest(*ssm.DescribeAvailablePatchesInput) (*request.Request, *ssm.DescribeAvailablePatchesOutput) + DescribeAvailablePatchesPages(*ssm.DescribeAvailablePatchesInput, func(*ssm.DescribeAvailablePatchesOutput, bool) bool) error + DescribeAvailablePatchesPagesWithContext(aws.Context, *ssm.DescribeAvailablePatchesInput, func(*ssm.DescribeAvailablePatchesOutput, bool) bool, ...request.Option) error + DescribeDocument(*ssm.DescribeDocumentInput) (*ssm.DescribeDocumentOutput, error) DescribeDocumentWithContext(aws.Context, *ssm.DescribeDocumentInput, ...request.Option) (*ssm.DescribeDocumentOutput, error) DescribeDocumentRequest(*ssm.DescribeDocumentInput) (*request.Request, *ssm.DescribeDocumentOutput) @@ -199,14 +214,23 @@ type SSMAPI interface { DescribeEffectiveInstanceAssociationsWithContext(aws.Context, *ssm.DescribeEffectiveInstanceAssociationsInput, ...request.Option) (*ssm.DescribeEffectiveInstanceAssociationsOutput, error) DescribeEffectiveInstanceAssociationsRequest(*ssm.DescribeEffectiveInstanceAssociationsInput) (*request.Request, *ssm.DescribeEffectiveInstanceAssociationsOutput) + DescribeEffectiveInstanceAssociationsPages(*ssm.DescribeEffectiveInstanceAssociationsInput, func(*ssm.DescribeEffectiveInstanceAssociationsOutput, bool) bool) error + DescribeEffectiveInstanceAssociationsPagesWithContext(aws.Context, *ssm.DescribeEffectiveInstanceAssociationsInput, func(*ssm.DescribeEffectiveInstanceAssociationsOutput, bool) bool, ...request.Option) error + DescribeEffectivePatchesForPatchBaseline(*ssm.DescribeEffectivePatchesForPatchBaselineInput) (*ssm.DescribeEffectivePatchesForPatchBaselineOutput, error) DescribeEffectivePatchesForPatchBaselineWithContext(aws.Context, *ssm.DescribeEffectivePatchesForPatchBaselineInput, ...request.Option) (*ssm.DescribeEffectivePatchesForPatchBaselineOutput, error) DescribeEffectivePatchesForPatchBaselineRequest(*ssm.DescribeEffectivePatchesForPatchBaselineInput) (*request.Request, *ssm.DescribeEffectivePatchesForPatchBaselineOutput) + DescribeEffectivePatchesForPatchBaselinePages(*ssm.DescribeEffectivePatchesForPatchBaselineInput, func(*ssm.DescribeEffectivePatchesForPatchBaselineOutput, bool) bool) error + DescribeEffectivePatchesForPatchBaselinePagesWithContext(aws.Context, *ssm.DescribeEffectivePatchesForPatchBaselineInput, func(*ssm.DescribeEffectivePatchesForPatchBaselineOutput, bool) bool, ...request.Option) error + DescribeInstanceAssociationsStatus(*ssm.DescribeInstanceAssociationsStatusInput) (*ssm.DescribeInstanceAssociationsStatusOutput, error) DescribeInstanceAssociationsStatusWithContext(aws.Context, *ssm.DescribeInstanceAssociationsStatusInput, ...request.Option) (*ssm.DescribeInstanceAssociationsStatusOutput, error) DescribeInstanceAssociationsStatusRequest(*ssm.DescribeInstanceAssociationsStatusInput) (*request.Request, *ssm.DescribeInstanceAssociationsStatusOutput) + DescribeInstanceAssociationsStatusPages(*ssm.DescribeInstanceAssociationsStatusInput, func(*ssm.DescribeInstanceAssociationsStatusOutput, bool) bool) error + DescribeInstanceAssociationsStatusPagesWithContext(aws.Context, *ssm.DescribeInstanceAssociationsStatusInput, func(*ssm.DescribeInstanceAssociationsStatusOutput, bool) bool, ...request.Option) error + DescribeInstanceInformation(*ssm.DescribeInstanceInformationInput) (*ssm.DescribeInstanceInformationOutput, error) DescribeInstanceInformationWithContext(aws.Context, *ssm.DescribeInstanceInformationInput, ...request.Option) (*ssm.DescribeInstanceInformationOutput, error) DescribeInstanceInformationRequest(*ssm.DescribeInstanceInformationInput) (*request.Request, *ssm.DescribeInstanceInformationOutput) @@ -218,54 +242,93 @@ type SSMAPI interface { DescribeInstancePatchStatesWithContext(aws.Context, *ssm.DescribeInstancePatchStatesInput, ...request.Option) (*ssm.DescribeInstancePatchStatesOutput, error) DescribeInstancePatchStatesRequest(*ssm.DescribeInstancePatchStatesInput) (*request.Request, *ssm.DescribeInstancePatchStatesOutput) + DescribeInstancePatchStatesPages(*ssm.DescribeInstancePatchStatesInput, func(*ssm.DescribeInstancePatchStatesOutput, bool) bool) error + DescribeInstancePatchStatesPagesWithContext(aws.Context, *ssm.DescribeInstancePatchStatesInput, func(*ssm.DescribeInstancePatchStatesOutput, bool) bool, ...request.Option) error + DescribeInstancePatchStatesForPatchGroup(*ssm.DescribeInstancePatchStatesForPatchGroupInput) (*ssm.DescribeInstancePatchStatesForPatchGroupOutput, error) DescribeInstancePatchStatesForPatchGroupWithContext(aws.Context, *ssm.DescribeInstancePatchStatesForPatchGroupInput, ...request.Option) (*ssm.DescribeInstancePatchStatesForPatchGroupOutput, error) DescribeInstancePatchStatesForPatchGroupRequest(*ssm.DescribeInstancePatchStatesForPatchGroupInput) (*request.Request, *ssm.DescribeInstancePatchStatesForPatchGroupOutput) + DescribeInstancePatchStatesForPatchGroupPages(*ssm.DescribeInstancePatchStatesForPatchGroupInput, func(*ssm.DescribeInstancePatchStatesForPatchGroupOutput, bool) bool) error + DescribeInstancePatchStatesForPatchGroupPagesWithContext(aws.Context, *ssm.DescribeInstancePatchStatesForPatchGroupInput, func(*ssm.DescribeInstancePatchStatesForPatchGroupOutput, bool) bool, ...request.Option) error + DescribeInstancePatches(*ssm.DescribeInstancePatchesInput) (*ssm.DescribeInstancePatchesOutput, error) DescribeInstancePatchesWithContext(aws.Context, *ssm.DescribeInstancePatchesInput, ...request.Option) (*ssm.DescribeInstancePatchesOutput, error) DescribeInstancePatchesRequest(*ssm.DescribeInstancePatchesInput) (*request.Request, *ssm.DescribeInstancePatchesOutput) + DescribeInstancePatchesPages(*ssm.DescribeInstancePatchesInput, func(*ssm.DescribeInstancePatchesOutput, bool) bool) error + DescribeInstancePatchesPagesWithContext(aws.Context, *ssm.DescribeInstancePatchesInput, func(*ssm.DescribeInstancePatchesOutput, bool) bool, ...request.Option) error + DescribeInventoryDeletions(*ssm.DescribeInventoryDeletionsInput) (*ssm.DescribeInventoryDeletionsOutput, error) DescribeInventoryDeletionsWithContext(aws.Context, *ssm.DescribeInventoryDeletionsInput, ...request.Option) (*ssm.DescribeInventoryDeletionsOutput, error) DescribeInventoryDeletionsRequest(*ssm.DescribeInventoryDeletionsInput) (*request.Request, *ssm.DescribeInventoryDeletionsOutput) + DescribeInventoryDeletionsPages(*ssm.DescribeInventoryDeletionsInput, func(*ssm.DescribeInventoryDeletionsOutput, bool) bool) error + DescribeInventoryDeletionsPagesWithContext(aws.Context, *ssm.DescribeInventoryDeletionsInput, func(*ssm.DescribeInventoryDeletionsOutput, bool) bool, ...request.Option) error + DescribeMaintenanceWindowExecutionTaskInvocations(*ssm.DescribeMaintenanceWindowExecutionTaskInvocationsInput) (*ssm.DescribeMaintenanceWindowExecutionTaskInvocationsOutput, error) DescribeMaintenanceWindowExecutionTaskInvocationsWithContext(aws.Context, *ssm.DescribeMaintenanceWindowExecutionTaskInvocationsInput, ...request.Option) (*ssm.DescribeMaintenanceWindowExecutionTaskInvocationsOutput, error) DescribeMaintenanceWindowExecutionTaskInvocationsRequest(*ssm.DescribeMaintenanceWindowExecutionTaskInvocationsInput) (*request.Request, *ssm.DescribeMaintenanceWindowExecutionTaskInvocationsOutput) + DescribeMaintenanceWindowExecutionTaskInvocationsPages(*ssm.DescribeMaintenanceWindowExecutionTaskInvocationsInput, func(*ssm.DescribeMaintenanceWindowExecutionTaskInvocationsOutput, bool) bool) error + DescribeMaintenanceWindowExecutionTaskInvocationsPagesWithContext(aws.Context, *ssm.DescribeMaintenanceWindowExecutionTaskInvocationsInput, func(*ssm.DescribeMaintenanceWindowExecutionTaskInvocationsOutput, bool) bool, ...request.Option) error + DescribeMaintenanceWindowExecutionTasks(*ssm.DescribeMaintenanceWindowExecutionTasksInput) (*ssm.DescribeMaintenanceWindowExecutionTasksOutput, error) DescribeMaintenanceWindowExecutionTasksWithContext(aws.Context, *ssm.DescribeMaintenanceWindowExecutionTasksInput, ...request.Option) (*ssm.DescribeMaintenanceWindowExecutionTasksOutput, error) DescribeMaintenanceWindowExecutionTasksRequest(*ssm.DescribeMaintenanceWindowExecutionTasksInput) (*request.Request, *ssm.DescribeMaintenanceWindowExecutionTasksOutput) + DescribeMaintenanceWindowExecutionTasksPages(*ssm.DescribeMaintenanceWindowExecutionTasksInput, func(*ssm.DescribeMaintenanceWindowExecutionTasksOutput, bool) bool) error + DescribeMaintenanceWindowExecutionTasksPagesWithContext(aws.Context, *ssm.DescribeMaintenanceWindowExecutionTasksInput, func(*ssm.DescribeMaintenanceWindowExecutionTasksOutput, bool) bool, ...request.Option) error + DescribeMaintenanceWindowExecutions(*ssm.DescribeMaintenanceWindowExecutionsInput) (*ssm.DescribeMaintenanceWindowExecutionsOutput, error) DescribeMaintenanceWindowExecutionsWithContext(aws.Context, *ssm.DescribeMaintenanceWindowExecutionsInput, ...request.Option) (*ssm.DescribeMaintenanceWindowExecutionsOutput, error) DescribeMaintenanceWindowExecutionsRequest(*ssm.DescribeMaintenanceWindowExecutionsInput) (*request.Request, *ssm.DescribeMaintenanceWindowExecutionsOutput) + DescribeMaintenanceWindowExecutionsPages(*ssm.DescribeMaintenanceWindowExecutionsInput, func(*ssm.DescribeMaintenanceWindowExecutionsOutput, bool) bool) error + DescribeMaintenanceWindowExecutionsPagesWithContext(aws.Context, *ssm.DescribeMaintenanceWindowExecutionsInput, func(*ssm.DescribeMaintenanceWindowExecutionsOutput, bool) bool, ...request.Option) error + DescribeMaintenanceWindowSchedule(*ssm.DescribeMaintenanceWindowScheduleInput) (*ssm.DescribeMaintenanceWindowScheduleOutput, error) DescribeMaintenanceWindowScheduleWithContext(aws.Context, *ssm.DescribeMaintenanceWindowScheduleInput, ...request.Option) (*ssm.DescribeMaintenanceWindowScheduleOutput, error) DescribeMaintenanceWindowScheduleRequest(*ssm.DescribeMaintenanceWindowScheduleInput) (*request.Request, *ssm.DescribeMaintenanceWindowScheduleOutput) + DescribeMaintenanceWindowSchedulePages(*ssm.DescribeMaintenanceWindowScheduleInput, func(*ssm.DescribeMaintenanceWindowScheduleOutput, bool) bool) error + DescribeMaintenanceWindowSchedulePagesWithContext(aws.Context, *ssm.DescribeMaintenanceWindowScheduleInput, func(*ssm.DescribeMaintenanceWindowScheduleOutput, bool) bool, ...request.Option) error + DescribeMaintenanceWindowTargets(*ssm.DescribeMaintenanceWindowTargetsInput) (*ssm.DescribeMaintenanceWindowTargetsOutput, error) DescribeMaintenanceWindowTargetsWithContext(aws.Context, *ssm.DescribeMaintenanceWindowTargetsInput, ...request.Option) (*ssm.DescribeMaintenanceWindowTargetsOutput, error) DescribeMaintenanceWindowTargetsRequest(*ssm.DescribeMaintenanceWindowTargetsInput) (*request.Request, *ssm.DescribeMaintenanceWindowTargetsOutput) + DescribeMaintenanceWindowTargetsPages(*ssm.DescribeMaintenanceWindowTargetsInput, func(*ssm.DescribeMaintenanceWindowTargetsOutput, bool) bool) error + DescribeMaintenanceWindowTargetsPagesWithContext(aws.Context, *ssm.DescribeMaintenanceWindowTargetsInput, func(*ssm.DescribeMaintenanceWindowTargetsOutput, bool) bool, ...request.Option) error + DescribeMaintenanceWindowTasks(*ssm.DescribeMaintenanceWindowTasksInput) (*ssm.DescribeMaintenanceWindowTasksOutput, error) DescribeMaintenanceWindowTasksWithContext(aws.Context, *ssm.DescribeMaintenanceWindowTasksInput, ...request.Option) (*ssm.DescribeMaintenanceWindowTasksOutput, error) DescribeMaintenanceWindowTasksRequest(*ssm.DescribeMaintenanceWindowTasksInput) (*request.Request, *ssm.DescribeMaintenanceWindowTasksOutput) + DescribeMaintenanceWindowTasksPages(*ssm.DescribeMaintenanceWindowTasksInput, func(*ssm.DescribeMaintenanceWindowTasksOutput, bool) bool) error + DescribeMaintenanceWindowTasksPagesWithContext(aws.Context, *ssm.DescribeMaintenanceWindowTasksInput, func(*ssm.DescribeMaintenanceWindowTasksOutput, bool) bool, ...request.Option) error + DescribeMaintenanceWindows(*ssm.DescribeMaintenanceWindowsInput) (*ssm.DescribeMaintenanceWindowsOutput, error) DescribeMaintenanceWindowsWithContext(aws.Context, *ssm.DescribeMaintenanceWindowsInput, ...request.Option) (*ssm.DescribeMaintenanceWindowsOutput, error) DescribeMaintenanceWindowsRequest(*ssm.DescribeMaintenanceWindowsInput) (*request.Request, *ssm.DescribeMaintenanceWindowsOutput) + DescribeMaintenanceWindowsPages(*ssm.DescribeMaintenanceWindowsInput, func(*ssm.DescribeMaintenanceWindowsOutput, bool) bool) error + DescribeMaintenanceWindowsPagesWithContext(aws.Context, *ssm.DescribeMaintenanceWindowsInput, func(*ssm.DescribeMaintenanceWindowsOutput, bool) bool, ...request.Option) error + DescribeMaintenanceWindowsForTarget(*ssm.DescribeMaintenanceWindowsForTargetInput) (*ssm.DescribeMaintenanceWindowsForTargetOutput, error) DescribeMaintenanceWindowsForTargetWithContext(aws.Context, *ssm.DescribeMaintenanceWindowsForTargetInput, ...request.Option) (*ssm.DescribeMaintenanceWindowsForTargetOutput, error) DescribeMaintenanceWindowsForTargetRequest(*ssm.DescribeMaintenanceWindowsForTargetInput) (*request.Request, *ssm.DescribeMaintenanceWindowsForTargetOutput) + DescribeMaintenanceWindowsForTargetPages(*ssm.DescribeMaintenanceWindowsForTargetInput, func(*ssm.DescribeMaintenanceWindowsForTargetOutput, bool) bool) error + DescribeMaintenanceWindowsForTargetPagesWithContext(aws.Context, *ssm.DescribeMaintenanceWindowsForTargetInput, func(*ssm.DescribeMaintenanceWindowsForTargetOutput, bool) bool, ...request.Option) error + DescribeOpsItems(*ssm.DescribeOpsItemsInput) (*ssm.DescribeOpsItemsOutput, error) DescribeOpsItemsWithContext(aws.Context, *ssm.DescribeOpsItemsInput, ...request.Option) (*ssm.DescribeOpsItemsOutput, error) DescribeOpsItemsRequest(*ssm.DescribeOpsItemsInput) (*request.Request, *ssm.DescribeOpsItemsOutput) + DescribeOpsItemsPages(*ssm.DescribeOpsItemsInput, func(*ssm.DescribeOpsItemsOutput, bool) bool) error + DescribeOpsItemsPagesWithContext(aws.Context, *ssm.DescribeOpsItemsInput, func(*ssm.DescribeOpsItemsOutput, bool) bool, ...request.Option) error + DescribeParameters(*ssm.DescribeParametersInput) (*ssm.DescribeParametersOutput, error) DescribeParametersWithContext(aws.Context, *ssm.DescribeParametersInput, ...request.Option) (*ssm.DescribeParametersOutput, error) DescribeParametersRequest(*ssm.DescribeParametersInput) (*request.Request, *ssm.DescribeParametersOutput) @@ -277,6 +340,9 @@ type SSMAPI interface { DescribePatchBaselinesWithContext(aws.Context, *ssm.DescribePatchBaselinesInput, ...request.Option) (*ssm.DescribePatchBaselinesOutput, error) DescribePatchBaselinesRequest(*ssm.DescribePatchBaselinesInput) (*request.Request, *ssm.DescribePatchBaselinesOutput) + DescribePatchBaselinesPages(*ssm.DescribePatchBaselinesInput, func(*ssm.DescribePatchBaselinesOutput, bool) bool) error + DescribePatchBaselinesPagesWithContext(aws.Context, *ssm.DescribePatchBaselinesInput, func(*ssm.DescribePatchBaselinesOutput, bool) bool, ...request.Option) error + DescribePatchGroupState(*ssm.DescribePatchGroupStateInput) (*ssm.DescribePatchGroupStateOutput, error) DescribePatchGroupStateWithContext(aws.Context, *ssm.DescribePatchGroupStateInput, ...request.Option) (*ssm.DescribePatchGroupStateOutput, error) DescribePatchGroupStateRequest(*ssm.DescribePatchGroupStateInput) (*request.Request, *ssm.DescribePatchGroupStateOutput) @@ -285,14 +351,23 @@ type SSMAPI interface { DescribePatchGroupsWithContext(aws.Context, *ssm.DescribePatchGroupsInput, ...request.Option) (*ssm.DescribePatchGroupsOutput, error) DescribePatchGroupsRequest(*ssm.DescribePatchGroupsInput) (*request.Request, *ssm.DescribePatchGroupsOutput) + DescribePatchGroupsPages(*ssm.DescribePatchGroupsInput, func(*ssm.DescribePatchGroupsOutput, bool) bool) error + DescribePatchGroupsPagesWithContext(aws.Context, *ssm.DescribePatchGroupsInput, func(*ssm.DescribePatchGroupsOutput, bool) bool, ...request.Option) error + DescribePatchProperties(*ssm.DescribePatchPropertiesInput) (*ssm.DescribePatchPropertiesOutput, error) DescribePatchPropertiesWithContext(aws.Context, *ssm.DescribePatchPropertiesInput, ...request.Option) (*ssm.DescribePatchPropertiesOutput, error) DescribePatchPropertiesRequest(*ssm.DescribePatchPropertiesInput) (*request.Request, *ssm.DescribePatchPropertiesOutput) + DescribePatchPropertiesPages(*ssm.DescribePatchPropertiesInput, func(*ssm.DescribePatchPropertiesOutput, bool) bool) error + DescribePatchPropertiesPagesWithContext(aws.Context, *ssm.DescribePatchPropertiesInput, func(*ssm.DescribePatchPropertiesOutput, bool) bool, ...request.Option) error + DescribeSessions(*ssm.DescribeSessionsInput) (*ssm.DescribeSessionsOutput, error) DescribeSessionsWithContext(aws.Context, *ssm.DescribeSessionsInput, ...request.Option) (*ssm.DescribeSessionsOutput, error) DescribeSessionsRequest(*ssm.DescribeSessionsInput) (*request.Request, *ssm.DescribeSessionsOutput) + DescribeSessionsPages(*ssm.DescribeSessionsInput, func(*ssm.DescribeSessionsOutput, bool) bool) error + DescribeSessionsPagesWithContext(aws.Context, *ssm.DescribeSessionsInput, func(*ssm.DescribeSessionsOutput, bool) bool, ...request.Option) error + GetAutomationExecution(*ssm.GetAutomationExecutionInput) (*ssm.GetAutomationExecutionOutput, error) GetAutomationExecutionWithContext(aws.Context, *ssm.GetAutomationExecutionInput, ...request.Option) (*ssm.GetAutomationExecutionOutput, error) GetAutomationExecutionRequest(*ssm.GetAutomationExecutionInput) (*request.Request, *ssm.GetAutomationExecutionOutput) @@ -325,10 +400,16 @@ type SSMAPI interface { GetInventoryWithContext(aws.Context, *ssm.GetInventoryInput, ...request.Option) (*ssm.GetInventoryOutput, error) GetInventoryRequest(*ssm.GetInventoryInput) (*request.Request, *ssm.GetInventoryOutput) + GetInventoryPages(*ssm.GetInventoryInput, func(*ssm.GetInventoryOutput, bool) bool) error + GetInventoryPagesWithContext(aws.Context, *ssm.GetInventoryInput, func(*ssm.GetInventoryOutput, bool) bool, ...request.Option) error + GetInventorySchema(*ssm.GetInventorySchemaInput) (*ssm.GetInventorySchemaOutput, error) GetInventorySchemaWithContext(aws.Context, *ssm.GetInventorySchemaInput, ...request.Option) (*ssm.GetInventorySchemaOutput, error) GetInventorySchemaRequest(*ssm.GetInventorySchemaInput) (*request.Request, *ssm.GetInventorySchemaOutput) + GetInventorySchemaPages(*ssm.GetInventorySchemaInput, func(*ssm.GetInventorySchemaOutput, bool) bool) error + GetInventorySchemaPagesWithContext(aws.Context, *ssm.GetInventorySchemaInput, func(*ssm.GetInventorySchemaOutput, bool) bool, ...request.Option) error + GetMaintenanceWindow(*ssm.GetMaintenanceWindowInput) (*ssm.GetMaintenanceWindowOutput, error) GetMaintenanceWindowWithContext(aws.Context, *ssm.GetMaintenanceWindowInput, ...request.Option) (*ssm.GetMaintenanceWindowOutput, error) GetMaintenanceWindowRequest(*ssm.GetMaintenanceWindowInput) (*request.Request, *ssm.GetMaintenanceWindowOutput) @@ -357,6 +438,9 @@ type SSMAPI interface { GetOpsSummaryWithContext(aws.Context, *ssm.GetOpsSummaryInput, ...request.Option) (*ssm.GetOpsSummaryOutput, error) GetOpsSummaryRequest(*ssm.GetOpsSummaryInput) (*request.Request, *ssm.GetOpsSummaryOutput) + GetOpsSummaryPages(*ssm.GetOpsSummaryInput, func(*ssm.GetOpsSummaryOutput, bool) bool) error + GetOpsSummaryPagesWithContext(aws.Context, *ssm.GetOpsSummaryInput, func(*ssm.GetOpsSummaryOutput, bool) bool, ...request.Option) error + GetParameter(*ssm.GetParameterInput) (*ssm.GetParameterOutput, error) GetParameterWithContext(aws.Context, *ssm.GetParameterInput, ...request.Option) (*ssm.GetParameterOutput, error) GetParameterRequest(*ssm.GetParameterInput) (*request.Request, *ssm.GetParameterOutput) @@ -399,6 +483,9 @@ type SSMAPI interface { ListAssociationVersionsWithContext(aws.Context, *ssm.ListAssociationVersionsInput, ...request.Option) (*ssm.ListAssociationVersionsOutput, error) ListAssociationVersionsRequest(*ssm.ListAssociationVersionsInput) (*request.Request, *ssm.ListAssociationVersionsOutput) + ListAssociationVersionsPages(*ssm.ListAssociationVersionsInput, func(*ssm.ListAssociationVersionsOutput, bool) bool) error + ListAssociationVersionsPagesWithContext(aws.Context, *ssm.ListAssociationVersionsInput, func(*ssm.ListAssociationVersionsOutput, bool) bool, ...request.Option) error + ListAssociations(*ssm.ListAssociationsInput) (*ssm.ListAssociationsOutput, error) ListAssociationsWithContext(aws.Context, *ssm.ListAssociationsInput, ...request.Option) (*ssm.ListAssociationsOutput, error) ListAssociationsRequest(*ssm.ListAssociationsInput) (*request.Request, *ssm.ListAssociationsOutput) @@ -424,14 +511,23 @@ type SSMAPI interface { ListComplianceItemsWithContext(aws.Context, *ssm.ListComplianceItemsInput, ...request.Option) (*ssm.ListComplianceItemsOutput, error) ListComplianceItemsRequest(*ssm.ListComplianceItemsInput) (*request.Request, *ssm.ListComplianceItemsOutput) + ListComplianceItemsPages(*ssm.ListComplianceItemsInput, func(*ssm.ListComplianceItemsOutput, bool) bool) error + ListComplianceItemsPagesWithContext(aws.Context, *ssm.ListComplianceItemsInput, func(*ssm.ListComplianceItemsOutput, bool) bool, ...request.Option) error + ListComplianceSummaries(*ssm.ListComplianceSummariesInput) (*ssm.ListComplianceSummariesOutput, error) ListComplianceSummariesWithContext(aws.Context, *ssm.ListComplianceSummariesInput, ...request.Option) (*ssm.ListComplianceSummariesOutput, error) ListComplianceSummariesRequest(*ssm.ListComplianceSummariesInput) (*request.Request, *ssm.ListComplianceSummariesOutput) + ListComplianceSummariesPages(*ssm.ListComplianceSummariesInput, func(*ssm.ListComplianceSummariesOutput, bool) bool) error + ListComplianceSummariesPagesWithContext(aws.Context, *ssm.ListComplianceSummariesInput, func(*ssm.ListComplianceSummariesOutput, bool) bool, ...request.Option) error + ListDocumentVersions(*ssm.ListDocumentVersionsInput) (*ssm.ListDocumentVersionsOutput, error) ListDocumentVersionsWithContext(aws.Context, *ssm.ListDocumentVersionsInput, ...request.Option) (*ssm.ListDocumentVersionsOutput, error) ListDocumentVersionsRequest(*ssm.ListDocumentVersionsInput) (*request.Request, *ssm.ListDocumentVersionsOutput) + ListDocumentVersionsPages(*ssm.ListDocumentVersionsInput, func(*ssm.ListDocumentVersionsOutput, bool) bool) error + ListDocumentVersionsPagesWithContext(aws.Context, *ssm.ListDocumentVersionsInput, func(*ssm.ListDocumentVersionsOutput, bool) bool, ...request.Option) error + ListDocuments(*ssm.ListDocumentsInput) (*ssm.ListDocumentsOutput, error) ListDocumentsWithContext(aws.Context, *ssm.ListDocumentsInput, ...request.Option) (*ssm.ListDocumentsOutput, error) ListDocumentsRequest(*ssm.ListDocumentsInput) (*request.Request, *ssm.ListDocumentsOutput) @@ -447,10 +543,16 @@ type SSMAPI interface { ListResourceComplianceSummariesWithContext(aws.Context, *ssm.ListResourceComplianceSummariesInput, ...request.Option) (*ssm.ListResourceComplianceSummariesOutput, error) ListResourceComplianceSummariesRequest(*ssm.ListResourceComplianceSummariesInput) (*request.Request, *ssm.ListResourceComplianceSummariesOutput) + ListResourceComplianceSummariesPages(*ssm.ListResourceComplianceSummariesInput, func(*ssm.ListResourceComplianceSummariesOutput, bool) bool) error + ListResourceComplianceSummariesPagesWithContext(aws.Context, *ssm.ListResourceComplianceSummariesInput, func(*ssm.ListResourceComplianceSummariesOutput, bool) bool, ...request.Option) error + ListResourceDataSync(*ssm.ListResourceDataSyncInput) (*ssm.ListResourceDataSyncOutput, error) ListResourceDataSyncWithContext(aws.Context, *ssm.ListResourceDataSyncInput, ...request.Option) (*ssm.ListResourceDataSyncOutput, error) ListResourceDataSyncRequest(*ssm.ListResourceDataSyncInput) (*request.Request, *ssm.ListResourceDataSyncOutput) + ListResourceDataSyncPages(*ssm.ListResourceDataSyncInput, func(*ssm.ListResourceDataSyncOutput, bool) bool) error + ListResourceDataSyncPagesWithContext(aws.Context, *ssm.ListResourceDataSyncInput, func(*ssm.ListResourceDataSyncOutput, bool) bool, ...request.Option) error + ListTagsForResource(*ssm.ListTagsForResourceInput) (*ssm.ListTagsForResourceOutput, error) ListTagsForResourceWithContext(aws.Context, *ssm.ListTagsForResourceInput, ...request.Option) (*ssm.ListTagsForResourceOutput, error) ListTagsForResourceRequest(*ssm.ListTagsForResourceInput) (*request.Request, *ssm.ListTagsForResourceOutput) @@ -574,6 +676,9 @@ type SSMAPI interface { UpdateServiceSetting(*ssm.UpdateServiceSettingInput) (*ssm.UpdateServiceSettingOutput, error) UpdateServiceSettingWithContext(aws.Context, *ssm.UpdateServiceSettingInput, ...request.Option) (*ssm.UpdateServiceSettingOutput, error) UpdateServiceSettingRequest(*ssm.UpdateServiceSettingInput) (*request.Request, *ssm.UpdateServiceSettingOutput) + + WaitUntilCommandExecuted(*ssm.GetCommandInvocationInput) error + WaitUntilCommandExecutedWithContext(aws.Context, *ssm.GetCommandInvocationInput, ...request.WaiterOption) error } var _ SSMAPI = (*ssm.SSM)(nil) diff --git a/vendor/github.com/aws/aws-sdk-go/service/ssm/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/ssm/waiters.go new file mode 100644 index 000000000..4bc0d1401 --- /dev/null +++ b/vendor/github.com/aws/aws-sdk-go/service/ssm/waiters.go @@ -0,0 +1,91 @@ +// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. + +package ssm + +import ( + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/request" +) + +// WaitUntilCommandExecuted uses the Amazon SSM API operation +// GetCommandInvocation to wait for a condition to be met before returning. +// If the condition is not met within the max attempt window, an error will +// be returned. +func (c *SSM) WaitUntilCommandExecuted(input *GetCommandInvocationInput) error { + return c.WaitUntilCommandExecutedWithContext(aws.BackgroundContext(), input) +} + +// WaitUntilCommandExecutedWithContext is an extended version of WaitUntilCommandExecuted. +// 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 *SSM) WaitUntilCommandExecutedWithContext(ctx aws.Context, input *GetCommandInvocationInput, opts ...request.WaiterOption) error { + w := request.Waiter{ + Name: "WaitUntilCommandExecuted", + MaxAttempts: 20, + Delay: request.ConstantWaiterDelay(5 * time.Second), + Acceptors: []request.WaiterAcceptor{ + { + State: request.RetryWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "Pending", + }, + { + State: request.RetryWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "InProgress", + }, + { + State: request.RetryWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "Delayed", + }, + { + State: request.SuccessWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "Success", + }, + { + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "Cancelled", + }, + { + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "TimedOut", + }, + { + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "Failed", + }, + { + State: request.FailureWaiterState, + Matcher: request.PathWaiterMatch, Argument: "Status", + Expected: "Cancelling", + }, + }, + Logger: c.Config.Logger, + NewRequest: func(opts []request.Option) (*request.Request, error) { + var inCpy *GetCommandInvocationInput + if input != nil { + tmp := *input + inCpy = &tmp + } + req, _ := c.GetCommandInvocationRequest(inCpy) + req.SetContext(ctx) + req.ApplyOptions(opts...) + return req, nil + }, + } + w.ApplyOptions(opts...) + + 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 7f60d4aa1..550b5f687 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 @@ -1788,7 +1788,7 @@ type AssumeRoleWithSAMLInput struct { // in the IAM User Guide. // // SAMLAssertion is a required field - SAMLAssertion *string `min:"4" type:"string" required:"true"` + SAMLAssertion *string `min:"4" type:"string" required:"true" sensitive:"true"` } // String returns the string representation @@ -2100,7 +2100,7 @@ type AssumeRoleWithWebIdentityInput struct { // the application makes an AssumeRoleWithWebIdentity call. // // WebIdentityToken is a required field - WebIdentityToken *string `min:"4" type:"string" required:"true"` + WebIdentityToken *string `min:"4" type:"string" required:"true" sensitive:"true"` } // String returns the string representation diff --git a/vendor/github.com/creack/goselect/.gitignore b/vendor/github.com/creack/goselect/.gitignore deleted file mode 100644 index 6f4dacea8..000000000 --- a/vendor/github.com/creack/goselect/.gitignore +++ /dev/null @@ -1,29 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof - -go-select* -goselect* -example-* -example/example diff --git a/vendor/github.com/creack/goselect/Dockerfile b/vendor/github.com/creack/goselect/Dockerfile deleted file mode 100644 index d03b5a9d9..000000000 --- a/vendor/github.com/creack/goselect/Dockerfile +++ /dev/null @@ -1,5 +0,0 @@ -FROM google/golang:stable -MAINTAINER Guillaume J. Charmes -CMD /tmp/a.out -ADD . /src -RUN cd /src && go build -o /tmp/a.out diff --git a/vendor/github.com/creack/goselect/LICENSE b/vendor/github.com/creack/goselect/LICENSE deleted file mode 100644 index 95c600af1..000000000 --- a/vendor/github.com/creack/goselect/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Guillaume J. Charmes - -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/creack/goselect/README.md b/vendor/github.com/creack/goselect/README.md deleted file mode 100644 index 807ab85e8..000000000 --- a/vendor/github.com/creack/goselect/README.md +++ /dev/null @@ -1,133 +0,0 @@ -# go-select - -select(2) implementation in Go - -## Supported platforms - -| | 386 | amd64 | arm | arm64 | mips | mipsle | mips64 | mips64le | ppc64le | s390x | -|---------------|-----|-------|-----|-------|------|--------|--------|----------|---------|-------| -| **linux** | yes | yes | yes | yes | yes | yes | yes | yes | yes | yes | -| **darwin** | yes | yes | ?? | ?? | n/a | n/a | n/a | n/a | n/a | n/a | -| **freebsd** | yes | yes | yes | n/a | n/a | n/a | n/a | n/a | n/a | n/a | -| **openbsd** | yes | yes | yes | n/a | n/a | n/a | n/a | n/a | n/a | n/a | -| **netbsd** | yes | yes | yes | n/a | n/a | n/a | n/a | n/a | n/a | n/a | -| **dragonfly** | n/a | yes | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | -| **solaris** | n/a | no | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | -| **plan9** | no | no | no | n/a | n/a | n/a | n/a | n/a | n/a | n/a | -| **windows** | yes | yes | n/a | n/a | n/a | n/a | n/a | n/a | n/a | n/a | -| **android** | ?? | ?? | ?? | ?? | n/a | n/a | n/a | n/a | n/a | n/a | - -*n/a: platform not supported by Go -*??: not tested - -Go on `plan9` and `solaris` do not implement `syscall.Select` nor `syscall.SYS_SELECT`. - -## Cross compile test - -Note that this only tests the compilation, not the functionality. - -```sh -$> ./test_crosscompile.sh > /dev/null | sort -[OK] android/386 -[OK] android/amd64 -[OK] android/arm -[OK] android/arm64 -[OK] darwin/386 -[OK] darwin/amd64 -[OK] darwin/arm -[OK] darwin/arm64 -[OK] dragonfly/amd64 -[OK] freebsd/386 -[OK] freebsd/amd64 -[OK] freebsd/arm -[OK] linux/386 -[OK] linux/amd64 -[OK] linux/arm -[OK] linux/arm64 -[OK] linux/mips -[OK] linux/mips64 -[OK] linux/mips64le -[OK] linux/mipsle -[OK] linux/ppc64le -[OK] linux/s390x -[OK] netbsd/386 -[OK] netbsd/amd64 -[OK] netbsd/arm -[OK] openbsd/386 -[OK] openbsd/amd64 -[OK] openbsd/arm -[OK] plan9/386 -[OK] plan9/amd64 -[OK] plan9/arm -[OK] solaris/amd64 -[OK] windows/386 -[OK] windows/amd64 -[OK] windows/arm - -# Expected failures. -[KO] android/mips -[KO] android/mips64 -[KO] android/mips64le -[KO] android/mipsle -[KO] android/ppc64le -[KO] android/s390x -[KO] darwin/mips -[KO] darwin/mips64 -[KO] darwin/mips64le -[KO] darwin/mipsle -[KO] darwin/ppc64le -[KO] darwin/s390x -[KO] dragonfly/386 -[KO] dragonfly/arm -[KO] dragonfly/arm64 -[KO] dragonfly/mips -[KO] dragonfly/mips64 -[KO] dragonfly/mips64le -[KO] dragonfly/mipsle -[KO] dragonfly/ppc64le -[KO] dragonfly/s390x -[KO] freebsd/arm64 -[KO] freebsd/mips -[KO] freebsd/mips64 -[KO] freebsd/mips64le -[KO] freebsd/mipsle -[KO] freebsd/ppc64le -[KO] freebsd/s390x -[KO] netbsd/arm64 -[KO] netbsd/mips -[KO] netbsd/mips64 -[KO] netbsd/mips64le -[KO] netbsd/mipsle -[KO] netbsd/ppc64le -[KO] netbsd/s390x -[KO] openbsd/arm64 -[KO] openbsd/mips -[KO] openbsd/mips64 -[KO] openbsd/mips64le -[KO] openbsd/mipsle -[KO] openbsd/ppc64le -[KO] openbsd/s390x -[KO] plan9/arm64 -[KO] plan9/mips -[KO] plan9/mips64 -[KO] plan9/mips64le -[KO] plan9/mipsle -[KO] plan9/ppc64le -[KO] plan9/s390x -[KO] solaris/386 -[KO] solaris/arm -[KO] solaris/arm64 -[KO] solaris/mips -[KO] solaris/mips64 -[KO] solaris/mips64le -[KO] solaris/mipsle -[KO] solaris/ppc64le -[KO] solaris/s390x -[KO] windows/arm64 -[KO] windows/mips -[KO] windows/mips64 -[KO] windows/mips64le -[KO] windows/mipsle -[KO] windows/ppc64le -[KO] windows/s390x -``` diff --git a/vendor/github.com/creack/goselect/fdset.go b/vendor/github.com/creack/goselect/fdset.go deleted file mode 100644 index 2ff3f6c7a..000000000 --- a/vendor/github.com/creack/goselect/fdset.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build !freebsd,!windows,!plan9 - -package goselect - -import "syscall" - -const FD_SETSIZE = syscall.FD_SETSIZE - -// FDSet wraps syscall.FdSet with convenience methods -type FDSet syscall.FdSet - -// Set adds the fd to the set -func (fds *FDSet) Set(fd uintptr) { - fds.Bits[fd/NFDBITS] |= (1 << (fd % NFDBITS)) -} - -// Clear remove the fd from the set -func (fds *FDSet) Clear(fd uintptr) { - fds.Bits[fd/NFDBITS] &^= (1 << (fd % NFDBITS)) -} - -// IsSet check if the given fd is set -func (fds *FDSet) IsSet(fd uintptr) bool { - return fds.Bits[fd/NFDBITS]&(1<<(fd%NFDBITS)) != 0 -} - -// Keep a null set to avoid reinstatiation -var nullFdSet = &FDSet{} - -// Zero empties the Set -func (fds *FDSet) Zero() { - copy(fds.Bits[:], (nullFdSet).Bits[:]) -} diff --git a/vendor/github.com/creack/goselect/fdset_32.go b/vendor/github.com/creack/goselect/fdset_32.go deleted file mode 100644 index a346d3f1c..000000000 --- a/vendor/github.com/creack/goselect/fdset_32.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build darwin openbsd netbsd 386 arm mips mipsle - -package goselect - -// darwin, netbsd and openbsd uses uint32 on both amd64 and 386 - -const ( - // NFDBITS is the amount of bits per mask - NFDBITS = 4 * 8 -) diff --git a/vendor/github.com/creack/goselect/fdset_64.go b/vendor/github.com/creack/goselect/fdset_64.go deleted file mode 100644 index 0e70213d8..000000000 --- a/vendor/github.com/creack/goselect/fdset_64.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !darwin,!netbsd,!openbsd -// +build amd64 arm64 ppc64le mips64 mips64le s390x - -package goselect - -// darwin, netbsd and openbsd uses uint32 on both amd64 and 386 - -const ( - // NFDBITS is the amount of bits per mask - NFDBITS = 8 * 8 -) diff --git a/vendor/github.com/creack/goselect/fdset_doc.go b/vendor/github.com/creack/goselect/fdset_doc.go deleted file mode 100644 index d9f15a1ce..000000000 --- a/vendor/github.com/creack/goselect/fdset_doc.go +++ /dev/null @@ -1,93 +0,0 @@ -package goselect - -/** -From: XCode's MacOSX10.10.sdk/System/Library/Frameworks/Kernel.framework/Versions/A/Headers/sys/select.h --- -// darwin/amd64 / 386 -sizeof(__int32_t) == 4 --- - -typedef __int32_t __fd_mask; - -#define FD_SETSIZE 1024 -#define __NFDBITS (sizeof(__fd_mask) * 8) -#define __howmany(x, y) ((((x) % (y)) == 0) ? ((x) / (y)) : (((x) / (y)) + 1)) - -typedef struct fd_set { - __fd_mask fds_bits[__howmany(__FD_SETSIZE, __NFDBITS)]; -} fd_set; - -#define __FD_MASK(n) ((__fd_mask)1 << ((n) % __NFDBITS)) -#define FD_SET(n, p) ((p)->fds_bits[(n)/__NFDBITS] |= __FD_MASK(n)) -#define FD_CLR(n, p) ((p)->fds_bits[(n)/__NFDBITS] &= ~__FD_MASK(n)) -#define FD_ISSET(n, p) (((p)->fds_bits[(n)/__NFDBITS] & __FD_MASK(n)) != 0) -*/ - -/** -From: /usr/include/i386-linux-gnu/sys/select.h --- -// linux/i686 -sizeof(long int) == 4 --- - -typedef long int __fd_mask; - -#define FD_SETSIZE 1024 -#define __NFDBITS (sizeof(__fd_mask) * 8) - - -typedef struct fd_set { - __fd_mask fds_bits[__FD_SETSIZE / __NFDBITS]; -} fd_set; - -#define __FD_MASK(n) ((__fd_mask)1 << ((n) % __NFDBITS)) -#define FD_SET(n, p) ((p)->fds_bits[(n)/__NFDBITS] |= __FD_MASK(n)) -#define FD_CLR(n, p) ((p)->fds_bits[(n)/__NFDBITS] &= ~__FD_MASK(n)) -#define FD_ISSET(n, p) (((p)->fds_bits[(n)/__NFDBITS] & __FD_MASK(n)) != 0) -*/ - -/** -From: /usr/include/x86_64-linux-gnu/sys/select.h --- -// linux/amd64 -sizeof(long int) == 8 --- - -typedef long int __fd_mask; - -#define FD_SETSIZE 1024 -#define __NFDBITS (sizeof(__fd_mask) * 8) - - -typedef struct fd_set { - __fd_mask fds_bits[__FD_SETSIZE / __NFDBITS]; -} fd_set; - -#define __FD_MASK(n) ((__fd_mask)1 << ((n) % __NFDBITS)) -#define FD_SET(n, p) ((p)->fds_bits[(n)/__NFDBITS] |= __FD_MASK(n)) -#define FD_CLR(n, p) ((p)->fds_bits[(n)/__NFDBITS] &= ~__FD_MASK(n)) -#define FD_ISSET(n, p) (((p)->fds_bits[(n)/__NFDBITS] & __FD_MASK(n)) != 0) -*/ - -/** -From: /usr/include/sys/select.h --- -// freebsd/amd64 -sizeof(unsigned long) == 8 --- - -typedef unsigned long __fd_mask; - -#define FD_SETSIZE 1024U -#define __NFDBITS (sizeof(__fd_mask) * 8) -#define _howmany(x, y) (((x) + ((y) - 1)) / (y)) - -typedef struct fd_set { - __fd_mask fds_bits[_howmany(FD_SETSIZE, __NFDBITS)]; -} fd_set; - -#define __FD_MASK(n) ((__fd_mask)1 << ((n) % __NFDBITS)) -#define FD_SET(n, p) ((p)->fds_bits[(n)/__NFDBITS] |= __FD_MASK(n)) -#define FD_CLR(n, p) ((p)->fds_bits[(n)/__NFDBITS] &= ~__FD_MASK(n)) -#define FD_ISSET(n, p) (((p)->fds_bits[(n)/__NFDBITS] & __FD_MASK(n)) != 0) -*/ diff --git a/vendor/github.com/creack/goselect/fdset_freebsd.go b/vendor/github.com/creack/goselect/fdset_freebsd.go deleted file mode 100644 index 03f7b9127..000000000 --- a/vendor/github.com/creack/goselect/fdset_freebsd.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build freebsd - -package goselect - -import "syscall" - -const FD_SETSIZE = syscall.FD_SETSIZE - -// FDSet wraps syscall.FdSet with convenience methods -type FDSet syscall.FdSet - -// Set adds the fd to the set -func (fds *FDSet) Set(fd uintptr) { - fds.X__fds_bits[fd/NFDBITS] |= (1 << (fd % NFDBITS)) -} - -// Clear remove the fd from the set -func (fds *FDSet) Clear(fd uintptr) { - fds.X__fds_bits[fd/NFDBITS] &^= (1 << (fd % NFDBITS)) -} - -// IsSet check if the given fd is set -func (fds *FDSet) IsSet(fd uintptr) bool { - return fds.X__fds_bits[fd/NFDBITS]&(1<<(fd%NFDBITS)) != 0 -} - -// Keep a null set to avoid reinstatiation -var nullFdSet = &FDSet{} - -// Zero empties the Set -func (fds *FDSet) Zero() { - copy(fds.X__fds_bits[:], (nullFdSet).X__fds_bits[:]) -} diff --git a/vendor/github.com/creack/goselect/fdset_unsupported.go b/vendor/github.com/creack/goselect/fdset_unsupported.go deleted file mode 100644 index cbd8d5880..000000000 --- a/vendor/github.com/creack/goselect/fdset_unsupported.go +++ /dev/null @@ -1,20 +0,0 @@ -// +build plan9 - -package goselect - -const FD_SETSIZE = 0 - -// FDSet wraps syscall.FdSet with convenience methods -type FDSet struct{} - -// Set adds the fd to the set -func (fds *FDSet) Set(fd uintptr) {} - -// Clear remove the fd from the set -func (fds *FDSet) Clear(fd uintptr) {} - -// IsSet check if the given fd is set -func (fds *FDSet) IsSet(fd uintptr) bool { return false } - -// Zero empties the Set -func (fds *FDSet) Zero() {} diff --git a/vendor/github.com/creack/goselect/fdset_windows.go b/vendor/github.com/creack/goselect/fdset_windows.go deleted file mode 100644 index ee3491975..000000000 --- a/vendor/github.com/creack/goselect/fdset_windows.go +++ /dev/null @@ -1,57 +0,0 @@ -// +build windows - -package goselect - -import "syscall" - -const FD_SETSIZE = 64 - -// FDSet extracted from mingw libs source code -type FDSet struct { - fd_count uint - fd_array [FD_SETSIZE]uintptr -} - -// Set adds the fd to the set -func (fds *FDSet) Set(fd uintptr) { - var i uint - for i = 0; i < fds.fd_count; i++ { - if fds.fd_array[i] == fd { - break - } - } - if i == fds.fd_count { - if fds.fd_count < FD_SETSIZE { - fds.fd_array[i] = fd - fds.fd_count++ - } - } -} - -// Clear remove the fd from the set -func (fds *FDSet) Clear(fd uintptr) { - var i uint - for i = 0; i < fds.fd_count; i++ { - if fds.fd_array[i] == fd { - for i < fds.fd_count-1 { - fds.fd_array[i] = fds.fd_array[i+1] - i++ - } - fds.fd_count-- - break - } - } -} - -// IsSet check if the given fd is set -func (fds *FDSet) IsSet(fd uintptr) bool { - if isset, err := __WSAFDIsSet(syscall.Handle(fd), fds); err == nil && isset != 0 { - return true - } - return false -} - -// Zero empties the Set -func (fds *FDSet) Zero() { - fds.fd_count = 0 -} diff --git a/vendor/github.com/creack/goselect/select.go b/vendor/github.com/creack/goselect/select.go deleted file mode 100644 index 7f2875e73..000000000 --- a/vendor/github.com/creack/goselect/select.go +++ /dev/null @@ -1,28 +0,0 @@ -package goselect - -import ( - "syscall" - "time" -) - -// Select wraps syscall.Select with Go types -func Select(n int, r, w, e *FDSet, timeout time.Duration) error { - var timeval *syscall.Timeval - if timeout >= 0 { - t := syscall.NsecToTimeval(timeout.Nanoseconds()) - timeval = &t - } - - return sysSelect(n, r, w, e, timeval) -} - -// RetrySelect wraps syscall.Select with Go types, and retries a number of times, with a given retryDelay. -func RetrySelect(n int, r, w, e *FDSet, timeout time.Duration, retries int, retryDelay time.Duration) (err error) { - for i := 0; i < retries; i++ { - if err = Select(n, r, w, e, timeout); err != syscall.EINTR { - return err - } - time.Sleep(retryDelay) - } - return err -} diff --git a/vendor/github.com/creack/goselect/select_linux.go b/vendor/github.com/creack/goselect/select_linux.go deleted file mode 100644 index acd569e9d..000000000 --- a/vendor/github.com/creack/goselect/select_linux.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build linux - -package goselect - -import "syscall" - -func sysSelect(n int, r, w, e *FDSet, timeout *syscall.Timeval) error { - _, err := syscall.Select(n, (*syscall.FdSet)(r), (*syscall.FdSet)(w), (*syscall.FdSet)(e), timeout) - return err -} diff --git a/vendor/github.com/creack/goselect/select_other.go b/vendor/github.com/creack/goselect/select_other.go deleted file mode 100644 index 6c8208147..000000000 --- a/vendor/github.com/creack/goselect/select_other.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build !linux,!windows,!plan9,!solaris - -package goselect - -import "syscall" - -func sysSelect(n int, r, w, e *FDSet, timeout *syscall.Timeval) error { - return syscall.Select(n, (*syscall.FdSet)(r), (*syscall.FdSet)(w), (*syscall.FdSet)(e), timeout) -} diff --git a/vendor/github.com/creack/goselect/select_unsupported.go b/vendor/github.com/creack/goselect/select_unsupported.go deleted file mode 100644 index bea0ad94a..000000000 --- a/vendor/github.com/creack/goselect/select_unsupported.go +++ /dev/null @@ -1,16 +0,0 @@ -// +build plan9 solaris - -package goselect - -import ( - "fmt" - "runtime" - "syscall" -) - -// ErrUnsupported . -var ErrUnsupported = fmt.Errorf("Platofrm %s/%s unsupported", runtime.GOOS, runtime.GOARCH) - -func sysSelect(n int, r, w, e *FDSet, timeout *syscall.Timeval) error { - return ErrUnsupported -} diff --git a/vendor/github.com/creack/goselect/select_windows.go b/vendor/github.com/creack/goselect/select_windows.go deleted file mode 100644 index 0fb70d5d2..000000000 --- a/vendor/github.com/creack/goselect/select_windows.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build windows - -package goselect - -import "syscall" - -//sys _select(nfds int, readfds *FDSet, writefds *FDSet, exceptfds *FDSet, timeout *syscall.Timeval) (total int, err error) = ws2_32.select -//sys __WSAFDIsSet(handle syscall.Handle, fdset *FDSet) (isset int, err error) = ws2_32.__WSAFDIsSet - -func sysSelect(n int, r, w, e *FDSet, timeout *syscall.Timeval) error { - _, err := _select(n, r, w, e, timeout) - return err -} diff --git a/vendor/github.com/creack/goselect/test_crosscompile.sh b/vendor/github.com/creack/goselect/test_crosscompile.sh deleted file mode 100644 index f8e1d292f..000000000 --- a/vendor/github.com/creack/goselect/test_crosscompile.sh +++ /dev/null @@ -1,112 +0,0 @@ -rm -rf crosstest -mkdir -p crosstest - -export GOOS=linux; export GOARCH=arm; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=linux; export GOARCH=arm64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=linux; export GOARCH=amd64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=linux; export GOARCH=386; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=linux; export GOARCH=mips; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=linux; export GOARCH=mipsle; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=linux; export GOARCH=mips64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=linux; export GOARCH=mips64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=linux; export GOARCH=ppc64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=linux; export GOARCH=s390x; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; - -export GOOS=darwin; export GOARCH=arm; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=darwin; export GOARCH=arm64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=darwin; export GOARCH=amd64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=darwin; export GOARCH=386; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=darwin; export GOARCH=mips; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=darwin; export GOARCH=mipsle; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=darwin; export GOARCH=mips64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=darwin; export GOARCH=mips64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=darwin; export GOARCH=ppc64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=darwin; export GOARCH=s390x; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; - -export GOOS=freebsd; export GOARCH=arm; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=freebsd; export GOARCH=arm64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=freebsd; export GOARCH=amd64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=freebsd; export GOARCH=386; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=freebsd; export GOARCH=mips; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=freebsd; export GOARCH=mipsle; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=freebsd; export GOARCH=mips64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=freebsd; export GOARCH=mips64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=freebsd; export GOARCH=ppc64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=freebsd; export GOARCH=s390x; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; - -export GOOS=openbsd; export GOARCH=arm; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=openbsd; export GOARCH=arm64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=openbsd; export GOARCH=amd64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=openbsd; export GOARCH=386; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=openbsd; export GOARCH=mips; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=openbsd; export GOARCH=mipsle; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=openbsd; export GOARCH=mips64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=openbsd; export GOARCH=mips64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=openbsd; export GOARCH=ppc64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=openbsd; export GOARCH=s390x; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; - -export GOOS=netbsd; export GOARCH=arm; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=netbsd; export GOARCH=arm64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=netbsd; export GOARCH=amd64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=netbsd; export GOARCH=386; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=netbsd; export GOARCH=mips; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=netbsd; export GOARCH=mipsle; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=netbsd; export GOARCH=mips64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=netbsd; export GOARCH=mips64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=netbsd; export GOARCH=ppc64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=netbsd; export GOARCH=s390x; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; - -export GOOS=dragonfly; export GOARCH=arm; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=dragonfly; export GOARCH=arm64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=dragonfly; export GOARCH=amd64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=dragonfly; export GOARCH=386; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=dragonfly; export GOARCH=mips; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=dragonfly; export GOARCH=mipsle; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=dragonfly; export GOARCH=mips64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=dragonfly; export GOARCH=mips64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=dragonfly; export GOARCH=ppc64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=dragonfly; export GOARCH=s390x; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; - -export GOOS=solaris; export GOARCH=arm; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=solaris; export GOARCH=arm64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=solaris; export GOARCH=amd64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=solaris; export GOARCH=386; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=solaris; export GOARCH=mips; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=solaris; export GOARCH=mipsle; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=solaris; export GOARCH=mips64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=solaris; export GOARCH=mips64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=solaris; export GOARCH=ppc64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=solaris; export GOARCH=s390x; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; - -export GOOS=plan9; export GOARCH=arm; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=plan9; export GOARCH=arm64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=plan9; export GOARCH=amd64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=plan9; export GOARCH=386; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=plan9; export GOARCH=mips; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=plan9; export GOARCH=mipsle; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=plan9; export GOARCH=mips64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=plan9; export GOARCH=mips64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=plan9; export GOARCH=ppc64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=plan9; export GOARCH=s390x; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; - -export GOOS=windows; export GOARCH=arm; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=windows; export GOARCH=arm64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=windows; export GOARCH=amd64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=windows; export GOARCH=386; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=windows; export GOARCH=mips; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=windows; export GOARCH=mipsle; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=windows; export GOARCH=mips64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=windows; export GOARCH=mips64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=windows; export GOARCH=ppc64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=windows; export GOARCH=s390x; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; - -export GOOS=android; export GOARCH=arm; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=android; export GOARCH=arm64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=android; export GOARCH=amd64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=android; export GOARCH=386; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=android; export GOARCH=mips; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=android; export GOARCH=mipsle; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=android; export GOARCH=mips64; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=android; export GOARCH=mips64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=android; export GOARCH=ppc64le; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; -export GOOS=android; export GOARCH=s390x; echo "$(go build -o crosstest/${GOOS}_${GOARCH} && echo '[OK]' || echo '[KO]') $GOOS/$GOARCH"; diff --git a/vendor/github.com/creack/goselect/zselect_windows.go b/vendor/github.com/creack/goselect/zselect_windows.go deleted file mode 100644 index e01502c07..000000000 --- a/vendor/github.com/creack/goselect/zselect_windows.go +++ /dev/null @@ -1,39 +0,0 @@ -// MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT - -package goselect - -import "unsafe" -import "syscall" - -var _ unsafe.Pointer - -var ( - modws2_32 = syscall.NewLazyDLL("ws2_32.dll") - - procselect = modws2_32.NewProc("select") - proc__WSAFDIsSet = modws2_32.NewProc("__WSAFDIsSet") -) - -func _select(nfds int, readfds *FDSet, writefds *FDSet, exceptfds *FDSet, timeout *syscall.Timeval) (total int, err error) { - r0, _, e1 := syscall.Syscall6(procselect.Addr(), 5, uintptr(nfds), uintptr(unsafe.Pointer(readfds)), uintptr(unsafe.Pointer(writefds)), uintptr(unsafe.Pointer(exceptfds)), uintptr(unsafe.Pointer(timeout)), 0) - total = int(r0) - if total == 0 { - if e1 != 0 { - err = error(e1) - } - } - return -} - -func __WSAFDIsSet(handle syscall.Handle, fdset *FDSet) (isset int, err error) { - r0, _, e1 := syscall.Syscall(proc__WSAFDIsSet.Addr(), 2, uintptr(handle), uintptr(unsafe.Pointer(fdset)), 0) - isset = int(r0) - if isset == 0 { - if e1 != 0 { - err = error(e1) - } else { - err = syscall.EINVAL - } - } - return -} diff --git a/vendor/github.com/docker/docker/AUTHORS b/vendor/github.com/docker/docker/AUTHORS deleted file mode 100644 index c5dafd722..000000000 --- a/vendor/github.com/docker/docker/AUTHORS +++ /dev/null @@ -1,1952 +0,0 @@ -# This file lists all individuals having contributed content to the repository. -# For how it is generated, see `hack/generate-authors.sh`. - -Aanand Prasad -Aaron Davidson -Aaron Feng -Aaron Huslage -Aaron L. Xu -Aaron Lehmann -Aaron Welch -Aaron.L.Xu -Abel Muiño -Abhijeet Kasurde -Abhinandan Prativadi -Abhinav Ajgaonkar -Abhishek Chanda -Abhishek Sharma -Abin Shahab -Adam Avilla -Adam Eijdenberg -Adam Kunk -Adam Miller -Adam Mills -Adam Pointer -Adam Singer -Adam Walz -Addam Hardy -Aditi Rajagopal -Aditya -Adnan Khan -Adolfo Ochagavía -Adria Casas -Adrian Moisey -Adrian Mouat -Adrian Oprea -Adrien Folie -Adrien Gallouët -Ahmed Kamal -Ahmet Alp Balkan -Aidan Feldman -Aidan Hobson Sayers -AJ Bowen -Ajey Charantimath -ajneu -Akash Gupta -Akihiro Matsushima -Akihiro Suda -Akim Demaille -Akira Koyasu -Akshay Karle -Al Tobey -alambike -Alan Scherger -Alan Thompson -Albert Callarisa -Albert Zhang -Aleksa Sarai -Aleksandrs Fadins -Alena Prokharchyk -Alessandro Boch -Alessio Biancalana -Alex Chan -Alex Chen -Alex Coventry -Alex Crawford -Alex Ellis -Alex Gaynor -Alex Olshansky -Alex Samorukov -Alex Warhawk -Alexander Artemenko -Alexander Boyd -Alexander Larsson -Alexander Midlash -Alexander Morozov -Alexander Shopov -Alexandre Beslic -Alexandre Garnier -Alexandre González -Alexandru Sfirlogea -Alexey Guskov -Alexey Kotlyarov -Alexey Shamrin -Alexis THOMAS -Alfred Landrum -Ali Dehghani -Alicia Lauerman -Alihan Demir -Allen Madsen -Allen Sun -almoehi -Alvaro Saurin -Alvin Deng -Alvin Richards -amangoel -Amen Belayneh -Amir Goldstein -Amit Bakshi -Amit Krishnan -Amit Shukla -Amy Lindburg -Anand Patil -AnandkumarPatel -Anatoly Borodin -Anchal Agrawal -Anders Janmyr -Andre Dublin <81dublin@gmail.com> -Andre Granovsky -Andrea Luzzardi -Andrea Turli -Andreas Elvers -Andreas Köhler -Andreas Savvides -Andreas Tiefenthaler -Andrei Gherzan -Andrew C. Bodine -Andrew Clay Shafer -Andrew Duckworth -Andrew France -Andrew Gerrand -Andrew Guenther -Andrew He -Andrew Hsu -Andrew Kuklewicz -Andrew Macgregor -Andrew Macpherson -Andrew Martin -Andrew McDonnell -Andrew Munsell -Andrew Pennebaker -Andrew Po -Andrew Weiss -Andrew Williams -Andrews Medina -Andrey Petrov -Andrey Stolbovsky -André Martins -andy -Andy Chambers -andy diller -Andy Goldstein -Andy Kipp -Andy Rothfusz -Andy Smith -Andy Wilson -Anes Hasicic -Anil Belur -Anil Madhavapeddy -Ankush Agarwal -Anonmily -Anran Qiao -Anshul Pundir -Anthon van der Neut -Anthony Baire -Anthony Bishopric -Anthony Dahanne -Anthony Sottile -Anton Löfgren -Anton Nikitin -Anton Polonskiy -Anton Tiurin -Antonio Murdaca -Antonis Kalipetis -Antony Messerli -Anuj Bahuguna -Anusha Ragunathan -apocas -Arash Deshmeh -ArikaChen -Arnaud Lefebvre -Arnaud Porterie -Arthur Barr -Arthur Gautier -Artur Meyster -Arun Gupta -Asad Saeeduddin -Asbjørn Enge -averagehuman -Avi Das -Avi Miller -Avi Vaid -ayoshitake -Azat Khuyiyakhmetov -Bardia Keyoumarsi -Barnaby Gray -Barry Allard -Bartłomiej Piotrowski -Bastiaan Bakker -bdevloed -Ben Bonnefoy -Ben Firshman -Ben Golub -Ben Hall -Ben Sargent -Ben Severson -Ben Toews -Ben Wiklund -Benjamin Atkin -Benjamin Boudreau -Benoit Chesneau -Bernerd Schaefer -Bernhard M. Wiedemann -Bert Goethals -Bharath Thiruveedula -Bhiraj Butala -Bhumika Bayani -Bilal Amarni -Bill Wang -Bin Liu -Bingshen Wang -Blake Geno -Boaz Shuster -bobby abbott -Boris Pruessmann -Boshi Lian -Bouke Haarsma -Boyd Hemphill -boynux -Bradley Cicenas -Bradley Wright -Brandon Liu -Brandon Philips -Brandon Rhodes -Brendan Dixon -Brent Salisbury -Brett Higgins -Brett Kochendorfer -Brett Randall -Brian (bex) Exelbierd -Brian Bland -Brian DeHamer -Brian Dorsey -Brian Flad -Brian Goff -Brian McCallister -Brian Olsen -Brian Schwind -Brian Shumate -Brian Torres-Gil -Brian Trump -Brice Jaglin -Briehan Lombaard -Bruno Bigras -Bruno Binet -Bruno Gazzera -Bruno Renié -Bruno Tavares -Bryan Bess -Bryan Boreham -Bryan Matsuo -Bryan Murphy -Burke Libbey -Byung Kang -Caleb Spare -Calen Pennington -Cameron Boehmer -Cameron Spear -Campbell Allen -Candid Dauth -Cao Weiwei -Carl Henrik Lunde -Carl Loa Odin -Carl X. Su -Carlo Mion -Carlos Alexandro Becker -Carlos Sanchez -Carol Fager-Higgins -Cary -Casey Bisson -Ce Gao -Cedric Davies -Cezar Sa Espinola -Chad Swenson -Chance Zibolski -Chander Govindarajan -Chanhun Jeong -Chao Wang -Charles Chan -Charles Hooper -Charles Law -Charles Lindsay -Charles Merriam -Charles Sarrazin -Charles Smith -Charlie Drage -Charlie Lewis -Chase Bolt -ChaYoung You -Chen Chao -Chen Chuanliang -Chen Hanxiao -Chen Min -Chen Mingjie -Chen Qiu -Cheng-mean Liu -Chetan Birajdar -Chewey -Chia-liang Kao -chli -Cholerae Hu -Chris Alfonso -Chris Armstrong -Chris Dias -Chris Dituri -Chris Fordham -Chris Gavin -Chris Gibson -Chris Khoo -Chris McKinnel -Chris McKinnel -Chris Seto -Chris Snow -Chris St. Pierre -Chris Stivers -Chris Swan -Chris Wahl -Chris Weyl -Christian Berendt -Christian Brauner -Christian Böhme -Christian Persson -Christian Rotzoll -Christian Simon -Christian Stefanescu -Christophe Mehay -Christophe Troestler -Christophe Vidal -Christopher Biscardi -Christopher Crone -Christopher Currie -Christopher Jones -Christopher Latham -Christopher Rigor -Christy Perez -Chun Chen -Ciro S. Costa -Clayton Coleman -Clinton Kitson -Coenraad Loubser -Colin Dunklau -Colin Hebert -Colin Rice -Colin Walters -Collin Guarino -Colm Hally -companycy -Corbin Coleman -Corey Farrell -Cory Forsyth -cressie176 -CrimsonGlory -Cristian Staretu -cristiano balducci -Cruceru Calin-Cristian -CUI Wei -Cyprian Gracz -Cyril F -Daan van Berkel -Daehyeok Mun -Dafydd Crosby -dalanlan -Damian Smyth -Damien Nadé -Damien Nozay -Damjan Georgievski -Dan Anolik -Dan Buch -Dan Cotora -Dan Feldman -Dan Griffin -Dan Hirsch -Dan Keder -Dan Levy -Dan McPherson -Dan Stine -Dan Williams -Dani Louca -Daniel Antlinger -Daniel Dao -Daniel Exner -Daniel Farrell -Daniel Garcia -Daniel Gasienica -Daniel Grunwell -Daniel Hiltgen -Daniel J Walsh -Daniel Menet -Daniel Mizyrycki -Daniel Nephin -Daniel Norberg -Daniel Nordberg -Daniel Robinson -Daniel S -Daniel Von Fange -Daniel Watkins -Daniel X Moore -Daniel YC Lin -Daniel Zhang -Danny Berger -Danny Yates -Danyal Khaliq -Darren Coxall -Darren Shepherd -Darren Stahl -Dattatraya Kumbhar -Davanum Srinivas -Dave Barboza -Dave Goodchild -Dave Henderson -Dave MacDonald -Dave Tucker -David Anderson -David Calavera -David Corking -David Cramer -David Currie -David Davis -David Dooling -David Gageot -David Gebler -David Glasser -David Lawrence -David Lechner -David M. Karr -David Mackey -David Mat -David Mcanulty -David McKay -David Pelaez -David R. Jenni -David Röthlisberger -David Sheets -David Sissitka -David Trott -David Williamson -David Xia -David Young -Davide Ceretti -Dawn Chen -dbdd -dcylabs -Deborah Gertrude Digges -deed02392 -Deng Guangxing -Deni Bertovic -Denis Defreyne -Denis Gladkikh -Denis Ollier -Dennis Chen -Dennis Chen -Dennis Docter -Derek -Derek -Derek Ch -Derek McGowan -Deric Crago -Deshi Xiao -devmeyster -Devvyn Murphy -Dharmit Shah -Dhawal Yogesh Bhanushali -Diego Romero -Diego Siqueira -Dieter Reuter -Dillon Dixon -Dima Stopel -Dimitri John Ledkov -Dimitris Rozakis -Dimitry Andric -Dinesh Subhraveti -Ding Fei -Diogo Monica -DiuDiugirl -Djibril Koné -dkumor -Dmitri Logvinenko -Dmitri Shuralyov -Dmitry Demeshchuk -Dmitry Gusev -Dmitry Kononenko -Dmitry Shyshkin -Dmitry Smirnov -Dmitry V. Krivenok -Dmitry Vorobev -Dolph Mathews -Dominik Dingel -Dominik Finkbeiner -Dominik Honnef -Don Kirkby -Don Kjer -Don Spaulding -Donald Huang -Dong Chen -Donovan Jones -Doron Podoleanu -Doug Davis -Doug MacEachern -Doug Tangren -Douglas Curtis -Dr Nic Williams -dragon788 -Dražen Lučanin -Drew Erny -Drew Hubl -Dustin Sallings -Ed Costello -Edmund Wagner -Eiichi Tsukata -Eike Herzbach -Eivin Giske Skaaren -Eivind Uggedal -Elan Ruusamäe -Elena Morozova -Eli Uriegas -Elias Faxö -Elias Probst -Elijah Zupancic -eluck -Elvir Kuric -Emil Davtyan -Emil Hernvall -Emily Maier -Emily Rose -Emir Ozer -Enguerran -Eohyung Lee -epeterso -Eric Barch -Eric Curtin -Eric G. Noriega -Eric Hanchrow -Eric Lee -Eric Myhre -Eric Paris -Eric Rafaloff -Eric Rosenberg -Eric Sage -Eric Soderstrom -Eric Yang -Eric-Olivier Lamey -Erica Windisch -Erik Bray -Erik Dubbelboer -Erik Hollensbe -Erik Inge Bolsø -Erik Kristensen -Erik St. Martin -Erik Weathers -Erno Hopearuoho -Erwin van der Koogh -Euan Kemp -Eugen Krizo -Eugene Yakubovich -Evan Allrich -Evan Carmi -Evan Hazlett -Evan Krall -Evan Phoenix -Evan Wies -Evelyn Xu -Everett Toews -Evgeny Shmarnev -Evgeny Vereshchagin -Ewa Czechowska -Eystein Måløy Stenberg -ezbercih -Ezra Silvera -Fabian Lauer -Fabiano Rosas -Fabio Falci -Fabio Kung -Fabio Rapposelli -Fabio Rehm -Fabrizio Regini -Fabrizio Soppelsa -Faiz Khan -falmp -Fangyuan Gao <21551127@zju.edu.cn> -Fareed Dudhia -Fathi Boudra -Federico Gimenez -Felipe Oliveira -Felix Abecassis -Felix Geisendörfer -Felix Hupfeld -Felix Rabe -Felix Ruess -Felix Schindler -Feng Yan -Fengtu Wang -Ferenc Szabo -Fernando -Fero Volar -Ferran Rodenas -Filipe Brandenburger -Filipe Oliveira -Flavio Castelli -Flavio Crisciani -Florian -Florian Klein -Florian Maier -Florian Noeding -Florian Weingarten -Florin Asavoaie -Florin Patan -fonglh -Foysal Iqbal -Francesc Campoy -Francis Chuang -Francisco Carriedo -Francisco Souza -Frank Groeneveld -Frank Herrmann -Frank Macreery -Frank Rosquin -Fred Lifton -Frederick F. Kautz IV -Frederik Loeffert -Frederik Nordahl Jul Sabroe -Freek Kalter -Frieder Bluemle -Félix Baylac-Jacqué -Félix Cantournet -Gabe Rosenhouse -Gabor Nagy -Gabriel Linder -Gabriel Monroy -Gabriel Nicolas Avellaneda -Gaetan de Villele -Galen Sampson -Gang Qiao -Gareth Rushgrove -Garrett Barboza -Gary Schaetz -Gaurav -gautam, prasanna -Gaël PORTAY -Genki Takiuchi -GennadySpb -Geoffrey Bachelet -George Kontridze -George MacRorie -George Xie -Georgi Hristozov -Gereon Frey -German DZ -Gert van Valkenhoef -Gerwim Feiken -Ghislain Bourgeois -Giampaolo Mancini -Gianluca Borello -Gildas Cuisinier -gissehel -Giuseppe Mazzotta -Gleb Fotengauer-Malinovskiy -Gleb M Borisov -Glyn Normington -GoBella -Goffert van Gool -Gopikannan Venugopalsamy -Gosuke Miyashita -Gou Rao -Govinda Fichtner -Grant Reaber -Graydon Hoare -Greg Fausak -Greg Pflaum -Greg Stephens -Greg Thornton -Grzegorz Jaśkiewicz -Guilhem Lettron -Guilherme Salgado -Guillaume Dufour -Guillaume J. Charmes -guoxiuyan -Gurjeet Singh -Guruprasad -Gustav Sinder -gwx296173 -Günter Zöchbauer -Hakan Özler -Hans Kristian Flaatten -Hans Rødtang -Hao Shu Wei -Hao Zhang <21521210@zju.edu.cn> -Harald Albers -Harley Laue -Harold Cooper -Harry Zhang -Harshal Patil -Harshal Patil -He Simei -He Xiaoxi -He Xin -heartlock <21521209@zju.edu.cn> -Hector Castro -Helen Xie -Henning Sprang -Hobofan -Hollie Teal -Hong Xu -Hongbin Lu -hsinko <21551195@zju.edu.cn> -Hu Keping -Hu Tao -Huanzhong Zhang -Huayi Zhang -Hugo Duncan -Hugo Marisco <0x6875676f@gmail.com> -Hunter Blanks -huqun -Huu Nguyen -hyeongkyu.lee -Hyzhou Zhy -Iago López Galeiras -Ian Babrou -Ian Bishop -Ian Bull -Ian Calvert -Ian Campbell -Ian Lee -Ian Main -Ian Philpot -Ian Truslove -Iavael -Icaro Seara -Ignacio Capurro -Igor Dolzhikov -Igor Karpovich -Iliana Weller -Ilkka Laukkanen -Ilya Dmitrichenko -Ilya Gusev -Ilya Khlopotov -imre Fitos -inglesp -Ingo Gottwald -Isaac Dupree -Isabel Jimenez -Isao Jonas -Ivan Babrou -Ivan Fraixedes -Ivan Grcic -Ivan Markin -J Bruni -J. Nunn -Jack Danger Canty -Jack Laxson -Jacob Atzen -Jacob Edelman -Jacob Tomlinson -Jacob Vallejo -Jacob Wen -Jaivish Kothari -Jake Champlin -Jake Moshenko -Jake Sanders -jakedt -James Allen -James Carey -James Carr -James DeFelice -James Harrison Fisher -James Kyburz -James Kyle -James Lal -James Mills -James Nesbitt -James Nugent -James Turnbull -Jamie Hannaford -Jamshid Afshar -Jan Keromnes -Jan Koprowski -Jan Pazdziora -Jan Toebes -Jan-Gerd Tenberge -Jan-Jaap Driessen -Jana Radhakrishnan -Jannick Fahlbusch -Januar Wayong -Jared Biel -Jared Hocutt -Jaroslaw Zabiello -jaseg -Jasmine Hegman -Jason Divock -Jason Giedymin -Jason Green -Jason Hall -Jason Heiss -Jason Livesay -Jason McVetta -Jason Plum -Jason Shepherd -Jason Smith -Jason Sommer -Jason Stangroome -jaxgeller -Jay -Jay -Jay Kamat -Jean-Baptiste Barth -Jean-Baptiste Dalido -Jean-Christophe Berthon -Jean-Paul Calderone -Jean-Pierre Huynh -Jean-Tiare Le Bigot -Jeeva S. Chelladhurai -Jeff Anderson -Jeff Johnston -Jeff Lindsay -Jeff Mickey -Jeff Minard -Jeff Nickoloff -Jeff Silberman -Jeff Welch -Jeffrey Bolle -Jeffrey Morgan -Jeffrey van Gogh -Jenny Gebske -Jeremy Chambers -Jeremy Grosser -Jeremy Price -Jeremy Qian -Jeremy Unruh -Jeremy Yallop -Jeroen Franse -Jeroen Jacobs -Jesse Dearing -Jesse Dubay -Jessica Frazelle -Jezeniel Zapanta -Jhon Honce -Ji.Zhilong -Jian Zhang -Jie Luo -Jihyun Hwang -Jilles Oldenbeuving -Jim Alateras -Jim Galasyn -Jim Minter -Jim Perrin -Jimmy Cuadra -Jimmy Puckett -Jimmy Song -jimmyxian -Jinsoo Park -Jiri Popelka -Jiuyue Ma -Jiří Župka -jjy -jmzwcn -Joao Fernandes -Joe Beda -Joe Doliner -Joe Ferguson -Joe Gordon -Joe Shaw -Joe Van Dyk -Joel Friedly -Joel Handwell -Joel Hansson -Joel Wurtz -Joey Geiger -Joey Geiger -Joey Gibson -Joffrey F -Johan Euphrosine -Johan Rydberg -Johanan Lieberman -Johannes 'fish' Ziemke -John Costa -John Feminella -John Gardiner Myers -John Gossman -John Harris -John Howard (VM) -John Laswell -John Maguire -John Mulhausen -John OBrien III -John Starks -John Stephens -John Tims -John V. Martinez -John Warwick -John Willis -Jon Johnson -Jon Surrell -Jon Wedaman -Jonas Pfenniger -Jonathan A. Sternberg -Jonathan Boulle -Jonathan Camp -Jonathan Dowland -Jonathan Lebon -Jonathan Lomas -Jonathan McCrohan -Jonathan Mueller -Jonathan Pares -Jonathan Rudenberg -Jonathan Stoppani -Jonh Wendell -Joni Sar -Joost Cassee -Jordan Arentsen -Jordan Jennings -Jordan Sissel -Jorge Marin -Jorit Kleine-Möllhoff -Jose Diaz-Gonzalez -Joseph Anthony Pasquale Holsten -Joseph Hager -Joseph Kern -Joseph Rothrock -Josh -Josh Bodah -Josh Bonczkowski -Josh Chorlton -Josh Eveleth -Josh Hawn -Josh Horwitz -Josh Poimboeuf -Josh Soref -Josh Wilson -Josiah Kiehl -José Tomás Albornoz -Joyce Jang -JP -Julian Taylor -Julien Barbier -Julien Bisconti -Julien Bordellier -Julien Dubois -Julien Kassar -Julien Maitrehenry -Julien Pervillé -Julio Montes -Jun-Ru Chang -Jussi Nummelin -Justas Brazauskas -Justin Cormack -Justin Force -Justin Menga -Justin Plock -Justin Simonelis -Justin Terry -Justyn Temme -Jyrki Puttonen -Jérôme Petazzoni -Jörg Thalheim -K. Heller -Kai Blin -Kai Qiang Wu (Kennan) -Kamil Domański -Kamjar Gerami -Kanstantsin Shautsou -Kara Alexandra -Karan Lyons -Kareem Khazem -kargakis -Karl Grzeszczak -Karol Duleba -Karthik Nayak -Kate Heddleston -Katie McLaughlin -Kato Kazuyoshi -Katrina Owen -Kawsar Saiyeed -Kay Yan -kayrus -Ke Li -Ke Xu -Kei Ohmura -Keith Hudgins -Keli Hu -Ken Cochrane -Ken Herner -Ken ICHIKAWA -Kenfe-Mickaël Laventure -Kenjiro Nakayama -Kent Johnson -Kevin "qwazerty" Houdebert -Kevin Burke -Kevin Clark -Kevin Feyrer -Kevin J. Lynagh -Kevin Jing Qiu -Kevin Kern -Kevin Menard -Kevin Meredith -Kevin P. Kucharczyk -Kevin Richardson -Kevin Shi -Kevin Wallace -Kevin Yap -Keyvan Fatehi -kies -Kim BKC Carlbacker -Kim Eik -Kimbro Staken -Kir Kolyshkin -Kiran Gangadharan -Kirill SIbirev -knappe -Kohei Tsuruta -Koichi Shiraishi -Konrad Kleine -Konstantin Gribov -Konstantin L -Konstantin Pelykh -Krasi Georgiev -Krasimir Georgiev -Kris-Mikael Krister -Kristian Haugene -Kristina Zabunova -krrg -Kun Zhang -Kunal Kushwaha -Kyle Conroy -Kyle Linden -kyu -Lachlan Coote -Lai Jiangshan -Lajos Papp -Lakshan Perera -Lalatendu Mohanty -Lance Chen -Lance Kinley -Lars Butler -Lars Kellogg-Stedman -Lars R. Damerow -Lars-Magnus Skog -Laszlo Meszaros -Laura Frank -Laurent Erignoux -Laurie Voss -Leandro Siqueira -Lee Chao <932819864@qq.com> -Lee, Meng-Han -leeplay -Lei Jitang -Len Weincier -Lennie -Leo Gallucci -Leszek Kowalski -Levi Blackstone -Levi Gross -Lewis Daly -Lewis Marshall -Lewis Peckover -Li Yi -Liam Macgillavry -Liana Lo -Liang Mingqiang -Liang-Chi Hsieh -Liao Qingwei -Lily Guo -limsy -Lin Lu -LingFaKe -Linus Heckemann -Liran Tal -Liron Levin -Liu Bo -Liu Hua -liwenqi -lixiaobing10051267 -Liz Zhang -LIZAO LI -Lizzie Dixon <_@lizzie.io> -Lloyd Dewolf -Lokesh Mandvekar -longliqiang88 <394564827@qq.com> -Lorenz Leutgeb -Lorenzo Fontana -Louis Opter -Luca Favatella -Luca Marturana -Luca Orlandi -Luca-Bogdan Grigorescu -Lucas Chan -Lucas Chi -Lucas Molas -Luciano Mores -Luis Martínez de Bartolomé Izquierdo -Luiz Svoboda -Lukas Waslowski -lukaspustina -Lukasz Zajaczkowski -Luke Marsden -Lyn -Lynda O'Leary -Lénaïc Huard -Ma Müller -Ma Shimiao -Mabin -Madhan Raj Mookkandy -Madhav Puri -Madhu Venugopal -Mageee -Mahesh Tiyyagura -malnick -Malte Janduda -Manfred Touron -Manfred Zabarauskas -Manjunath A Kumatagi -Mansi Nahar -Manuel Meurer -Manuel Woelker -mapk0y -Marc Abramowitz -Marc Kuo -Marc Tamsky -Marcel Edmund Franke -Marcelo Horacio Fortino -Marcelo Salazar -Marco Hennings -Marcus Cobden -Marcus Farkas -Marcus Linke -Marcus Martins -Marcus Ramberg -Marek Goldmann -Marian Marinov -Marianna Tessel -Mario Loriedo -Marius Gundersen -Marius Sturm -Marius Voila -Mark Allen -Mark McGranaghan -Mark McKinstry -Mark Milstein -Mark Oates -Mark Parker -Mark West -Markan Patel -Marko Mikulicic -Marko Tibold -Markus Fix -Markus Kortlang -Martijn Dwars -Martijn van Oosterhout -Martin Honermeyer -Martin Kelly -Martin Mosegaard Amdisen -Martin Redmond -Mary Anthony -Masahito Zembutsu -Masayuki Morita -Mason Malone -Mateusz Sulima -Mathias Monnerville -Mathieu Le Marec - Pasquet -Mathieu Parent -Matt Apperson -Matt Bachmann -Matt Bentley -Matt Haggard -Matt Hoyle -Matt McCormick -Matt Moore -Matt Richardson -Matt Rickard -Matt Robenolt -Matt Schurenko -Matt Williams -Matthew Heon -Matthew Lapworth -Matthew Mayer -Matthew Mosesohn -Matthew Mueller -Matthew Riley -Matthias Klumpp -Matthias Kühnle -Matthias Rampke -Matthieu Hauglustaine -Mauricio Garavaglia -mauriyouth -Max Shytikov -Maxim Fedchyshyn -Maxim Ivanov -Maxim Kulkin -Maxim Treskin -Maxime Petazzoni -Meaglith Ma -meejah -Megan Kostick -Mehul Kar -Mei ChunTao -Mengdi Gao -Mert Yazıcıoğlu -mgniu -Micah Zoltu -Michael A. Smith -Michael Bridgen -Michael Brown -Michael Chiang -Michael Crosby -Michael Currie -Michael Friis -Michael Gorsuch -Michael Grauer -Michael Holzheu -Michael Hudson-Doyle -Michael Huettermann -Michael Irwin -Michael Käufl -Michael Neale -Michael Prokop -Michael Scharf -Michael Spetsiotis -Michael Stapelberg -Michael Steinert -Michael Thies -Michael West -Michal Fojtik -Michal Gebauer -Michal Jemala -Michal Minář -Michal Wieczorek -Michaël Pailloncy -Michał Czeraszkiewicz -Michiel@unhosted -Mickaël FORTUNATO -Miguel Angel Fernández -Miguel Morales -Mihai Borobocea -Mihuleacc Sergiu -Mike Brown -Mike Casas -Mike Chelen -Mike Danese -Mike Dillon -Mike Dougherty -Mike Estes -Mike Gaffney -Mike Goelzer -Mike Leone -Mike MacCana -Mike Naberezny -Mike Snitzer -mikelinjie <294893458@qq.com> -Mikhail Sobolev -Miklos Szegedi -Milind Chawre -Miloslav Trmač -mingqing -Mingzhen Feng -Misty Stanley-Jones -Mitch Capper -Mizuki Urushida -mlarcher -Mohammad Banikazemi -Mohammed Aaqib Ansari -Mohit Soni -Moorthy RS -Morgan Bauer -Morgante Pell -Morgy93 -Morten Siebuhr -Morton Fox -Moysés Borges -mrfly -Mrunal Patel -Muayyad Alsadi -Mustafa Akın -Muthukumar R -Máximo Cuadros -Médi-Rémi Hashim -Nace Oroz -Nahum Shalman -Nakul Pathak -Nalin Dahyabhai -Nan Monnand Deng -Naoki Orii -Natalie Parker -Natanael Copa -Nate Brennand -Nate Eagleson -Nate Jones -Nathan Hsieh -Nathan Kleyn -Nathan LeClaire -Nathan McCauley -Nathan Williams -Naveed Jamil -Neal McBurnett -Neil Horman -Neil Peterson -Nelson Chen -Neyazul Haque -Nghia Tran -Niall O'Higgins -Nicholas E. Rabenau -Nick DeCoursin -Nick Irvine -Nick Parker -Nick Payne -Nick Russo -Nick Stenning -Nick Stinemates -NickrenREN -Nicola Kabar -Nicolas Borboën -Nicolas De Loof -Nicolas Dudebout -Nicolas Goy -Nicolas Kaiser -Nicolas Sterchele -Nicolás Hock Isaza -Nigel Poulton -Nik Nyby -Nikhil Chawla -NikolaMandic -Nikolas Garofil -Nikolay Milovanov -Nirmal Mehta -Nishant Totla -NIWA Hideyuki -Noah Meyerhans -Noah Treuhaft -noducks -Nolan Darilek -nponeccop -Nuutti Kotivuori -nzwsch -O.S. Tezer -objectified -odk- -Oguz Bilgic -Oh Jinkyun -Ohad Schneider -ohmystack -Ole Reifschneider -Oliver Neal -Olivier Gambier -Olle Jonsson -Oriol Francès -Oskar Niburski -Otto Kekäläinen -Ouyang Liduo -Ovidio Mallo -Panagiotis Moustafellos -Paolo G. Giarrusso -Pascal -Pascal Borreli -Pascal Hartig -Patrick Böänziger -Patrick Devine -Patrick Hemmer -Patrick Stapleton -pattichen -Paul -paul -Paul Annesley -Paul Bellamy -Paul Bowsher -Paul Furtado -Paul Hammond -Paul Jimenez -Paul Kehrer -Paul Lietar -Paul Liljenberg -Paul Morie -Paul Nasrat -Paul Weaver -Paulo Ribeiro -Pavel Lobashov -Pavel Pletenev -Pavel Pospisil -Pavel Sutyrin -Pavel Tikhomirov -Pavlos Ratis -Pavol Vargovcik -Pawel Konczalski -Peeyush Gupta -Peggy Li -Pei Su -Peng Tao -Penghan Wang -Per Weijnitz -perhapszzy@sina.com -Peter Bourgon -Peter Braden -Peter Bücker -Peter Choi -Peter Dave Hello -Peter Edge -Peter Ericson -Peter Esbensen -Peter Jaffe -Peter Malmgren -Peter Salvatore -Peter Volpe -Peter Waller -Petr Švihlík -Phil -Phil Estes -Phil Spitler -Philip Alexander Etling -Philip Monroe -Philipp Gillé -Philipp Wahala -Philipp Weissensteiner -Phillip Alexander -phineas -pidster -Piergiuliano Bossi -Pierre -Pierre Carrier -Pierre Dal-Pra -Pierre Wacrenier -Pierre-Alain RIVIERE -Piotr Bogdan -pixelistik -Porjo -Poul Kjeldager Sørensen -Pradeep Chhetri -Pradip Dhara -Prasanna Gautam -Pratik Karki -Prayag Verma -Przemek Hejman -Pure White -pysqz -Qiang Huang -Qinglan Peng -qudongfang -Quentin Brossard -Quentin Perez -Quentin Tayssier -r0n22 -Rafal Jeczalik -Rafe Colton -Raghavendra K T -Raghuram Devarakonda -Raja Sami -Rajat Pandit -Rajdeep Dua -Ralf Sippl -Ralle -Ralph Bean -Ramkumar Ramachandra -Ramon Brooker -Ramon van Alteren -Ray Tsang -ReadmeCritic -Recursive Madman -Reficul -Regan McCooey -Remi Rampin -Remy Suen -Renato Riccieri Santos Zannon -Renaud Gaubert -Rhys Hiltner -Ri Xu -Ricardo N Feliciano -Rich Moyse -Rich Seymour -Richard -Richard Burnison -Richard Harvey -Richard Mathie -Richard Metzler -Richard Scothern -Richo Healey -Rick Bradley -Rick van de Loo -Rick Wieman -Rik Nijessen -Riku Voipio -Riley Guerin -Ritesh H Shukla -Riyaz Faizullabhoy -Rob Vesse -Robert Bachmann -Robert Bittle -Robert Obryk -Robert Schneider -Robert Stern -Robert Terhaar -Robert Wallis -Roberto G. Hashioka -Roberto Muñoz Fernández -Robin Naundorf -Robin Schneider -Robin Speekenbrink -robpc -Rodolfo Carvalho -Rodrigo Vaz -Roel Van Nyen -Roger Peppe -Rohit Jnagal -Rohit Kadam -Rojin George -Roland Huß -Roland Kammerer -Roland Moriz -Roma Sokolov -Roman Dudin -Roman Strashkin -Ron Smits -Ron Williams -root -root -root -root -Rory Hunter -Rory McCune -Ross Boucher -Rovanion Luckey -Royce Remer -Rozhnov Alexandr -Rudolph Gottesheim -Rui Lopes -Runshen Zhu -Ryan Abrams -Ryan Anderson -Ryan Aslett -Ryan Belgrave -Ryan Detzel -Ryan Fowler -Ryan Liu -Ryan McLaughlin -Ryan O'Donnell -Ryan Seto -Ryan Simmen -Ryan Stelly -Ryan Thomas -Ryan Trauntvein -Ryan Wallner -Ryan Zhang -ryancooper7 -RyanDeng -Rémy Greinhofer -s. rannou -s00318865 -Sabin Basyal -Sachin Joshi -Sagar Hani -Sainath Grandhi -Sakeven Jiang -Sally O'Malley -Sam Abed -Sam Alba -Sam Bailey -Sam J Sharpe -Sam Neirinck -Sam Reis -Sam Rijs -Sambuddha Basu -Sami Wagiaalla -Samuel Andaya -Samuel Dion-Girardeau -Samuel Karp -Samuel PHAN -Sandeep Bansal -Sankar சங்கர் -Sanket Saurav -Santhosh Manohar -sapphiredev -Sargun Dhillon -Sascha Andres -Satnam Singh -Satoshi Amemiya -Satoshi Tagomori -Scott Bessler -Scott Collier -Scott Johnston -Scott Stamp -Scott Walls -sdreyesg -Sean Christopherson -Sean Cronin -Sean Lee -Sean McIntyre -Sean OMeara -Sean P. Kane -Sean Rodman -Sebastiaan van Steenis -Sebastiaan van Stijn -Senthil Kumar Selvaraj -Senthil Kumaran -SeongJae Park -Seongyeol Lim -Serge Hallyn -Sergey Alekseev -Sergey Evstifeev -Sergii Kabashniuk -Serhat Gülçiçek -Sevki Hasirci -Shane Canon -Shane da Silva -Shaun Kaasten -shaunol -Shawn Landden -Shawn Siefkas -shawnhe -Shayne Wang -Shekhar Gulati -Sheng Yang -Shengbo Song -Shev Yan -Shih-Yuan Lee -Shijiang Wei -Shijun Qin -Shishir Mahajan -Shoubhik Bose -Shourya Sarcar -shuai-z -Shukui Yang -Shuwei Hao -Sian Lerk Lau -Sidhartha Mani -sidharthamani -Silas Sewell -Silvan Jegen -Simei He -Simon Eskildsen -Simon Ferquel -Simon Leinen -Simon Menke -Simon Taranto -Simon Vikstrom -Sindhu S -Sjoerd Langkemper -Solganik Alexander -Solomon Hykes -Song Gao -Soshi Katsuta -Soulou -Spencer Brown -Spencer Smith -Sridatta Thatipamala -Sridhar Ratnakumar -Srini Brahmaroutu -Srinivasan Srivatsan -Stanislav Bondarenko -Steeve Morin -Stefan Berger -Stefan J. Wernli -Stefan Praszalowicz -Stefan S. -Stefan Scherer -Stefan Staudenmeyer -Stefan Weil -Stephan Spindler -Stephen Crosby -Stephen Day -Stephen Drake -Stephen Rust -Steve Desmond -Steve Dougherty -Steve Durrheimer -Steve Francia -Steve Koch -Steven Burgess -Steven Erenst -Steven Hartland -Steven Iveson -Steven Merrill -Steven Richards -Steven Taylor -Subhajit Ghosh -Sujith Haridasan -Sun Gengze <690388648@qq.com> -Sun Jianbo -Sunny Gogoi -Suryakumar Sudar -Sven Dowideit -Swapnil Daingade -Sylvain Baubeau -Sylvain Bellemare -Sébastien -Sébastien HOUZÉ -Sébastien Luttringer -Sébastien Stormacq -Tabakhase -Tadej Janež -TAGOMORI Satoshi -tang0th -Tangi Colin -Tatsuki Sugiura -Tatsushi Inagaki -Taylor Jones -tbonza -Ted M. Young -Tehmasp Chaudhri -Tejesh Mehta -terryding77 <550147740@qq.com> -tgic -Thatcher Peskens -theadactyl -Thell 'Bo' Fowler -Thermionix -Thijs Terlouw -Thomas Bikeev -Thomas Frössman -Thomas Gazagnaire -Thomas Grainger -Thomas Hansen -Thomas Leonard -Thomas Léveil -Thomas Orozco -Thomas Riccardi -Thomas Schroeter -Thomas Sjögren -Thomas Swift -Thomas Tanaka -Thomas Texier -Ti Zhou -Tianon Gravi -Tianyi Wang -Tibor Vass -Tiffany Jernigan -Tiffany Low -Tim Bart -Tim Bosse -Tim Dettrick -Tim Düsterhus -Tim Hockin -Tim Potter -Tim Ruffles -Tim Smith -Tim Terhorst -Tim Wang -Tim Waugh -Tim Wraight -Tim Zju <21651152@zju.edu.cn> -timfeirg -Timothy Hobbs -tjwebb123 -tobe -Tobias Bieniek -Tobias Bradtke -Tobias Gesellchen -Tobias Klauser -Tobias Munk -Tobias Schmidt -Tobias Schwab -Todd Crane -Todd Lunter -Todd Whiteman -Toli Kuznets -Tom Barlow -Tom Booth -Tom Denham -Tom Fotherby -Tom Howe -Tom Hulihan -Tom Maaswinkel -Tom Sweeney -Tom Wilkie -Tom X. Tobin -Tomas Tomecek -Tomasz Kopczynski -Tomasz Lipinski -Tomasz Nurkiewicz -Tommaso Visconti -Tomáš Hrčka -Tonny Xu -Tony Abboud -Tony Daws -Tony Miller -toogley -Torstein Husebø -Tõnis Tiigi -tpng -tracylihui <793912329@qq.com> -Trapier Marshall -Travis Cline -Travis Thieman -Trent Ogren -Trevor -Trevor Pounds -Trevor Sullivan -Trishna Guha -Tristan Carel -Troy Denton -Tycho Andersen -Tyler Brock -Tzu-Jung Lee -uhayate -Ulysse Carion -Umesh Yadav -Utz Bacher -vagrant -Vaidas Jablonskis -vanderliang -Veres Lajos -Victor Algaze -Victor Coisne -Victor Costan -Victor I. Wood -Victor Lyuboslavsky -Victor Marmol -Victor Palma -Victor Vieux -Victoria Bialas -Vijaya Kumar K -Viktor Stanchev -Viktor Vojnovski -VinayRaghavanKS -Vincent Batts -Vincent Bernat -Vincent Demeester -Vincent Giersch -Vincent Mayers -Vincent Woo -Vinod Kulkarni -Vishal Doshi -Vishnu Kannan -Vitaly Ostrosablin -Vitor Monteiro -Vivek Agarwal -Vivek Dasgupta -Vivek Goyal -Vladimir Bulyga -Vladimir Kirillov -Vladimir Pouzanov -Vladimir Rutsky -Vladimir Varankin -VladimirAus -Vlastimil Zeman -Vojtech Vitek (V-Teq) -waitingkuo -Walter Leibbrandt -Walter Stanish -Wang Chao -Wang Guoliang -Wang Jie -Wang Long -Wang Ping -Wang Xing -Wang Yuexiao -Ward Vandewege -WarheadsSE -Wayne Chang -Wayne Song -Weerasak Chongnguluam -Wei Wu -Wei-Ting Kuo -weiyan -Weiyang Zhu -Wen Cheng Ma -Wendel Fleming -Wenjun Tang -Wenkai Yin -Wentao Zhang -Wenxuan Zhao -Wenyu You <21551128@zju.edu.cn> -Wenzhi Liang -Wes Morgan -Wewang Xiaorenfine -Will Dietz -Will Rouesnel -Will Weaver -willhf -William Delanoue -William Henry -William Hubbs -William Martin -William Riancho -William Thurston -WiseTrem -Wolfgang Powisch -Wonjun Kim -xamyzhao -Xianglin Gao -Xianlu Bird -XiaoBing Jiang -Xiaoxu Chen -Xiaoyu Zhang -xiekeyang -Xinbo Weng -Xinzi Zhou -Xiuming Chen -Xuecong Liao -xuzhaokui -Yahya -YAMADA Tsuyoshi -Yamasaki Masahide -Yan Feng -Yang Bai -Yang Pengfei -yangchenliang -Yanqiang Miao -Yao Zaiyong -Yassine Tijani -Yasunori Mahata -Yazhong Liu -Yestin Sun -Yi EungJun -Yibai Zhang -Yihang Ho -Ying Li -Yohei Ueda -Yong Tang -Yongzhi Pan -Yosef Fertel -You-Sheng Yang (楊有勝) -Youcef YEKHLEF -Yu Changchun -Yu Chengxia -Yu Peng -Yu-Ju Hong -Yuan Sun -Yuanhong Peng -Yuhao Fang -Yunxiang Huang -Yurii Rashkovskii -Yves Junqueira -Zac Dover -Zach Borboa -Zachary Jaffee -Zain Memon -Zaiste! -Zane DeGraffenried -Zefan Li -Zen Lin(Zhinan Lin) -Zhang Kun -Zhang Wei -Zhang Wentao -ZhangHang -zhangxianwei -Zhenan Ye <21551168@zju.edu.cn> -zhenghenghuo -Zhenkun Bi -Zhou Hao -Zhu Guihua -Zhu Kunjia -Zhuoyun Wei -Zilin Du -zimbatm -Ziming Dong -ZJUshuaizhou <21551191@zju.edu.cn> -zmarouf -Zoltan Tombol -Zou Yu -zqh -Zuhayr Elahi -Zunayed Ali -Álex González -Álvaro Lázaro -Átila Camurça Alves -尹吉峰 -徐俊杰 -搏通 -黄艳红00139573 diff --git a/vendor/github.com/docker/docker/NOTICE b/vendor/github.com/docker/docker/NOTICE deleted file mode 100644 index 0c74e15b0..000000000 --- a/vendor/github.com/docker/docker/NOTICE +++ /dev/null @@ -1,19 +0,0 @@ -Docker -Copyright 2012-2017 Docker, Inc. - -This product includes software developed at Docker, Inc. (https://www.docker.com). - -This product contains software (https://github.com/kr/pty) developed -by Keith Rarick, licensed under the MIT License. - -The following is courtesy of our legal counsel: - - -Use and transfer of Docker may be subject to certain restrictions by the -United States and other governments. -It is your responsibility to ensure that your use and/or transfer does not -violate applicable laws. - -For more information, please see https://www.bis.doc.gov - -See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/vendor/github.com/dustin/go-humanize/.travis.yml b/vendor/github.com/dustin/go-humanize/.travis.yml deleted file mode 100644 index ba95cdd15..000000000 --- a/vendor/github.com/dustin/go-humanize/.travis.yml +++ /dev/null @@ -1,21 +0,0 @@ -sudo: false -language: go -go: - - 1.3.x - - 1.5.x - - 1.6.x - - 1.7.x - - 1.8.x - - 1.9.x - - master -matrix: - allow_failures: - - go: master - fast_finish: true -install: - - # Do nothing. This is needed to prevent default install action "go get -t -v ./..." from happening here (we want it to happen inside script step). -script: - - go get -t -v ./... - - diff -u <(echo -n) <(gofmt -d -s .) - - go tool vet . - - go test -v -race ./... diff --git a/vendor/github.com/dustin/go-humanize/LICENSE b/vendor/github.com/dustin/go-humanize/LICENSE deleted file mode 100644 index 8d9a94a90..000000000 --- a/vendor/github.com/dustin/go-humanize/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2005-2008 Dustin Sallings - -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/dustin/go-humanize/README.markdown b/vendor/github.com/dustin/go-humanize/README.markdown deleted file mode 100644 index 91b4ae564..000000000 --- a/vendor/github.com/dustin/go-humanize/README.markdown +++ /dev/null @@ -1,124 +0,0 @@ -# Humane Units [![Build Status](https://travis-ci.org/dustin/go-humanize.svg?branch=master)](https://travis-ci.org/dustin/go-humanize) [![GoDoc](https://godoc.org/github.com/dustin/go-humanize?status.svg)](https://godoc.org/github.com/dustin/go-humanize) - -Just a few functions for helping humanize times and sizes. - -`go get` it as `github.com/dustin/go-humanize`, import it as -`"github.com/dustin/go-humanize"`, use it as `humanize`. - -See [godoc](https://godoc.org/github.com/dustin/go-humanize) for -complete documentation. - -## Sizes - -This lets you take numbers like `82854982` and convert them to useful -strings like, `83 MB` or `79 MiB` (whichever you prefer). - -Example: - -```go -fmt.Printf("That file is %s.", humanize.Bytes(82854982)) // That file is 83 MB. -``` - -## Times - -This lets you take a `time.Time` and spit it out in relative terms. -For example, `12 seconds ago` or `3 days from now`. - -Example: - -```go -fmt.Printf("This was touched %s.", humanize.Time(someTimeInstance)) // This was touched 7 hours ago. -``` - -Thanks to Kyle Lemons for the time implementation from an IRC -conversation one day. It's pretty neat. - -## Ordinals - -From a [mailing list discussion][odisc] where a user wanted to be able -to label ordinals. - - 0 -> 0th - 1 -> 1st - 2 -> 2nd - 3 -> 3rd - 4 -> 4th - [...] - -Example: - -```go -fmt.Printf("You're my %s best friend.", humanize.Ordinal(193)) // You are my 193rd best friend. -``` - -## Commas - -Want to shove commas into numbers? Be my guest. - - 0 -> 0 - 100 -> 100 - 1000 -> 1,000 - 1000000000 -> 1,000,000,000 - -100000 -> -100,000 - -Example: - -```go -fmt.Printf("You owe $%s.\n", humanize.Comma(6582491)) // You owe $6,582,491. -``` - -## Ftoa - -Nicer float64 formatter that removes trailing zeros. - -```go -fmt.Printf("%f", 2.24) // 2.240000 -fmt.Printf("%s", humanize.Ftoa(2.24)) // 2.24 -fmt.Printf("%f", 2.0) // 2.000000 -fmt.Printf("%s", humanize.Ftoa(2.0)) // 2 -``` - -## SI notation - -Format numbers with [SI notation][sinotation]. - -Example: - -```go -humanize.SI(0.00000000223, "M") // 2.23 nM -``` - -## English-specific functions - -The following functions are in the `humanize/english` subpackage. - -### Plurals - -Simple English pluralization - -```go -english.PluralWord(1, "object", "") // object -english.PluralWord(42, "object", "") // objects -english.PluralWord(2, "bus", "") // buses -english.PluralWord(99, "locus", "loci") // loci - -english.Plural(1, "object", "") // 1 object -english.Plural(42, "object", "") // 42 objects -english.Plural(2, "bus", "") // 2 buses -english.Plural(99, "locus", "loci") // 99 loci -``` - -### Word series - -Format comma-separated words lists with conjuctions: - -```go -english.WordSeries([]string{"foo"}, "and") // foo -english.WordSeries([]string{"foo", "bar"}, "and") // foo and bar -english.WordSeries([]string{"foo", "bar", "baz"}, "and") // foo, bar and baz - -english.OxfordWordSeries([]string{"foo", "bar", "baz"}, "and") // foo, bar, and baz -``` - -[odisc]: https://groups.google.com/d/topic/golang-nuts/l8NhI74jl-4/discussion -[sinotation]: http://en.wikipedia.org/wiki/Metric_prefix diff --git a/vendor/github.com/dustin/go-humanize/big.go b/vendor/github.com/dustin/go-humanize/big.go deleted file mode 100644 index f49dc337d..000000000 --- a/vendor/github.com/dustin/go-humanize/big.go +++ /dev/null @@ -1,31 +0,0 @@ -package humanize - -import ( - "math/big" -) - -// order of magnitude (to a max order) -func oomm(n, b *big.Int, maxmag int) (float64, int) { - mag := 0 - m := &big.Int{} - for n.Cmp(b) >= 0 { - n.DivMod(n, b, m) - mag++ - if mag == maxmag && maxmag >= 0 { - break - } - } - return float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64())), mag -} - -// total order of magnitude -// (same as above, but with no upper limit) -func oom(n, b *big.Int) (float64, int) { - mag := 0 - m := &big.Int{} - for n.Cmp(b) >= 0 { - n.DivMod(n, b, m) - mag++ - } - return float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64())), mag -} diff --git a/vendor/github.com/dustin/go-humanize/bigbytes.go b/vendor/github.com/dustin/go-humanize/bigbytes.go deleted file mode 100644 index 1a2bf6172..000000000 --- a/vendor/github.com/dustin/go-humanize/bigbytes.go +++ /dev/null @@ -1,173 +0,0 @@ -package humanize - -import ( - "fmt" - "math/big" - "strings" - "unicode" -) - -var ( - bigIECExp = big.NewInt(1024) - - // BigByte is one byte in bit.Ints - BigByte = big.NewInt(1) - // BigKiByte is 1,024 bytes in bit.Ints - BigKiByte = (&big.Int{}).Mul(BigByte, bigIECExp) - // BigMiByte is 1,024 k bytes in bit.Ints - BigMiByte = (&big.Int{}).Mul(BigKiByte, bigIECExp) - // BigGiByte is 1,024 m bytes in bit.Ints - BigGiByte = (&big.Int{}).Mul(BigMiByte, bigIECExp) - // BigTiByte is 1,024 g bytes in bit.Ints - BigTiByte = (&big.Int{}).Mul(BigGiByte, bigIECExp) - // BigPiByte is 1,024 t bytes in bit.Ints - BigPiByte = (&big.Int{}).Mul(BigTiByte, bigIECExp) - // BigEiByte is 1,024 p bytes in bit.Ints - BigEiByte = (&big.Int{}).Mul(BigPiByte, bigIECExp) - // BigZiByte is 1,024 e bytes in bit.Ints - BigZiByte = (&big.Int{}).Mul(BigEiByte, bigIECExp) - // BigYiByte is 1,024 z bytes in bit.Ints - BigYiByte = (&big.Int{}).Mul(BigZiByte, bigIECExp) -) - -var ( - bigSIExp = big.NewInt(1000) - - // BigSIByte is one SI byte in big.Ints - BigSIByte = big.NewInt(1) - // BigKByte is 1,000 SI bytes in big.Ints - BigKByte = (&big.Int{}).Mul(BigSIByte, bigSIExp) - // BigMByte is 1,000 SI k bytes in big.Ints - BigMByte = (&big.Int{}).Mul(BigKByte, bigSIExp) - // BigGByte is 1,000 SI m bytes in big.Ints - BigGByte = (&big.Int{}).Mul(BigMByte, bigSIExp) - // BigTByte is 1,000 SI g bytes in big.Ints - BigTByte = (&big.Int{}).Mul(BigGByte, bigSIExp) - // BigPByte is 1,000 SI t bytes in big.Ints - BigPByte = (&big.Int{}).Mul(BigTByte, bigSIExp) - // BigEByte is 1,000 SI p bytes in big.Ints - BigEByte = (&big.Int{}).Mul(BigPByte, bigSIExp) - // BigZByte is 1,000 SI e bytes in big.Ints - BigZByte = (&big.Int{}).Mul(BigEByte, bigSIExp) - // BigYByte is 1,000 SI z bytes in big.Ints - BigYByte = (&big.Int{}).Mul(BigZByte, bigSIExp) -) - -var bigBytesSizeTable = map[string]*big.Int{ - "b": BigByte, - "kib": BigKiByte, - "kb": BigKByte, - "mib": BigMiByte, - "mb": BigMByte, - "gib": BigGiByte, - "gb": BigGByte, - "tib": BigTiByte, - "tb": BigTByte, - "pib": BigPiByte, - "pb": BigPByte, - "eib": BigEiByte, - "eb": BigEByte, - "zib": BigZiByte, - "zb": BigZByte, - "yib": BigYiByte, - "yb": BigYByte, - // Without suffix - "": BigByte, - "ki": BigKiByte, - "k": BigKByte, - "mi": BigMiByte, - "m": BigMByte, - "gi": BigGiByte, - "g": BigGByte, - "ti": BigTiByte, - "t": BigTByte, - "pi": BigPiByte, - "p": BigPByte, - "ei": BigEiByte, - "e": BigEByte, - "z": BigZByte, - "zi": BigZiByte, - "y": BigYByte, - "yi": BigYiByte, -} - -var ten = big.NewInt(10) - -func humanateBigBytes(s, base *big.Int, sizes []string) string { - if s.Cmp(ten) < 0 { - return fmt.Sprintf("%d B", s) - } - c := (&big.Int{}).Set(s) - val, mag := oomm(c, base, len(sizes)-1) - suffix := sizes[mag] - f := "%.0f %s" - if val < 10 { - f = "%.1f %s" - } - - return fmt.Sprintf(f, val, suffix) - -} - -// BigBytes produces a human readable representation of an SI size. -// -// See also: ParseBigBytes. -// -// BigBytes(82854982) -> 83 MB -func BigBytes(s *big.Int) string { - sizes := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} - return humanateBigBytes(s, bigSIExp, sizes) -} - -// BigIBytes produces a human readable representation of an IEC size. -// -// See also: ParseBigBytes. -// -// BigIBytes(82854982) -> 79 MiB -func BigIBytes(s *big.Int) string { - sizes := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"} - return humanateBigBytes(s, bigIECExp, sizes) -} - -// ParseBigBytes parses a string representation of bytes into the number -// of bytes it represents. -// -// See also: BigBytes, BigIBytes. -// -// ParseBigBytes("42 MB") -> 42000000, nil -// ParseBigBytes("42 mib") -> 44040192, nil -func ParseBigBytes(s string) (*big.Int, error) { - lastDigit := 0 - hasComma := false - for _, r := range s { - if !(unicode.IsDigit(r) || r == '.' || r == ',') { - break - } - if r == ',' { - hasComma = true - } - lastDigit++ - } - - num := s[:lastDigit] - if hasComma { - num = strings.Replace(num, ",", "", -1) - } - - val := &big.Rat{} - _, err := fmt.Sscanf(num, "%f", val) - if err != nil { - return nil, err - } - - extra := strings.ToLower(strings.TrimSpace(s[lastDigit:])) - if m, ok := bigBytesSizeTable[extra]; ok { - mv := (&big.Rat{}).SetInt(m) - val.Mul(val, mv) - rv := &big.Int{} - rv.Div(val.Num(), val.Denom()) - return rv, nil - } - - return nil, fmt.Errorf("unhandled size name: %v", extra) -} diff --git a/vendor/github.com/dustin/go-humanize/bytes.go b/vendor/github.com/dustin/go-humanize/bytes.go deleted file mode 100644 index 0b498f488..000000000 --- a/vendor/github.com/dustin/go-humanize/bytes.go +++ /dev/null @@ -1,143 +0,0 @@ -package humanize - -import ( - "fmt" - "math" - "strconv" - "strings" - "unicode" -) - -// IEC Sizes. -// kibis of bits -const ( - Byte = 1 << (iota * 10) - KiByte - MiByte - GiByte - TiByte - PiByte - EiByte -) - -// SI Sizes. -const ( - IByte = 1 - KByte = IByte * 1000 - MByte = KByte * 1000 - GByte = MByte * 1000 - TByte = GByte * 1000 - PByte = TByte * 1000 - EByte = PByte * 1000 -) - -var bytesSizeTable = map[string]uint64{ - "b": Byte, - "kib": KiByte, - "kb": KByte, - "mib": MiByte, - "mb": MByte, - "gib": GiByte, - "gb": GByte, - "tib": TiByte, - "tb": TByte, - "pib": PiByte, - "pb": PByte, - "eib": EiByte, - "eb": EByte, - // Without suffix - "": Byte, - "ki": KiByte, - "k": KByte, - "mi": MiByte, - "m": MByte, - "gi": GiByte, - "g": GByte, - "ti": TiByte, - "t": TByte, - "pi": PiByte, - "p": PByte, - "ei": EiByte, - "e": EByte, -} - -func logn(n, b float64) float64 { - return math.Log(n) / math.Log(b) -} - -func humanateBytes(s uint64, base float64, sizes []string) string { - if s < 10 { - return fmt.Sprintf("%d B", s) - } - e := math.Floor(logn(float64(s), base)) - suffix := sizes[int(e)] - val := math.Floor(float64(s)/math.Pow(base, e)*10+0.5) / 10 - f := "%.0f %s" - if val < 10 { - f = "%.1f %s" - } - - return fmt.Sprintf(f, val, suffix) -} - -// Bytes produces a human readable representation of an SI size. -// -// See also: ParseBytes. -// -// Bytes(82854982) -> 83 MB -func Bytes(s uint64) string { - sizes := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB"} - return humanateBytes(s, 1000, sizes) -} - -// IBytes produces a human readable representation of an IEC size. -// -// See also: ParseBytes. -// -// IBytes(82854982) -> 79 MiB -func IBytes(s uint64) string { - sizes := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"} - return humanateBytes(s, 1024, sizes) -} - -// ParseBytes parses a string representation of bytes into the number -// of bytes it represents. -// -// See Also: Bytes, IBytes. -// -// ParseBytes("42 MB") -> 42000000, nil -// ParseBytes("42 mib") -> 44040192, nil -func ParseBytes(s string) (uint64, error) { - lastDigit := 0 - hasComma := false - for _, r := range s { - if !(unicode.IsDigit(r) || r == '.' || r == ',') { - break - } - if r == ',' { - hasComma = true - } - lastDigit++ - } - - num := s[:lastDigit] - if hasComma { - num = strings.Replace(num, ",", "", -1) - } - - f, err := strconv.ParseFloat(num, 64) - if err != nil { - return 0, err - } - - extra := strings.ToLower(strings.TrimSpace(s[lastDigit:])) - if m, ok := bytesSizeTable[extra]; ok { - f *= float64(m) - if f >= math.MaxUint64 { - return 0, fmt.Errorf("too large: %v", s) - } - return uint64(f), nil - } - - return 0, fmt.Errorf("unhandled size name: %v", extra) -} diff --git a/vendor/github.com/dustin/go-humanize/comma.go b/vendor/github.com/dustin/go-humanize/comma.go deleted file mode 100644 index 520ae3e57..000000000 --- a/vendor/github.com/dustin/go-humanize/comma.go +++ /dev/null @@ -1,116 +0,0 @@ -package humanize - -import ( - "bytes" - "math" - "math/big" - "strconv" - "strings" -) - -// Comma produces a string form of the given number in base 10 with -// commas after every three orders of magnitude. -// -// e.g. Comma(834142) -> 834,142 -func Comma(v int64) string { - sign := "" - - // Min int64 can't be negated to a usable value, so it has to be special cased. - if v == math.MinInt64 { - return "-9,223,372,036,854,775,808" - } - - if v < 0 { - sign = "-" - v = 0 - v - } - - parts := []string{"", "", "", "", "", "", ""} - j := len(parts) - 1 - - for v > 999 { - parts[j] = strconv.FormatInt(v%1000, 10) - switch len(parts[j]) { - case 2: - parts[j] = "0" + parts[j] - case 1: - parts[j] = "00" + parts[j] - } - v = v / 1000 - j-- - } - parts[j] = strconv.Itoa(int(v)) - return sign + strings.Join(parts[j:], ",") -} - -// Commaf produces a string form of the given number in base 10 with -// commas after every three orders of magnitude. -// -// e.g. Commaf(834142.32) -> 834,142.32 -func Commaf(v float64) string { - buf := &bytes.Buffer{} - if v < 0 { - buf.Write([]byte{'-'}) - v = 0 - v - } - - comma := []byte{','} - - parts := strings.Split(strconv.FormatFloat(v, 'f', -1, 64), ".") - pos := 0 - if len(parts[0])%3 != 0 { - pos += len(parts[0]) % 3 - buf.WriteString(parts[0][:pos]) - buf.Write(comma) - } - for ; pos < len(parts[0]); pos += 3 { - buf.WriteString(parts[0][pos : pos+3]) - buf.Write(comma) - } - buf.Truncate(buf.Len() - 1) - - if len(parts) > 1 { - buf.Write([]byte{'.'}) - buf.WriteString(parts[1]) - } - return buf.String() -} - -// CommafWithDigits works like the Commaf but limits the resulting -// string to the given number of decimal places. -// -// e.g. CommafWithDigits(834142.32, 1) -> 834,142.3 -func CommafWithDigits(f float64, decimals int) string { - return stripTrailingDigits(Commaf(f), decimals) -} - -// BigComma produces a string form of the given big.Int in base 10 -// with commas after every three orders of magnitude. -func BigComma(b *big.Int) string { - sign := "" - if b.Sign() < 0 { - sign = "-" - b.Abs(b) - } - - athousand := big.NewInt(1000) - c := (&big.Int{}).Set(b) - _, m := oom(c, athousand) - parts := make([]string, m+1) - j := len(parts) - 1 - - mod := &big.Int{} - for b.Cmp(athousand) >= 0 { - b.DivMod(b, athousand, mod) - parts[j] = strconv.FormatInt(mod.Int64(), 10) - switch len(parts[j]) { - case 2: - parts[j] = "0" + parts[j] - case 1: - parts[j] = "00" + parts[j] - } - j-- - } - parts[j] = strconv.Itoa(int(b.Int64())) - return sign + strings.Join(parts[j:], ",") -} diff --git a/vendor/github.com/dustin/go-humanize/commaf.go b/vendor/github.com/dustin/go-humanize/commaf.go deleted file mode 100644 index 620690dec..000000000 --- a/vendor/github.com/dustin/go-humanize/commaf.go +++ /dev/null @@ -1,40 +0,0 @@ -// +build go1.6 - -package humanize - -import ( - "bytes" - "math/big" - "strings" -) - -// BigCommaf produces a string form of the given big.Float in base 10 -// with commas after every three orders of magnitude. -func BigCommaf(v *big.Float) string { - buf := &bytes.Buffer{} - if v.Sign() < 0 { - buf.Write([]byte{'-'}) - v.Abs(v) - } - - comma := []byte{','} - - parts := strings.Split(v.Text('f', -1), ".") - pos := 0 - if len(parts[0])%3 != 0 { - pos += len(parts[0]) % 3 - buf.WriteString(parts[0][:pos]) - buf.Write(comma) - } - for ; pos < len(parts[0]); pos += 3 { - buf.WriteString(parts[0][pos : pos+3]) - buf.Write(comma) - } - buf.Truncate(buf.Len() - 1) - - if len(parts) > 1 { - buf.Write([]byte{'.'}) - buf.WriteString(parts[1]) - } - return buf.String() -} diff --git a/vendor/github.com/dustin/go-humanize/ftoa.go b/vendor/github.com/dustin/go-humanize/ftoa.go deleted file mode 100644 index 1c62b640d..000000000 --- a/vendor/github.com/dustin/go-humanize/ftoa.go +++ /dev/null @@ -1,46 +0,0 @@ -package humanize - -import ( - "strconv" - "strings" -) - -func stripTrailingZeros(s string) string { - offset := len(s) - 1 - for offset > 0 { - if s[offset] == '.' { - offset-- - break - } - if s[offset] != '0' { - break - } - offset-- - } - return s[:offset+1] -} - -func stripTrailingDigits(s string, digits int) string { - if i := strings.Index(s, "."); i >= 0 { - if digits <= 0 { - return s[:i] - } - i++ - if i+digits >= len(s) { - return s - } - return s[:i+digits] - } - return s -} - -// Ftoa converts a float to a string with no trailing zeros. -func Ftoa(num float64) string { - return stripTrailingZeros(strconv.FormatFloat(num, 'f', 6, 64)) -} - -// FtoaWithDigits converts a float to a string but limits the resulting string -// to the given number of decimal places, and no trailing zeros. -func FtoaWithDigits(num float64, digits int) string { - return stripTrailingZeros(stripTrailingDigits(strconv.FormatFloat(num, 'f', 6, 64), digits)) -} diff --git a/vendor/github.com/dustin/go-humanize/humanize.go b/vendor/github.com/dustin/go-humanize/humanize.go deleted file mode 100644 index a2c2da31e..000000000 --- a/vendor/github.com/dustin/go-humanize/humanize.go +++ /dev/null @@ -1,8 +0,0 @@ -/* -Package humanize converts boring ugly numbers to human-friendly strings and back. - -Durations can be turned into strings such as "3 days ago", numbers -representing sizes like 82854982 into useful strings like, "83 MB" or -"79 MiB" (whichever you prefer). -*/ -package humanize diff --git a/vendor/github.com/dustin/go-humanize/number.go b/vendor/github.com/dustin/go-humanize/number.go deleted file mode 100644 index dec618659..000000000 --- a/vendor/github.com/dustin/go-humanize/number.go +++ /dev/null @@ -1,192 +0,0 @@ -package humanize - -/* -Slightly adapted from the source to fit go-humanize. - -Author: https://github.com/gorhill -Source: https://gist.github.com/gorhill/5285193 - -*/ - -import ( - "math" - "strconv" -) - -var ( - renderFloatPrecisionMultipliers = [...]float64{ - 1, - 10, - 100, - 1000, - 10000, - 100000, - 1000000, - 10000000, - 100000000, - 1000000000, - } - - renderFloatPrecisionRounders = [...]float64{ - 0.5, - 0.05, - 0.005, - 0.0005, - 0.00005, - 0.000005, - 0.0000005, - 0.00000005, - 0.000000005, - 0.0000000005, - } -) - -// FormatFloat produces a formatted number as string based on the following user-specified criteria: -// * thousands separator -// * decimal separator -// * decimal precision -// -// Usage: s := RenderFloat(format, n) -// The format parameter tells how to render the number n. -// -// See examples: http://play.golang.org/p/LXc1Ddm1lJ -// -// Examples of format strings, given n = 12345.6789: -// "#,###.##" => "12,345.67" -// "#,###." => "12,345" -// "#,###" => "12345,678" -// "#\u202F###,##" => "12 345,68" -// "#.###,###### => 12.345,678900 -// "" (aka default format) => 12,345.67 -// -// The highest precision allowed is 9 digits after the decimal symbol. -// There is also a version for integer number, FormatInteger(), -// which is convenient for calls within template. -func FormatFloat(format string, n float64) string { - // Special cases: - // NaN = "NaN" - // +Inf = "+Infinity" - // -Inf = "-Infinity" - if math.IsNaN(n) { - return "NaN" - } - if n > math.MaxFloat64 { - return "Infinity" - } - if n < -math.MaxFloat64 { - return "-Infinity" - } - - // default format - precision := 2 - decimalStr := "." - thousandStr := "," - positiveStr := "" - negativeStr := "-" - - if len(format) > 0 { - format := []rune(format) - - // If there is an explicit format directive, - // then default values are these: - precision = 9 - thousandStr = "" - - // collect indices of meaningful formatting directives - formatIndx := []int{} - for i, char := range format { - if char != '#' && char != '0' { - formatIndx = append(formatIndx, i) - } - } - - if len(formatIndx) > 0 { - // Directive at index 0: - // Must be a '+' - // Raise an error if not the case - // index: 0123456789 - // +0.000,000 - // +000,000.0 - // +0000.00 - // +0000 - if formatIndx[0] == 0 { - if format[formatIndx[0]] != '+' { - panic("RenderFloat(): invalid positive sign directive") - } - positiveStr = "+" - formatIndx = formatIndx[1:] - } - - // Two directives: - // First is thousands separator - // Raise an error if not followed by 3-digit - // 0123456789 - // 0.000,000 - // 000,000.00 - if len(formatIndx) == 2 { - if (formatIndx[1] - formatIndx[0]) != 4 { - panic("RenderFloat(): thousands separator directive must be followed by 3 digit-specifiers") - } - thousandStr = string(format[formatIndx[0]]) - formatIndx = formatIndx[1:] - } - - // One directive: - // Directive is decimal separator - // The number of digit-specifier following the separator indicates wanted precision - // 0123456789 - // 0.00 - // 000,0000 - if len(formatIndx) == 1 { - decimalStr = string(format[formatIndx[0]]) - precision = len(format) - formatIndx[0] - 1 - } - } - } - - // generate sign part - var signStr string - if n >= 0.000000001 { - signStr = positiveStr - } else if n <= -0.000000001 { - signStr = negativeStr - n = -n - } else { - signStr = "" - n = 0.0 - } - - // split number into integer and fractional parts - intf, fracf := math.Modf(n + renderFloatPrecisionRounders[precision]) - - // generate integer part string - intStr := strconv.FormatInt(int64(intf), 10) - - // add thousand separator if required - if len(thousandStr) > 0 { - for i := len(intStr); i > 3; { - i -= 3 - intStr = intStr[:i] + thousandStr + intStr[i:] - } - } - - // no fractional part, we can leave now - if precision == 0 { - return signStr + intStr - } - - // generate fractional part - fracStr := strconv.Itoa(int(fracf * renderFloatPrecisionMultipliers[precision])) - // may need padding - if len(fracStr) < precision { - fracStr = "000000000000000"[:precision-len(fracStr)] + fracStr - } - - return signStr + intStr + decimalStr + fracStr -} - -// FormatInteger produces a formatted number as string. -// See FormatFloat. -func FormatInteger(format string, n int) string { - return FormatFloat(format, float64(n)) -} diff --git a/vendor/github.com/dustin/go-humanize/ordinals.go b/vendor/github.com/dustin/go-humanize/ordinals.go deleted file mode 100644 index 43d88a861..000000000 --- a/vendor/github.com/dustin/go-humanize/ordinals.go +++ /dev/null @@ -1,25 +0,0 @@ -package humanize - -import "strconv" - -// Ordinal gives you the input number in a rank/ordinal format. -// -// Ordinal(3) -> 3rd -func Ordinal(x int) string { - suffix := "th" - switch x % 10 { - case 1: - if x%100 != 11 { - suffix = "st" - } - case 2: - if x%100 != 12 { - suffix = "nd" - } - case 3: - if x%100 != 13 { - suffix = "rd" - } - } - return strconv.Itoa(x) + suffix -} diff --git a/vendor/github.com/dustin/go-humanize/si.go b/vendor/github.com/dustin/go-humanize/si.go deleted file mode 100644 index ae659e0e4..000000000 --- a/vendor/github.com/dustin/go-humanize/si.go +++ /dev/null @@ -1,123 +0,0 @@ -package humanize - -import ( - "errors" - "math" - "regexp" - "strconv" -) - -var siPrefixTable = map[float64]string{ - -24: "y", // yocto - -21: "z", // zepto - -18: "a", // atto - -15: "f", // femto - -12: "p", // pico - -9: "n", // nano - -6: "µ", // micro - -3: "m", // milli - 0: "", - 3: "k", // kilo - 6: "M", // mega - 9: "G", // giga - 12: "T", // tera - 15: "P", // peta - 18: "E", // exa - 21: "Z", // zetta - 24: "Y", // yotta -} - -var revSIPrefixTable = revfmap(siPrefixTable) - -// revfmap reverses the map and precomputes the power multiplier -func revfmap(in map[float64]string) map[string]float64 { - rv := map[string]float64{} - for k, v := range in { - rv[v] = math.Pow(10, k) - } - return rv -} - -var riParseRegex *regexp.Regexp - -func init() { - ri := `^([\-0-9.]+)\s?([` - for _, v := range siPrefixTable { - ri += v - } - ri += `]?)(.*)` - - riParseRegex = regexp.MustCompile(ri) -} - -// ComputeSI finds the most appropriate SI prefix for the given number -// and returns the prefix along with the value adjusted to be within -// that prefix. -// -// See also: SI, ParseSI. -// -// e.g. ComputeSI(2.2345e-12) -> (2.2345, "p") -func ComputeSI(input float64) (float64, string) { - if input == 0 { - return 0, "" - } - mag := math.Abs(input) - exponent := math.Floor(logn(mag, 10)) - exponent = math.Floor(exponent/3) * 3 - - value := mag / math.Pow(10, exponent) - - // Handle special case where value is exactly 1000.0 - // Should return 1 M instead of 1000 k - if value == 1000.0 { - exponent += 3 - value = mag / math.Pow(10, exponent) - } - - value = math.Copysign(value, input) - - prefix := siPrefixTable[exponent] - return value, prefix -} - -// SI returns a string with default formatting. -// -// SI uses Ftoa to format float value, removing trailing zeros. -// -// See also: ComputeSI, ParseSI. -// -// e.g. SI(1000000, "B") -> 1 MB -// e.g. SI(2.2345e-12, "F") -> 2.2345 pF -func SI(input float64, unit string) string { - value, prefix := ComputeSI(input) - return Ftoa(value) + " " + prefix + unit -} - -// SIWithDigits works like SI but limits the resulting string to the -// given number of decimal places. -// -// e.g. SIWithDigits(1000000, 0, "B") -> 1 MB -// e.g. SIWithDigits(2.2345e-12, 2, "F") -> 2.23 pF -func SIWithDigits(input float64, decimals int, unit string) string { - value, prefix := ComputeSI(input) - return FtoaWithDigits(value, decimals) + " " + prefix + unit -} - -var errInvalid = errors.New("invalid input") - -// ParseSI parses an SI string back into the number and unit. -// -// See also: SI, ComputeSI. -// -// e.g. ParseSI("2.2345 pF") -> (2.2345e-12, "F", nil) -func ParseSI(input string) (float64, string, error) { - found := riParseRegex.FindStringSubmatch(input) - if len(found) != 4 { - return 0, "", errInvalid - } - mag := revSIPrefixTable[found[2]] - unit := found[3] - - base, err := strconv.ParseFloat(found[1], 64) - return base * mag, unit, err -} diff --git a/vendor/github.com/dustin/go-humanize/times.go b/vendor/github.com/dustin/go-humanize/times.go deleted file mode 100644 index dd3fbf5ef..000000000 --- a/vendor/github.com/dustin/go-humanize/times.go +++ /dev/null @@ -1,117 +0,0 @@ -package humanize - -import ( - "fmt" - "math" - "sort" - "time" -) - -// Seconds-based time units -const ( - Day = 24 * time.Hour - Week = 7 * Day - Month = 30 * Day - Year = 12 * Month - LongTime = 37 * Year -) - -// Time formats a time into a relative string. -// -// Time(someT) -> "3 weeks ago" -func Time(then time.Time) string { - return RelTime(then, time.Now(), "ago", "from now") -} - -// A RelTimeMagnitude struct contains a relative time point at which -// the relative format of time will switch to a new format string. A -// slice of these in ascending order by their "D" field is passed to -// CustomRelTime to format durations. -// -// The Format field is a string that may contain a "%s" which will be -// replaced with the appropriate signed label (e.g. "ago" or "from -// now") and a "%d" that will be replaced by the quantity. -// -// The DivBy field is the amount of time the time difference must be -// divided by in order to display correctly. -// -// e.g. if D is 2*time.Minute and you want to display "%d minutes %s" -// DivBy should be time.Minute so whatever the duration is will be -// expressed in minutes. -type RelTimeMagnitude struct { - D time.Duration - Format string - DivBy time.Duration -} - -var defaultMagnitudes = []RelTimeMagnitude{ - {time.Second, "now", time.Second}, - {2 * time.Second, "1 second %s", 1}, - {time.Minute, "%d seconds %s", time.Second}, - {2 * time.Minute, "1 minute %s", 1}, - {time.Hour, "%d minutes %s", time.Minute}, - {2 * time.Hour, "1 hour %s", 1}, - {Day, "%d hours %s", time.Hour}, - {2 * Day, "1 day %s", 1}, - {Week, "%d days %s", Day}, - {2 * Week, "1 week %s", 1}, - {Month, "%d weeks %s", Week}, - {2 * Month, "1 month %s", 1}, - {Year, "%d months %s", Month}, - {18 * Month, "1 year %s", 1}, - {2 * Year, "2 years %s", 1}, - {LongTime, "%d years %s", Year}, - {math.MaxInt64, "a long while %s", 1}, -} - -// RelTime formats a time into a relative string. -// -// It takes two times and two labels. In addition to the generic time -// delta string (e.g. 5 minutes), the labels are used applied so that -// the label corresponding to the smaller time is applied. -// -// RelTime(timeInPast, timeInFuture, "earlier", "later") -> "3 weeks earlier" -func RelTime(a, b time.Time, albl, blbl string) string { - return CustomRelTime(a, b, albl, blbl, defaultMagnitudes) -} - -// CustomRelTime formats a time into a relative string. -// -// It takes two times two labels and a table of relative time formats. -// In addition to the generic time delta string (e.g. 5 minutes), the -// labels are used applied so that the label corresponding to the -// smaller time is applied. -func CustomRelTime(a, b time.Time, albl, blbl string, magnitudes []RelTimeMagnitude) string { - lbl := albl - diff := b.Sub(a) - - if a.After(b) { - lbl = blbl - diff = a.Sub(b) - } - - n := sort.Search(len(magnitudes), func(i int) bool { - return magnitudes[i].D > diff - }) - - if n >= len(magnitudes) { - n = len(magnitudes) - 1 - } - mag := magnitudes[n] - args := []interface{}{} - escaped := false - for _, ch := range mag.Format { - if escaped { - switch ch { - case 's': - args = append(args, lbl) - case 'd': - args = append(args, diff/mag.DivBy) - } - escaped = false - } else { - escaped = ch == '%' - } - } - return fmt.Sprintf(mag.Format, args...) -} diff --git a/vendor/github.com/gophercloud/gophercloud/openstack/imageservice/v2/imageimport/doc.go b/vendor/github.com/gophercloud/gophercloud/openstack/imageservice/v2/imageimport/doc.go new file mode 100644 index 000000000..777244565 --- /dev/null +++ b/vendor/github.com/gophercloud/gophercloud/openstack/imageservice/v2/imageimport/doc.go @@ -0,0 +1,27 @@ +/* +Package imageimport enables management of images import and retrieval of the +Imageservice Import API information. + +Example to Get an information about the Import API + + importInfo, err := imageimport.Get(imagesClient).Extract() + if err != nil { + panic(err) + } + + fmt.Printf("%+v\n", importInfo) + +Example to Create a new image import + + createOpts := imageimport.CreateOpts{ + Name: imageimport.WebDownloadMethod, + URI: "http://download.cirros-cloud.net/0.4.0/cirros-0.4.0-x86_64-disk.img", + } + imageID := "da3b75d9-3f4a-40e7-8a2c-bfab23927dea" + + err := imageimport.Create(imagesClient, imageID, createOpts).ExtractErr() + if err != nil { + panic(err) + } +*/ +package imageimport diff --git a/vendor/github.com/gophercloud/gophercloud/openstack/imageservice/v2/imageimport/requests.go b/vendor/github.com/gophercloud/gophercloud/openstack/imageservice/v2/imageimport/requests.go new file mode 100644 index 000000000..118d36ea8 --- /dev/null +++ b/vendor/github.com/gophercloud/gophercloud/openstack/imageservice/v2/imageimport/requests.go @@ -0,0 +1,55 @@ +package imageimport + +import "github.com/gophercloud/gophercloud" + +// ImportMethod represents valid Import API method. +type ImportMethod string + +const ( + // GlanceDirectMethod represents glance-direct Import API method. + GlanceDirectMethod ImportMethod = "glance-direct" + + // WebDownloadMethod represents web-download Import API method. + WebDownloadMethod ImportMethod = "web-download" +) + +// Get retrieves Import API information data. +func Get(c *gophercloud.ServiceClient) (r GetResult) { + resp, err := c.Get(infoURL(c), &r.Body, nil) + _, r.Header, r.Err = gophercloud.ParseResponse(resp, err) + return +} + +// CreateOptsBuilder allows to add additional parameters to the Create request. +type CreateOptsBuilder interface { + ToImportCreateMap() (map[string]interface{}, error) +} + +// CreateOpts specifies parameters of a new image import. +type CreateOpts struct { + Name ImportMethod `json:"name"` + URI string `json:"uri"` +} + +// ToImportCreateMap constructs a request body from CreateOpts. +func (opts CreateOpts) ToImportCreateMap() (map[string]interface{}, error) { + b, err := gophercloud.BuildRequestBody(opts, "") + if err != nil { + return nil, err + } + return map[string]interface{}{"method": b}, nil +} + +// Create requests the creation of a new image import on the server. +func Create(client *gophercloud.ServiceClient, imageID string, opts CreateOptsBuilder) (r CreateResult) { + b, err := opts.ToImportCreateMap() + if err != nil { + r.Err = err + return + } + resp, err := client.Post(importURL(client, imageID), b, nil, &gophercloud.RequestOpts{ + OkCodes: []int{202}, + }) + _, r.Header, r.Err = gophercloud.ParseResponse(resp, err) + return +} diff --git a/vendor/github.com/gophercloud/gophercloud/openstack/imageservice/v2/imageimport/results.go b/vendor/github.com/gophercloud/gophercloud/openstack/imageservice/v2/imageimport/results.go new file mode 100644 index 000000000..2158c20da --- /dev/null +++ b/vendor/github.com/gophercloud/gophercloud/openstack/imageservice/v2/imageimport/results.go @@ -0,0 +1,38 @@ +package imageimport + +import "github.com/gophercloud/gophercloud" + +type commonResult struct { + gophercloud.Result +} + +// GetResult represents the result of a get operation. Call its Extract method +// to interpret it as ImportInfo. +type GetResult struct { + commonResult +} + +// CreateResult is the result of import Create operation. Call its ExtractErr +// method to determine if the request succeeded or failed. +type CreateResult struct { + gophercloud.ErrResult +} + +// ImportInfo represents information data for the Import API. +type ImportInfo struct { + ImportMethods ImportMethods `json:"import-methods"` +} + +// ImportMethods contains information about available Import API methods. +type ImportMethods struct { + Description string `json:"description"` + Type string `json:"type"` + Value []string `json:"value"` +} + +// Extract is a function that accepts a result and extracts ImportInfo. +func (r commonResult) Extract() (*ImportInfo, error) { + var s *ImportInfo + err := r.ExtractInto(&s) + return s, err +} diff --git a/vendor/github.com/gophercloud/gophercloud/openstack/imageservice/v2/imageimport/urls.go b/vendor/github.com/gophercloud/gophercloud/openstack/imageservice/v2/imageimport/urls.go new file mode 100644 index 000000000..20310eb09 --- /dev/null +++ b/vendor/github.com/gophercloud/gophercloud/openstack/imageservice/v2/imageimport/urls.go @@ -0,0 +1,17 @@ +package imageimport + +import "github.com/gophercloud/gophercloud" + +const ( + rootPath = "images" + infoPath = "info" + resourcePath = "import" +) + +func infoURL(c *gophercloud.ServiceClient) string { + return c.ServiceURL(infoPath, resourcePath) +} + +func importURL(c *gophercloud.ServiceClient, imageID string) string { + return c.ServiceURL(rootPath, imageID, resourcePath) +} diff --git a/vendor/github.com/gorilla/websocket/.gitignore b/vendor/github.com/gorilla/websocket/.gitignore deleted file mode 100644 index ac710204f..000000000 --- a/vendor/github.com/gorilla/websocket/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe - -.idea/ -*.iml \ No newline at end of file diff --git a/vendor/github.com/gorilla/websocket/.travis.yml b/vendor/github.com/gorilla/websocket/.travis.yml deleted file mode 100644 index 3d8d29cf3..000000000 --- a/vendor/github.com/gorilla/websocket/.travis.yml +++ /dev/null @@ -1,19 +0,0 @@ -language: go -sudo: false - -matrix: - include: - - go: 1.4 - - go: 1.5 - - go: 1.6 - - go: 1.7 - - go: 1.8 - - go: tip - allow_failures: - - go: tip - -script: - - go get -t -v ./... - - diff -u <(echo -n) <(gofmt -d .) - - go vet $(go list ./... | grep -v /vendor/) - - go test -v -race ./... diff --git a/vendor/github.com/gorilla/websocket/AUTHORS b/vendor/github.com/gorilla/websocket/AUTHORS deleted file mode 100644 index b003eca0c..000000000 --- a/vendor/github.com/gorilla/websocket/AUTHORS +++ /dev/null @@ -1,8 +0,0 @@ -# This is the official list of Gorilla WebSocket authors for copyright -# purposes. -# -# Please keep the list sorted. - -Gary Burd -Joachim Bauch - diff --git a/vendor/github.com/gorilla/websocket/LICENSE b/vendor/github.com/gorilla/websocket/LICENSE deleted file mode 100644 index 9171c9722..000000000 --- a/vendor/github.com/gorilla/websocket/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2013 The Gorilla WebSocket Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/gorilla/websocket/README.md b/vendor/github.com/gorilla/websocket/README.md deleted file mode 100644 index 33c3d2be3..000000000 --- a/vendor/github.com/gorilla/websocket/README.md +++ /dev/null @@ -1,64 +0,0 @@ -# Gorilla WebSocket - -Gorilla WebSocket is a [Go](http://golang.org/) implementation of the -[WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. - -[![Build Status](https://travis-ci.org/gorilla/websocket.svg?branch=master)](https://travis-ci.org/gorilla/websocket) -[![GoDoc](https://godoc.org/github.com/gorilla/websocket?status.svg)](https://godoc.org/github.com/gorilla/websocket) - -### Documentation - -* [API Reference](http://godoc.org/github.com/gorilla/websocket) -* [Chat example](https://github.com/gorilla/websocket/tree/master/examples/chat) -* [Command example](https://github.com/gorilla/websocket/tree/master/examples/command) -* [Client and server example](https://github.com/gorilla/websocket/tree/master/examples/echo) -* [File watch example](https://github.com/gorilla/websocket/tree/master/examples/filewatch) - -### Status - -The Gorilla WebSocket package provides a complete and tested implementation of -the [WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. The -package API is stable. - -### Installation - - go get github.com/gorilla/websocket - -### Protocol Compliance - -The Gorilla WebSocket package passes the server tests in the [Autobahn Test -Suite](http://autobahn.ws/testsuite) using the application in the [examples/autobahn -subdirectory](https://github.com/gorilla/websocket/tree/master/examples/autobahn). - -### Gorilla WebSocket compared with other packages - - - - - - - - - - - - - - - - - - -
github.com/gorillagolang.org/x/net
RFC 6455 Features
Passes Autobahn Test SuiteYesNo
Receive fragmented messageYesNo, see note 1
Send close messageYesNo
Send pings and receive pongsYesNo
Get the type of a received data messageYesYes, see note 2
Other Features
Compression ExtensionsExperimentalNo
Read message using io.ReaderYesNo, see note 3
Write message using io.WriteCloserYesNo, see note 3
- -Notes: - -1. Large messages are fragmented in [Chrome's new WebSocket implementation](http://www.ietf.org/mail-archive/web/hybi/current/msg10503.html). -2. The application can get the type of a received data message by implementing - a [Codec marshal](http://godoc.org/golang.org/x/net/websocket#Codec.Marshal) - function. -3. The go.net io.Reader and io.Writer operate across WebSocket frame boundaries. - Read returns when the input buffer is full or a frame boundary is - encountered. Each call to Write sends a single frame message. The Gorilla - io.Reader and io.WriteCloser operate on a single WebSocket message. - diff --git a/vendor/github.com/gorilla/websocket/client.go b/vendor/github.com/gorilla/websocket/client.go deleted file mode 100644 index 43a87c753..000000000 --- a/vendor/github.com/gorilla/websocket/client.go +++ /dev/null @@ -1,392 +0,0 @@ -// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package websocket - -import ( - "bufio" - "bytes" - "crypto/tls" - "encoding/base64" - "errors" - "io" - "io/ioutil" - "net" - "net/http" - "net/url" - "strings" - "time" -) - -// ErrBadHandshake is returned when the server response to opening handshake is -// invalid. -var ErrBadHandshake = errors.New("websocket: bad handshake") - -var errInvalidCompression = errors.New("websocket: invalid compression negotiation") - -// NewClient creates a new client connection using the given net connection. -// The URL u specifies the host and request URI. Use requestHeader to specify -// the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies -// (Cookie). Use the response.Header to get the selected subprotocol -// (Sec-WebSocket-Protocol) and cookies (Set-Cookie). -// -// If the WebSocket handshake fails, ErrBadHandshake is returned along with a -// non-nil *http.Response so that callers can handle redirects, authentication, -// etc. -// -// Deprecated: Use Dialer instead. -func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error) { - d := Dialer{ - ReadBufferSize: readBufSize, - WriteBufferSize: writeBufSize, - NetDial: func(net, addr string) (net.Conn, error) { - return netConn, nil - }, - } - return d.Dial(u.String(), requestHeader) -} - -// A Dialer contains options for connecting to WebSocket server. -type Dialer struct { - // NetDial specifies the dial function for creating TCP connections. If - // NetDial is nil, net.Dial is used. - NetDial func(network, addr string) (net.Conn, error) - - // Proxy specifies a function to return a proxy for a given - // Request. If the function returns a non-nil error, the - // request is aborted with the provided error. - // If Proxy is nil or returns a nil *URL, no proxy is used. - Proxy func(*http.Request) (*url.URL, error) - - // TLSClientConfig specifies the TLS configuration to use with tls.Client. - // If nil, the default configuration is used. - TLSClientConfig *tls.Config - - // HandshakeTimeout specifies the duration for the handshake to complete. - HandshakeTimeout time.Duration - - // ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer - // size is zero, then a useful default size is used. The I/O buffer sizes - // do not limit the size of the messages that can be sent or received. - ReadBufferSize, WriteBufferSize int - - // Subprotocols specifies the client's requested subprotocols. - Subprotocols []string - - // EnableCompression specifies if the client should attempt to negotiate - // per message compression (RFC 7692). Setting this value to true does not - // guarantee that compression will be supported. Currently only "no context - // takeover" modes are supported. - EnableCompression bool - - // Jar specifies the cookie jar. - // If Jar is nil, cookies are not sent in requests and ignored - // in responses. - Jar http.CookieJar -} - -var errMalformedURL = errors.New("malformed ws or wss URL") - -// parseURL parses the URL. -// -// This function is a replacement for the standard library url.Parse function. -// In Go 1.4 and earlier, url.Parse loses information from the path. -func parseURL(s string) (*url.URL, error) { - // From the RFC: - // - // ws-URI = "ws:" "//" host [ ":" port ] path [ "?" query ] - // wss-URI = "wss:" "//" host [ ":" port ] path [ "?" query ] - var u url.URL - switch { - case strings.HasPrefix(s, "ws://"): - u.Scheme = "ws" - s = s[len("ws://"):] - case strings.HasPrefix(s, "wss://"): - u.Scheme = "wss" - s = s[len("wss://"):] - default: - return nil, errMalformedURL - } - - if i := strings.Index(s, "?"); i >= 0 { - u.RawQuery = s[i+1:] - s = s[:i] - } - - if i := strings.Index(s, "/"); i >= 0 { - u.Opaque = s[i:] - s = s[:i] - } else { - u.Opaque = "/" - } - - u.Host = s - - if strings.Contains(u.Host, "@") { - // Don't bother parsing user information because user information is - // not allowed in websocket URIs. - return nil, errMalformedURL - } - - return &u, nil -} - -func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) { - hostPort = u.Host - hostNoPort = u.Host - if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") { - hostNoPort = hostNoPort[:i] - } else { - switch u.Scheme { - case "wss": - hostPort += ":443" - case "https": - hostPort += ":443" - default: - hostPort += ":80" - } - } - return hostPort, hostNoPort -} - -// DefaultDialer is a dialer with all fields set to the default zero values. -var DefaultDialer = &Dialer{ - Proxy: http.ProxyFromEnvironment, -} - -// Dial creates a new client connection. Use requestHeader to specify the -// origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie). -// Use the response.Header to get the selected subprotocol -// (Sec-WebSocket-Protocol) and cookies (Set-Cookie). -// -// If the WebSocket handshake fails, ErrBadHandshake is returned along with a -// non-nil *http.Response so that callers can handle redirects, authentication, -// etcetera. The response body may not contain the entire response and does not -// need to be closed by the application. -func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) { - - if d == nil { - d = &Dialer{ - Proxy: http.ProxyFromEnvironment, - } - } - - challengeKey, err := generateChallengeKey() - if err != nil { - return nil, nil, err - } - - u, err := parseURL(urlStr) - if err != nil { - return nil, nil, err - } - - switch u.Scheme { - case "ws": - u.Scheme = "http" - case "wss": - u.Scheme = "https" - default: - return nil, nil, errMalformedURL - } - - if u.User != nil { - // User name and password are not allowed in websocket URIs. - return nil, nil, errMalformedURL - } - - req := &http.Request{ - Method: "GET", - URL: u, - Proto: "HTTP/1.1", - ProtoMajor: 1, - ProtoMinor: 1, - Header: make(http.Header), - Host: u.Host, - } - - // Set the cookies present in the cookie jar of the dialer - if d.Jar != nil { - for _, cookie := range d.Jar.Cookies(u) { - req.AddCookie(cookie) - } - } - - // Set the request headers using the capitalization for names and values in - // RFC examples. Although the capitalization shouldn't matter, there are - // servers that depend on it. The Header.Set method is not used because the - // method canonicalizes the header names. - req.Header["Upgrade"] = []string{"websocket"} - req.Header["Connection"] = []string{"Upgrade"} - req.Header["Sec-WebSocket-Key"] = []string{challengeKey} - req.Header["Sec-WebSocket-Version"] = []string{"13"} - if len(d.Subprotocols) > 0 { - req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.Subprotocols, ", ")} - } - for k, vs := range requestHeader { - switch { - case k == "Host": - if len(vs) > 0 { - req.Host = vs[0] - } - case k == "Upgrade" || - k == "Connection" || - k == "Sec-Websocket-Key" || - k == "Sec-Websocket-Version" || - k == "Sec-Websocket-Extensions" || - (k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0): - return nil, nil, errors.New("websocket: duplicate header not allowed: " + k) - default: - req.Header[k] = vs - } - } - - if d.EnableCompression { - req.Header.Set("Sec-Websocket-Extensions", "permessage-deflate; server_no_context_takeover; client_no_context_takeover") - } - - hostPort, hostNoPort := hostPortNoPort(u) - - var proxyURL *url.URL - // Check wether the proxy method has been configured - if d.Proxy != nil { - proxyURL, err = d.Proxy(req) - } - if err != nil { - return nil, nil, err - } - - var targetHostPort string - if proxyURL != nil { - targetHostPort, _ = hostPortNoPort(proxyURL) - } else { - targetHostPort = hostPort - } - - var deadline time.Time - if d.HandshakeTimeout != 0 { - deadline = time.Now().Add(d.HandshakeTimeout) - } - - netDial := d.NetDial - if netDial == nil { - netDialer := &net.Dialer{Deadline: deadline} - netDial = netDialer.Dial - } - - netConn, err := netDial("tcp", targetHostPort) - if err != nil { - return nil, nil, err - } - - defer func() { - if netConn != nil { - netConn.Close() - } - }() - - if err := netConn.SetDeadline(deadline); err != nil { - return nil, nil, err - } - - if proxyURL != nil { - connectHeader := make(http.Header) - if user := proxyURL.User; user != nil { - proxyUser := user.Username() - if proxyPassword, passwordSet := user.Password(); passwordSet { - credential := base64.StdEncoding.EncodeToString([]byte(proxyUser + ":" + proxyPassword)) - connectHeader.Set("Proxy-Authorization", "Basic "+credential) - } - } - connectReq := &http.Request{ - Method: "CONNECT", - URL: &url.URL{Opaque: hostPort}, - Host: hostPort, - Header: connectHeader, - } - - connectReq.Write(netConn) - - // Read response. - // Okay to use and discard buffered reader here, because - // TLS server will not speak until spoken to. - br := bufio.NewReader(netConn) - resp, err := http.ReadResponse(br, connectReq) - if err != nil { - return nil, nil, err - } - if resp.StatusCode != 200 { - f := strings.SplitN(resp.Status, " ", 2) - return nil, nil, errors.New(f[1]) - } - } - - if u.Scheme == "https" { - cfg := cloneTLSConfig(d.TLSClientConfig) - if cfg.ServerName == "" { - cfg.ServerName = hostNoPort - } - tlsConn := tls.Client(netConn, cfg) - netConn = tlsConn - if err := tlsConn.Handshake(); err != nil { - return nil, nil, err - } - if !cfg.InsecureSkipVerify { - if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil { - return nil, nil, err - } - } - } - - conn := newConn(netConn, false, d.ReadBufferSize, d.WriteBufferSize) - - if err := req.Write(netConn); err != nil { - return nil, nil, err - } - - resp, err := http.ReadResponse(conn.br, req) - if err != nil { - return nil, nil, err - } - - if d.Jar != nil { - if rc := resp.Cookies(); len(rc) > 0 { - d.Jar.SetCookies(u, rc) - } - } - - if resp.StatusCode != 101 || - !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") || - !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") || - resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) { - // Before closing the network connection on return from this - // function, slurp up some of the response to aid application - // debugging. - buf := make([]byte, 1024) - n, _ := io.ReadFull(resp.Body, buf) - resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n])) - return nil, resp, ErrBadHandshake - } - - for _, ext := range parseExtensions(resp.Header) { - if ext[""] != "permessage-deflate" { - continue - } - _, snct := ext["server_no_context_takeover"] - _, cnct := ext["client_no_context_takeover"] - if !snct || !cnct { - return nil, resp, errInvalidCompression - } - conn.newCompressionWriter = compressNoContextTakeover - conn.newDecompressionReader = decompressNoContextTakeover - break - } - - resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{})) - conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol") - - netConn.SetDeadline(time.Time{}) - netConn = nil // to avoid close in defer. - return conn, resp, nil -} diff --git a/vendor/github.com/gorilla/websocket/client_clone.go b/vendor/github.com/gorilla/websocket/client_clone.go deleted file mode 100644 index 4f0d94372..000000000 --- a/vendor/github.com/gorilla/websocket/client_clone.go +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.8 - -package websocket - -import "crypto/tls" - -func cloneTLSConfig(cfg *tls.Config) *tls.Config { - if cfg == nil { - return &tls.Config{} - } - return cfg.Clone() -} diff --git a/vendor/github.com/gorilla/websocket/client_clone_legacy.go b/vendor/github.com/gorilla/websocket/client_clone_legacy.go deleted file mode 100644 index babb007fb..000000000 --- a/vendor/github.com/gorilla/websocket/client_clone_legacy.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.8 - -package websocket - -import "crypto/tls" - -// cloneTLSConfig clones all public fields except the fields -// SessionTicketsDisabled and SessionTicketKey. This avoids copying the -// sync.Mutex in the sync.Once and makes it safe to call cloneTLSConfig on a -// config in active use. -func cloneTLSConfig(cfg *tls.Config) *tls.Config { - if cfg == nil { - return &tls.Config{} - } - return &tls.Config{ - Rand: cfg.Rand, - Time: cfg.Time, - Certificates: cfg.Certificates, - NameToCertificate: cfg.NameToCertificate, - GetCertificate: cfg.GetCertificate, - RootCAs: cfg.RootCAs, - NextProtos: cfg.NextProtos, - ServerName: cfg.ServerName, - ClientAuth: cfg.ClientAuth, - ClientCAs: cfg.ClientCAs, - InsecureSkipVerify: cfg.InsecureSkipVerify, - CipherSuites: cfg.CipherSuites, - PreferServerCipherSuites: cfg.PreferServerCipherSuites, - ClientSessionCache: cfg.ClientSessionCache, - MinVersion: cfg.MinVersion, - MaxVersion: cfg.MaxVersion, - CurvePreferences: cfg.CurvePreferences, - } -} diff --git a/vendor/github.com/gorilla/websocket/compression.go b/vendor/github.com/gorilla/websocket/compression.go deleted file mode 100644 index 813ffb1e8..000000000 --- a/vendor/github.com/gorilla/websocket/compression.go +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package websocket - -import ( - "compress/flate" - "errors" - "io" - "strings" - "sync" -) - -const ( - minCompressionLevel = -2 // flate.HuffmanOnly not defined in Go < 1.6 - maxCompressionLevel = flate.BestCompression - defaultCompressionLevel = 1 -) - -var ( - flateWriterPools [maxCompressionLevel - minCompressionLevel + 1]sync.Pool - flateReaderPool = sync.Pool{New: func() interface{} { - return flate.NewReader(nil) - }} -) - -func decompressNoContextTakeover(r io.Reader) io.ReadCloser { - const tail = - // Add four bytes as specified in RFC - "\x00\x00\xff\xff" + - // Add final block to squelch unexpected EOF error from flate reader. - "\x01\x00\x00\xff\xff" - - fr, _ := flateReaderPool.Get().(io.ReadCloser) - fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil) - return &flateReadWrapper{fr} -} - -func isValidCompressionLevel(level int) bool { - return minCompressionLevel <= level && level <= maxCompressionLevel -} - -func compressNoContextTakeover(w io.WriteCloser, level int) io.WriteCloser { - p := &flateWriterPools[level-minCompressionLevel] - tw := &truncWriter{w: w} - fw, _ := p.Get().(*flate.Writer) - if fw == nil { - fw, _ = flate.NewWriter(tw, level) - } else { - fw.Reset(tw) - } - return &flateWriteWrapper{fw: fw, tw: tw, p: p} -} - -// truncWriter is an io.Writer that writes all but the last four bytes of the -// stream to another io.Writer. -type truncWriter struct { - w io.WriteCloser - n int - p [4]byte -} - -func (w *truncWriter) Write(p []byte) (int, error) { - n := 0 - - // fill buffer first for simplicity. - if w.n < len(w.p) { - n = copy(w.p[w.n:], p) - p = p[n:] - w.n += n - if len(p) == 0 { - return n, nil - } - } - - m := len(p) - if m > len(w.p) { - m = len(w.p) - } - - if nn, err := w.w.Write(w.p[:m]); err != nil { - return n + nn, err - } - - copy(w.p[:], w.p[m:]) - copy(w.p[len(w.p)-m:], p[len(p)-m:]) - nn, err := w.w.Write(p[:len(p)-m]) - return n + nn, err -} - -type flateWriteWrapper struct { - fw *flate.Writer - tw *truncWriter - p *sync.Pool -} - -func (w *flateWriteWrapper) Write(p []byte) (int, error) { - if w.fw == nil { - return 0, errWriteClosed - } - return w.fw.Write(p) -} - -func (w *flateWriteWrapper) Close() error { - if w.fw == nil { - return errWriteClosed - } - err1 := w.fw.Flush() - w.p.Put(w.fw) - w.fw = nil - if w.tw.p != [4]byte{0, 0, 0xff, 0xff} { - return errors.New("websocket: internal error, unexpected bytes at end of flate stream") - } - err2 := w.tw.w.Close() - if err1 != nil { - return err1 - } - return err2 -} - -type flateReadWrapper struct { - fr io.ReadCloser -} - -func (r *flateReadWrapper) Read(p []byte) (int, error) { - if r.fr == nil { - return 0, io.ErrClosedPipe - } - n, err := r.fr.Read(p) - if err == io.EOF { - // Preemptively place the reader back in the pool. This helps with - // scenarios where the application does not call NextReader() soon after - // this final read. - r.Close() - } - return n, err -} - -func (r *flateReadWrapper) Close() error { - if r.fr == nil { - return io.ErrClosedPipe - } - err := r.fr.Close() - flateReaderPool.Put(r.fr) - r.fr = nil - return err -} diff --git a/vendor/github.com/gorilla/websocket/conn.go b/vendor/github.com/gorilla/websocket/conn.go deleted file mode 100644 index 97e1dbacb..000000000 --- a/vendor/github.com/gorilla/websocket/conn.go +++ /dev/null @@ -1,1149 +0,0 @@ -// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package websocket - -import ( - "bufio" - "encoding/binary" - "errors" - "io" - "io/ioutil" - "math/rand" - "net" - "strconv" - "sync" - "time" - "unicode/utf8" -) - -const ( - // Frame header byte 0 bits from Section 5.2 of RFC 6455 - finalBit = 1 << 7 - rsv1Bit = 1 << 6 - rsv2Bit = 1 << 5 - rsv3Bit = 1 << 4 - - // Frame header byte 1 bits from Section 5.2 of RFC 6455 - maskBit = 1 << 7 - - maxFrameHeaderSize = 2 + 8 + 4 // Fixed header + length + mask - maxControlFramePayloadSize = 125 - - writeWait = time.Second - - defaultReadBufferSize = 4096 - defaultWriteBufferSize = 4096 - - continuationFrame = 0 - noFrame = -1 -) - -// Close codes defined in RFC 6455, section 11.7. -const ( - CloseNormalClosure = 1000 - CloseGoingAway = 1001 - CloseProtocolError = 1002 - CloseUnsupportedData = 1003 - CloseNoStatusReceived = 1005 - CloseAbnormalClosure = 1006 - CloseInvalidFramePayloadData = 1007 - ClosePolicyViolation = 1008 - CloseMessageTooBig = 1009 - CloseMandatoryExtension = 1010 - CloseInternalServerErr = 1011 - CloseServiceRestart = 1012 - CloseTryAgainLater = 1013 - CloseTLSHandshake = 1015 -) - -// The message types are defined in RFC 6455, section 11.8. -const ( - // TextMessage denotes a text data message. The text message payload is - // interpreted as UTF-8 encoded text data. - TextMessage = 1 - - // BinaryMessage denotes a binary data message. - BinaryMessage = 2 - - // CloseMessage denotes a close control message. The optional message - // payload contains a numeric code and text. Use the FormatCloseMessage - // function to format a close message payload. - CloseMessage = 8 - - // PingMessage denotes a ping control message. The optional message payload - // is UTF-8 encoded text. - PingMessage = 9 - - // PongMessage denotes a ping control message. The optional message payload - // is UTF-8 encoded text. - PongMessage = 10 -) - -// ErrCloseSent is returned when the application writes a message to the -// connection after sending a close message. -var ErrCloseSent = errors.New("websocket: close sent") - -// ErrReadLimit is returned when reading a message that is larger than the -// read limit set for the connection. -var ErrReadLimit = errors.New("websocket: read limit exceeded") - -// netError satisfies the net Error interface. -type netError struct { - msg string - temporary bool - timeout bool -} - -func (e *netError) Error() string { return e.msg } -func (e *netError) Temporary() bool { return e.temporary } -func (e *netError) Timeout() bool { return e.timeout } - -// CloseError represents close frame. -type CloseError struct { - - // Code is defined in RFC 6455, section 11.7. - Code int - - // Text is the optional text payload. - Text string -} - -func (e *CloseError) Error() string { - s := []byte("websocket: close ") - s = strconv.AppendInt(s, int64(e.Code), 10) - switch e.Code { - case CloseNormalClosure: - s = append(s, " (normal)"...) - case CloseGoingAway: - s = append(s, " (going away)"...) - case CloseProtocolError: - s = append(s, " (protocol error)"...) - case CloseUnsupportedData: - s = append(s, " (unsupported data)"...) - case CloseNoStatusReceived: - s = append(s, " (no status)"...) - case CloseAbnormalClosure: - s = append(s, " (abnormal closure)"...) - case CloseInvalidFramePayloadData: - s = append(s, " (invalid payload data)"...) - case ClosePolicyViolation: - s = append(s, " (policy violation)"...) - case CloseMessageTooBig: - s = append(s, " (message too big)"...) - case CloseMandatoryExtension: - s = append(s, " (mandatory extension missing)"...) - case CloseInternalServerErr: - s = append(s, " (internal server error)"...) - case CloseTLSHandshake: - s = append(s, " (TLS handshake error)"...) - } - if e.Text != "" { - s = append(s, ": "...) - s = append(s, e.Text...) - } - return string(s) -} - -// IsCloseError returns boolean indicating whether the error is a *CloseError -// with one of the specified codes. -func IsCloseError(err error, codes ...int) bool { - if e, ok := err.(*CloseError); ok { - for _, code := range codes { - if e.Code == code { - return true - } - } - } - return false -} - -// IsUnexpectedCloseError returns boolean indicating whether the error is a -// *CloseError with a code not in the list of expected codes. -func IsUnexpectedCloseError(err error, expectedCodes ...int) bool { - if e, ok := err.(*CloseError); ok { - for _, code := range expectedCodes { - if e.Code == code { - return false - } - } - return true - } - return false -} - -var ( - errWriteTimeout = &netError{msg: "websocket: write timeout", timeout: true, temporary: true} - errUnexpectedEOF = &CloseError{Code: CloseAbnormalClosure, Text: io.ErrUnexpectedEOF.Error()} - errBadWriteOpCode = errors.New("websocket: bad write message type") - errWriteClosed = errors.New("websocket: write closed") - errInvalidControlFrame = errors.New("websocket: invalid control frame") -) - -func newMaskKey() [4]byte { - n := rand.Uint32() - return [4]byte{byte(n), byte(n >> 8), byte(n >> 16), byte(n >> 24)} -} - -func hideTempErr(err error) error { - if e, ok := err.(net.Error); ok && e.Temporary() { - err = &netError{msg: e.Error(), timeout: e.Timeout()} - } - return err -} - -func isControl(frameType int) bool { - return frameType == CloseMessage || frameType == PingMessage || frameType == PongMessage -} - -func isData(frameType int) bool { - return frameType == TextMessage || frameType == BinaryMessage -} - -var validReceivedCloseCodes = map[int]bool{ - // see http://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number - - CloseNormalClosure: true, - CloseGoingAway: true, - CloseProtocolError: true, - CloseUnsupportedData: true, - CloseNoStatusReceived: false, - CloseAbnormalClosure: false, - CloseInvalidFramePayloadData: true, - ClosePolicyViolation: true, - CloseMessageTooBig: true, - CloseMandatoryExtension: true, - CloseInternalServerErr: true, - CloseServiceRestart: true, - CloseTryAgainLater: true, - CloseTLSHandshake: false, -} - -func isValidReceivedCloseCode(code int) bool { - return validReceivedCloseCodes[code] || (code >= 3000 && code <= 4999) -} - -// The Conn type represents a WebSocket connection. -type Conn struct { - conn net.Conn - isServer bool - subprotocol string - - // Write fields - mu chan bool // used as mutex to protect write to conn - writeBuf []byte // frame is constructed in this buffer. - writeDeadline time.Time - writer io.WriteCloser // the current writer returned to the application - isWriting bool // for best-effort concurrent write detection - - writeErrMu sync.Mutex - writeErr error - - enableWriteCompression bool - compressionLevel int - newCompressionWriter func(io.WriteCloser, int) io.WriteCloser - - // Read fields - reader io.ReadCloser // the current reader returned to the application - readErr error - br *bufio.Reader - readRemaining int64 // bytes remaining in current frame. - readFinal bool // true the current message has more frames. - readLength int64 // Message size. - readLimit int64 // Maximum message size. - readMaskPos int - readMaskKey [4]byte - handlePong func(string) error - handlePing func(string) error - handleClose func(int, string) error - readErrCount int - messageReader *messageReader // the current low-level reader - - readDecompress bool // whether last read frame had RSV1 set - newDecompressionReader func(io.Reader) io.ReadCloser -} - -func newConn(conn net.Conn, isServer bool, readBufferSize, writeBufferSize int) *Conn { - return newConnBRW(conn, isServer, readBufferSize, writeBufferSize, nil) -} - -type writeHook struct { - p []byte -} - -func (wh *writeHook) Write(p []byte) (int, error) { - wh.p = p - return len(p), nil -} - -func newConnBRW(conn net.Conn, isServer bool, readBufferSize, writeBufferSize int, brw *bufio.ReadWriter) *Conn { - mu := make(chan bool, 1) - mu <- true - - var br *bufio.Reader - if readBufferSize == 0 && brw != nil && brw.Reader != nil { - // Reuse the supplied bufio.Reader if the buffer has a useful size. - // This code assumes that peek on a reader returns - // bufio.Reader.buf[:0]. - brw.Reader.Reset(conn) - if p, err := brw.Reader.Peek(0); err == nil && cap(p) >= 256 { - br = brw.Reader - } - } - if br == nil { - if readBufferSize == 0 { - readBufferSize = defaultReadBufferSize - } - if readBufferSize < maxControlFramePayloadSize { - readBufferSize = maxControlFramePayloadSize - } - br = bufio.NewReaderSize(conn, readBufferSize) - } - - var writeBuf []byte - if writeBufferSize == 0 && brw != nil && brw.Writer != nil { - // Use the bufio.Writer's buffer if the buffer has a useful size. This - // code assumes that bufio.Writer.buf[:1] is passed to the - // bufio.Writer's underlying writer. - var wh writeHook - brw.Writer.Reset(&wh) - brw.Writer.WriteByte(0) - brw.Flush() - if cap(wh.p) >= maxFrameHeaderSize+256 { - writeBuf = wh.p[:cap(wh.p)] - } - } - - if writeBuf == nil { - if writeBufferSize == 0 { - writeBufferSize = defaultWriteBufferSize - } - writeBuf = make([]byte, writeBufferSize+maxFrameHeaderSize) - } - - c := &Conn{ - isServer: isServer, - br: br, - conn: conn, - mu: mu, - readFinal: true, - writeBuf: writeBuf, - enableWriteCompression: true, - compressionLevel: defaultCompressionLevel, - } - c.SetCloseHandler(nil) - c.SetPingHandler(nil) - c.SetPongHandler(nil) - return c -} - -// Subprotocol returns the negotiated protocol for the connection. -func (c *Conn) Subprotocol() string { - return c.subprotocol -} - -// Close closes the underlying network connection without sending or waiting for a close frame. -func (c *Conn) Close() error { - return c.conn.Close() -} - -// LocalAddr returns the local network address. -func (c *Conn) LocalAddr() net.Addr { - return c.conn.LocalAddr() -} - -// RemoteAddr returns the remote network address. -func (c *Conn) RemoteAddr() net.Addr { - return c.conn.RemoteAddr() -} - -// Write methods - -func (c *Conn) writeFatal(err error) error { - err = hideTempErr(err) - c.writeErrMu.Lock() - if c.writeErr == nil { - c.writeErr = err - } - c.writeErrMu.Unlock() - return err -} - -func (c *Conn) write(frameType int, deadline time.Time, bufs ...[]byte) error { - <-c.mu - defer func() { c.mu <- true }() - - c.writeErrMu.Lock() - err := c.writeErr - c.writeErrMu.Unlock() - if err != nil { - return err - } - - c.conn.SetWriteDeadline(deadline) - for _, buf := range bufs { - if len(buf) > 0 { - _, err := c.conn.Write(buf) - if err != nil { - return c.writeFatal(err) - } - } - } - - if frameType == CloseMessage { - c.writeFatal(ErrCloseSent) - } - return nil -} - -// WriteControl writes a control message with the given deadline. The allowed -// message types are CloseMessage, PingMessage and PongMessage. -func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) error { - if !isControl(messageType) { - return errBadWriteOpCode - } - if len(data) > maxControlFramePayloadSize { - return errInvalidControlFrame - } - - b0 := byte(messageType) | finalBit - b1 := byte(len(data)) - if !c.isServer { - b1 |= maskBit - } - - buf := make([]byte, 0, maxFrameHeaderSize+maxControlFramePayloadSize) - buf = append(buf, b0, b1) - - if c.isServer { - buf = append(buf, data...) - } else { - key := newMaskKey() - buf = append(buf, key[:]...) - buf = append(buf, data...) - maskBytes(key, 0, buf[6:]) - } - - d := time.Hour * 1000 - if !deadline.IsZero() { - d = deadline.Sub(time.Now()) - if d < 0 { - return errWriteTimeout - } - } - - timer := time.NewTimer(d) - select { - case <-c.mu: - timer.Stop() - case <-timer.C: - return errWriteTimeout - } - defer func() { c.mu <- true }() - - c.writeErrMu.Lock() - err := c.writeErr - c.writeErrMu.Unlock() - if err != nil { - return err - } - - c.conn.SetWriteDeadline(deadline) - _, err = c.conn.Write(buf) - if err != nil { - return c.writeFatal(err) - } - if messageType == CloseMessage { - c.writeFatal(ErrCloseSent) - } - return err -} - -func (c *Conn) prepWrite(messageType int) error { - // Close previous writer if not already closed by the application. It's - // probably better to return an error in this situation, but we cannot - // change this without breaking existing applications. - if c.writer != nil { - c.writer.Close() - c.writer = nil - } - - if !isControl(messageType) && !isData(messageType) { - return errBadWriteOpCode - } - - c.writeErrMu.Lock() - err := c.writeErr - c.writeErrMu.Unlock() - return err -} - -// NextWriter returns a writer for the next message to send. The writer's Close -// method flushes the complete message to the network. -// -// There can be at most one open writer on a connection. NextWriter closes the -// previous writer if the application has not already done so. -func (c *Conn) NextWriter(messageType int) (io.WriteCloser, error) { - if err := c.prepWrite(messageType); err != nil { - return nil, err - } - - mw := &messageWriter{ - c: c, - frameType: messageType, - pos: maxFrameHeaderSize, - } - c.writer = mw - if c.newCompressionWriter != nil && c.enableWriteCompression && isData(messageType) { - w := c.newCompressionWriter(c.writer, c.compressionLevel) - mw.compress = true - c.writer = w - } - return c.writer, nil -} - -type messageWriter struct { - c *Conn - compress bool // whether next call to flushFrame should set RSV1 - pos int // end of data in writeBuf. - frameType int // type of the current frame. - err error -} - -func (w *messageWriter) fatal(err error) error { - if w.err != nil { - w.err = err - w.c.writer = nil - } - return err -} - -// flushFrame writes buffered data and extra as a frame to the network. The -// final argument indicates that this is the last frame in the message. -func (w *messageWriter) flushFrame(final bool, extra []byte) error { - c := w.c - length := w.pos - maxFrameHeaderSize + len(extra) - - // Check for invalid control frames. - if isControl(w.frameType) && - (!final || length > maxControlFramePayloadSize) { - return w.fatal(errInvalidControlFrame) - } - - b0 := byte(w.frameType) - if final { - b0 |= finalBit - } - if w.compress { - b0 |= rsv1Bit - } - w.compress = false - - b1 := byte(0) - if !c.isServer { - b1 |= maskBit - } - - // Assume that the frame starts at beginning of c.writeBuf. - framePos := 0 - if c.isServer { - // Adjust up if mask not included in the header. - framePos = 4 - } - - switch { - case length >= 65536: - c.writeBuf[framePos] = b0 - c.writeBuf[framePos+1] = b1 | 127 - binary.BigEndian.PutUint64(c.writeBuf[framePos+2:], uint64(length)) - case length > 125: - framePos += 6 - c.writeBuf[framePos] = b0 - c.writeBuf[framePos+1] = b1 | 126 - binary.BigEndian.PutUint16(c.writeBuf[framePos+2:], uint16(length)) - default: - framePos += 8 - c.writeBuf[framePos] = b0 - c.writeBuf[framePos+1] = b1 | byte(length) - } - - if !c.isServer { - key := newMaskKey() - copy(c.writeBuf[maxFrameHeaderSize-4:], key[:]) - maskBytes(key, 0, c.writeBuf[maxFrameHeaderSize:w.pos]) - if len(extra) > 0 { - return c.writeFatal(errors.New("websocket: internal error, extra used in client mode")) - } - } - - // Write the buffers to the connection with best-effort detection of - // concurrent writes. See the concurrency section in the package - // documentation for more info. - - if c.isWriting { - panic("concurrent write to websocket connection") - } - c.isWriting = true - - err := c.write(w.frameType, c.writeDeadline, c.writeBuf[framePos:w.pos], extra) - - if !c.isWriting { - panic("concurrent write to websocket connection") - } - c.isWriting = false - - if err != nil { - return w.fatal(err) - } - - if final { - c.writer = nil - return nil - } - - // Setup for next frame. - w.pos = maxFrameHeaderSize - w.frameType = continuationFrame - return nil -} - -func (w *messageWriter) ncopy(max int) (int, error) { - n := len(w.c.writeBuf) - w.pos - if n <= 0 { - if err := w.flushFrame(false, nil); err != nil { - return 0, err - } - n = len(w.c.writeBuf) - w.pos - } - if n > max { - n = max - } - return n, nil -} - -func (w *messageWriter) Write(p []byte) (int, error) { - if w.err != nil { - return 0, w.err - } - - if len(p) > 2*len(w.c.writeBuf) && w.c.isServer { - // Don't buffer large messages. - err := w.flushFrame(false, p) - if err != nil { - return 0, err - } - return len(p), nil - } - - nn := len(p) - for len(p) > 0 { - n, err := w.ncopy(len(p)) - if err != nil { - return 0, err - } - copy(w.c.writeBuf[w.pos:], p[:n]) - w.pos += n - p = p[n:] - } - return nn, nil -} - -func (w *messageWriter) WriteString(p string) (int, error) { - if w.err != nil { - return 0, w.err - } - - nn := len(p) - for len(p) > 0 { - n, err := w.ncopy(len(p)) - if err != nil { - return 0, err - } - copy(w.c.writeBuf[w.pos:], p[:n]) - w.pos += n - p = p[n:] - } - return nn, nil -} - -func (w *messageWriter) ReadFrom(r io.Reader) (nn int64, err error) { - if w.err != nil { - return 0, w.err - } - for { - if w.pos == len(w.c.writeBuf) { - err = w.flushFrame(false, nil) - if err != nil { - break - } - } - var n int - n, err = r.Read(w.c.writeBuf[w.pos:]) - w.pos += n - nn += int64(n) - if err != nil { - if err == io.EOF { - err = nil - } - break - } - } - return nn, err -} - -func (w *messageWriter) Close() error { - if w.err != nil { - return w.err - } - if err := w.flushFrame(true, nil); err != nil { - return err - } - w.err = errWriteClosed - return nil -} - -// WritePreparedMessage writes prepared message into connection. -func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error { - frameType, frameData, err := pm.frame(prepareKey{ - isServer: c.isServer, - compress: c.newCompressionWriter != nil && c.enableWriteCompression && isData(pm.messageType), - compressionLevel: c.compressionLevel, - }) - if err != nil { - return err - } - if c.isWriting { - panic("concurrent write to websocket connection") - } - c.isWriting = true - err = c.write(frameType, c.writeDeadline, frameData, nil) - if !c.isWriting { - panic("concurrent write to websocket connection") - } - c.isWriting = false - return err -} - -// WriteMessage is a helper method for getting a writer using NextWriter, -// writing the message and closing the writer. -func (c *Conn) WriteMessage(messageType int, data []byte) error { - - if c.isServer && (c.newCompressionWriter == nil || !c.enableWriteCompression) { - // Fast path with no allocations and single frame. - - if err := c.prepWrite(messageType); err != nil { - return err - } - mw := messageWriter{c: c, frameType: messageType, pos: maxFrameHeaderSize} - n := copy(c.writeBuf[mw.pos:], data) - mw.pos += n - data = data[n:] - return mw.flushFrame(true, data) - } - - w, err := c.NextWriter(messageType) - if err != nil { - return err - } - if _, err = w.Write(data); err != nil { - return err - } - return w.Close() -} - -// SetWriteDeadline sets the write deadline on the underlying network -// connection. After a write has timed out, the websocket state is corrupt and -// all future writes will return an error. A zero value for t means writes will -// not time out. -func (c *Conn) SetWriteDeadline(t time.Time) error { - c.writeDeadline = t - return nil -} - -// Read methods - -func (c *Conn) advanceFrame() (int, error) { - - // 1. Skip remainder of previous frame. - - if c.readRemaining > 0 { - if _, err := io.CopyN(ioutil.Discard, c.br, c.readRemaining); err != nil { - return noFrame, err - } - } - - // 2. Read and parse first two bytes of frame header. - - p, err := c.read(2) - if err != nil { - return noFrame, err - } - - final := p[0]&finalBit != 0 - frameType := int(p[0] & 0xf) - mask := p[1]&maskBit != 0 - c.readRemaining = int64(p[1] & 0x7f) - - c.readDecompress = false - if c.newDecompressionReader != nil && (p[0]&rsv1Bit) != 0 { - c.readDecompress = true - p[0] &^= rsv1Bit - } - - if rsv := p[0] & (rsv1Bit | rsv2Bit | rsv3Bit); rsv != 0 { - return noFrame, c.handleProtocolError("unexpected reserved bits 0x" + strconv.FormatInt(int64(rsv), 16)) - } - - switch frameType { - case CloseMessage, PingMessage, PongMessage: - if c.readRemaining > maxControlFramePayloadSize { - return noFrame, c.handleProtocolError("control frame length > 125") - } - if !final { - return noFrame, c.handleProtocolError("control frame not final") - } - case TextMessage, BinaryMessage: - if !c.readFinal { - return noFrame, c.handleProtocolError("message start before final message frame") - } - c.readFinal = final - case continuationFrame: - if c.readFinal { - return noFrame, c.handleProtocolError("continuation after final message frame") - } - c.readFinal = final - default: - return noFrame, c.handleProtocolError("unknown opcode " + strconv.Itoa(frameType)) - } - - // 3. Read and parse frame length. - - switch c.readRemaining { - case 126: - p, err := c.read(2) - if err != nil { - return noFrame, err - } - c.readRemaining = int64(binary.BigEndian.Uint16(p)) - case 127: - p, err := c.read(8) - if err != nil { - return noFrame, err - } - c.readRemaining = int64(binary.BigEndian.Uint64(p)) - } - - // 4. Handle frame masking. - - if mask != c.isServer { - return noFrame, c.handleProtocolError("incorrect mask flag") - } - - if mask { - c.readMaskPos = 0 - p, err := c.read(len(c.readMaskKey)) - if err != nil { - return noFrame, err - } - copy(c.readMaskKey[:], p) - } - - // 5. For text and binary messages, enforce read limit and return. - - if frameType == continuationFrame || frameType == TextMessage || frameType == BinaryMessage { - - c.readLength += c.readRemaining - if c.readLimit > 0 && c.readLength > c.readLimit { - c.WriteControl(CloseMessage, FormatCloseMessage(CloseMessageTooBig, ""), time.Now().Add(writeWait)) - return noFrame, ErrReadLimit - } - - return frameType, nil - } - - // 6. Read control frame payload. - - var payload []byte - if c.readRemaining > 0 { - payload, err = c.read(int(c.readRemaining)) - c.readRemaining = 0 - if err != nil { - return noFrame, err - } - if c.isServer { - maskBytes(c.readMaskKey, 0, payload) - } - } - - // 7. Process control frame payload. - - switch frameType { - case PongMessage: - if err := c.handlePong(string(payload)); err != nil { - return noFrame, err - } - case PingMessage: - if err := c.handlePing(string(payload)); err != nil { - return noFrame, err - } - case CloseMessage: - closeCode := CloseNoStatusReceived - closeText := "" - if len(payload) >= 2 { - closeCode = int(binary.BigEndian.Uint16(payload)) - if !isValidReceivedCloseCode(closeCode) { - return noFrame, c.handleProtocolError("invalid close code") - } - closeText = string(payload[2:]) - if !utf8.ValidString(closeText) { - return noFrame, c.handleProtocolError("invalid utf8 payload in close frame") - } - } - if err := c.handleClose(closeCode, closeText); err != nil { - return noFrame, err - } - return noFrame, &CloseError{Code: closeCode, Text: closeText} - } - - return frameType, nil -} - -func (c *Conn) handleProtocolError(message string) error { - c.WriteControl(CloseMessage, FormatCloseMessage(CloseProtocolError, message), time.Now().Add(writeWait)) - return errors.New("websocket: " + message) -} - -// NextReader returns the next data message received from the peer. The -// returned messageType is either TextMessage or BinaryMessage. -// -// There can be at most one open reader on a connection. NextReader discards -// the previous message if the application has not already consumed it. -// -// Applications must break out of the application's read loop when this method -// returns a non-nil error value. Errors returned from this method are -// permanent. Once this method returns a non-nil error, all subsequent calls to -// this method return the same error. -func (c *Conn) NextReader() (messageType int, r io.Reader, err error) { - // Close previous reader, only relevant for decompression. - if c.reader != nil { - c.reader.Close() - c.reader = nil - } - - c.messageReader = nil - c.readLength = 0 - - for c.readErr == nil { - frameType, err := c.advanceFrame() - if err != nil { - c.readErr = hideTempErr(err) - break - } - if frameType == TextMessage || frameType == BinaryMessage { - c.messageReader = &messageReader{c} - c.reader = c.messageReader - if c.readDecompress { - c.reader = c.newDecompressionReader(c.reader) - } - return frameType, c.reader, nil - } - } - - // Applications that do handle the error returned from this method spin in - // tight loop on connection failure. To help application developers detect - // this error, panic on repeated reads to the failed connection. - c.readErrCount++ - if c.readErrCount >= 1000 { - panic("repeated read on failed websocket connection") - } - - return noFrame, nil, c.readErr -} - -type messageReader struct{ c *Conn } - -func (r *messageReader) Read(b []byte) (int, error) { - c := r.c - if c.messageReader != r { - return 0, io.EOF - } - - for c.readErr == nil { - - if c.readRemaining > 0 { - if int64(len(b)) > c.readRemaining { - b = b[:c.readRemaining] - } - n, err := c.br.Read(b) - c.readErr = hideTempErr(err) - if c.isServer { - c.readMaskPos = maskBytes(c.readMaskKey, c.readMaskPos, b[:n]) - } - c.readRemaining -= int64(n) - if c.readRemaining > 0 && c.readErr == io.EOF { - c.readErr = errUnexpectedEOF - } - return n, c.readErr - } - - if c.readFinal { - c.messageReader = nil - return 0, io.EOF - } - - frameType, err := c.advanceFrame() - switch { - case err != nil: - c.readErr = hideTempErr(err) - case frameType == TextMessage || frameType == BinaryMessage: - c.readErr = errors.New("websocket: internal error, unexpected text or binary in Reader") - } - } - - err := c.readErr - if err == io.EOF && c.messageReader == r { - err = errUnexpectedEOF - } - return 0, err -} - -func (r *messageReader) Close() error { - return nil -} - -// ReadMessage is a helper method for getting a reader using NextReader and -// reading from that reader to a buffer. -func (c *Conn) ReadMessage() (messageType int, p []byte, err error) { - var r io.Reader - messageType, r, err = c.NextReader() - if err != nil { - return messageType, nil, err - } - p, err = ioutil.ReadAll(r) - return messageType, p, err -} - -// SetReadDeadline sets the read deadline on the underlying network connection. -// After a read has timed out, the websocket connection state is corrupt and -// all future reads will return an error. A zero value for t means reads will -// not time out. -func (c *Conn) SetReadDeadline(t time.Time) error { - return c.conn.SetReadDeadline(t) -} - -// SetReadLimit sets the maximum size for a message read from the peer. If a -// message exceeds the limit, the connection sends a close frame to the peer -// and returns ErrReadLimit to the application. -func (c *Conn) SetReadLimit(limit int64) { - c.readLimit = limit -} - -// CloseHandler returns the current close handler -func (c *Conn) CloseHandler() func(code int, text string) error { - return c.handleClose -} - -// SetCloseHandler sets the handler for close messages received from the peer. -// The code argument to h is the received close code or CloseNoStatusReceived -// if the close message is empty. The default close handler sends a close frame -// back to the peer. -// -// The application must read the connection to process close messages as -// described in the section on Control Frames above. -// -// The connection read methods return a CloseError when a close frame is -// received. Most applications should handle close messages as part of their -// normal error handling. Applications should only set a close handler when the -// application must perform some action before sending a close frame back to -// the peer. -func (c *Conn) SetCloseHandler(h func(code int, text string) error) { - if h == nil { - h = func(code int, text string) error { - message := []byte{} - if code != CloseNoStatusReceived { - message = FormatCloseMessage(code, "") - } - c.WriteControl(CloseMessage, message, time.Now().Add(writeWait)) - return nil - } - } - c.handleClose = h -} - -// PingHandler returns the current ping handler -func (c *Conn) PingHandler() func(appData string) error { - return c.handlePing -} - -// SetPingHandler sets the handler for ping messages received from the peer. -// The appData argument to h is the PING frame application data. The default -// ping handler sends a pong to the peer. -// -// The application must read the connection to process ping messages as -// described in the section on Control Frames above. -func (c *Conn) SetPingHandler(h func(appData string) error) { - if h == nil { - h = func(message string) error { - err := c.WriteControl(PongMessage, []byte(message), time.Now().Add(writeWait)) - if err == ErrCloseSent { - return nil - } else if e, ok := err.(net.Error); ok && e.Temporary() { - return nil - } - return err - } - } - c.handlePing = h -} - -// PongHandler returns the current pong handler -func (c *Conn) PongHandler() func(appData string) error { - return c.handlePong -} - -// SetPongHandler sets the handler for pong messages received from the peer. -// The appData argument to h is the PONG frame application data. The default -// pong handler does nothing. -// -// The application must read the connection to process ping messages as -// described in the section on Control Frames above. -func (c *Conn) SetPongHandler(h func(appData string) error) { - if h == nil { - h = func(string) error { return nil } - } - c.handlePong = h -} - -// UnderlyingConn returns the internal net.Conn. This can be used to further -// modifications to connection specific flags. -func (c *Conn) UnderlyingConn() net.Conn { - return c.conn -} - -// EnableWriteCompression enables and disables write compression of -// subsequent text and binary messages. This function is a noop if -// compression was not negotiated with the peer. -func (c *Conn) EnableWriteCompression(enable bool) { - c.enableWriteCompression = enable -} - -// SetCompressionLevel sets the flate compression level for subsequent text and -// binary messages. This function is a noop if compression was not negotiated -// with the peer. See the compress/flate package for a description of -// compression levels. -func (c *Conn) SetCompressionLevel(level int) error { - if !isValidCompressionLevel(level) { - return errors.New("websocket: invalid compression level") - } - c.compressionLevel = level - return nil -} - -// FormatCloseMessage formats closeCode and text as a WebSocket close message. -func FormatCloseMessage(closeCode int, text string) []byte { - buf := make([]byte, 2+len(text)) - binary.BigEndian.PutUint16(buf, uint16(closeCode)) - copy(buf[2:], text) - return buf -} diff --git a/vendor/github.com/gorilla/websocket/conn_read.go b/vendor/github.com/gorilla/websocket/conn_read.go deleted file mode 100644 index 1ea15059e..000000000 --- a/vendor/github.com/gorilla/websocket/conn_read.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.5 - -package websocket - -import "io" - -func (c *Conn) read(n int) ([]byte, error) { - p, err := c.br.Peek(n) - if err == io.EOF { - err = errUnexpectedEOF - } - c.br.Discard(len(p)) - return p, err -} diff --git a/vendor/github.com/gorilla/websocket/conn_read_legacy.go b/vendor/github.com/gorilla/websocket/conn_read_legacy.go deleted file mode 100644 index 018541cf6..000000000 --- a/vendor/github.com/gorilla/websocket/conn_read_legacy.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.5 - -package websocket - -import "io" - -func (c *Conn) read(n int) ([]byte, error) { - p, err := c.br.Peek(n) - if err == io.EOF { - err = errUnexpectedEOF - } - if len(p) > 0 { - // advance over the bytes just read - io.ReadFull(c.br, p) - } - return p, err -} diff --git a/vendor/github.com/gorilla/websocket/doc.go b/vendor/github.com/gorilla/websocket/doc.go deleted file mode 100644 index e291a952c..000000000 --- a/vendor/github.com/gorilla/websocket/doc.go +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package websocket implements the WebSocket protocol defined in RFC 6455. -// -// Overview -// -// The Conn type represents a WebSocket connection. A server application uses -// the Upgrade function from an Upgrader object with a HTTP request handler -// to get a pointer to a Conn: -// -// var upgrader = websocket.Upgrader{ -// ReadBufferSize: 1024, -// WriteBufferSize: 1024, -// } -// -// func handler(w http.ResponseWriter, r *http.Request) { -// conn, err := upgrader.Upgrade(w, r, nil) -// if err != nil { -// log.Println(err) -// return -// } -// ... Use conn to send and receive messages. -// } -// -// Call the connection's WriteMessage and ReadMessage methods to send and -// receive messages as a slice of bytes. This snippet of code shows how to echo -// messages using these methods: -// -// for { -// messageType, p, err := conn.ReadMessage() -// if err != nil { -// return -// } -// if err = conn.WriteMessage(messageType, p); err != nil { -// return err -// } -// } -// -// In above snippet of code, p is a []byte and messageType is an int with value -// websocket.BinaryMessage or websocket.TextMessage. -// -// An application can also send and receive messages using the io.WriteCloser -// and io.Reader interfaces. To send a message, call the connection NextWriter -// method to get an io.WriteCloser, write the message to the writer and close -// the writer when done. To receive a message, call the connection NextReader -// method to get an io.Reader and read until io.EOF is returned. This snippet -// shows how to echo messages using the NextWriter and NextReader methods: -// -// for { -// messageType, r, err := conn.NextReader() -// if err != nil { -// return -// } -// w, err := conn.NextWriter(messageType) -// if err != nil { -// return err -// } -// if _, err := io.Copy(w, r); err != nil { -// return err -// } -// if err := w.Close(); err != nil { -// return err -// } -// } -// -// Data Messages -// -// The WebSocket protocol distinguishes between text and binary data messages. -// Text messages are interpreted as UTF-8 encoded text. The interpretation of -// binary messages is left to the application. -// -// This package uses the TextMessage and BinaryMessage integer constants to -// identify the two data message types. The ReadMessage and NextReader methods -// return the type of the received message. The messageType argument to the -// WriteMessage and NextWriter methods specifies the type of a sent message. -// -// It is the application's responsibility to ensure that text messages are -// valid UTF-8 encoded text. -// -// Control Messages -// -// The WebSocket protocol defines three types of control messages: close, ping -// and pong. Call the connection WriteControl, WriteMessage or NextWriter -// methods to send a control message to the peer. -// -// Connections handle received close messages by sending a close message to the -// peer and returning a *CloseError from the the NextReader, ReadMessage or the -// message Read method. -// -// Connections handle received ping and pong messages by invoking callback -// functions set with SetPingHandler and SetPongHandler methods. The callback -// functions are called from the NextReader, ReadMessage and the message Read -// methods. -// -// The default ping handler sends a pong to the peer. The application's reading -// goroutine can block for a short time while the handler writes the pong data -// to the connection. -// -// The application must read the connection to process ping, pong and close -// messages sent from the peer. If the application is not otherwise interested -// in messages from the peer, then the application should start a goroutine to -// read and discard messages from the peer. A simple example is: -// -// func readLoop(c *websocket.Conn) { -// for { -// if _, _, err := c.NextReader(); err != nil { -// c.Close() -// break -// } -// } -// } -// -// Concurrency -// -// Connections support one concurrent reader and one concurrent writer. -// -// Applications are responsible for ensuring that no more than one goroutine -// calls the write methods (NextWriter, SetWriteDeadline, WriteMessage, -// WriteJSON, EnableWriteCompression, SetCompressionLevel) concurrently and -// that no more than one goroutine calls the read methods (NextReader, -// SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPingHandler) -// concurrently. -// -// The Close and WriteControl methods can be called concurrently with all other -// methods. -// -// Origin Considerations -// -// Web browsers allow Javascript applications to open a WebSocket connection to -// any host. It's up to the server to enforce an origin policy using the Origin -// request header sent by the browser. -// -// The Upgrader calls the function specified in the CheckOrigin field to check -// the origin. If the CheckOrigin function returns false, then the Upgrade -// method fails the WebSocket handshake with HTTP status 403. -// -// If the CheckOrigin field is nil, then the Upgrader uses a safe default: fail -// the handshake if the Origin request header is present and not equal to the -// Host request header. -// -// An application can allow connections from any origin by specifying a -// function that always returns true: -// -// var upgrader = websocket.Upgrader{ -// CheckOrigin: func(r *http.Request) bool { return true }, -// } -// -// The deprecated Upgrade function does not enforce an origin policy. It's the -// application's responsibility to check the Origin header before calling -// Upgrade. -// -// Compression EXPERIMENTAL -// -// Per message compression extensions (RFC 7692) are experimentally supported -// by this package in a limited capacity. Setting the EnableCompression option -// to true in Dialer or Upgrader will attempt to negotiate per message deflate -// support. -// -// var upgrader = websocket.Upgrader{ -// EnableCompression: true, -// } -// -// If compression was successfully negotiated with the connection's peer, any -// message received in compressed form will be automatically decompressed. -// All Read methods will return uncompressed bytes. -// -// Per message compression of messages written to a connection can be enabled -// or disabled by calling the corresponding Conn method: -// -// conn.EnableWriteCompression(false) -// -// Currently this package does not support compression with "context takeover". -// This means that messages must be compressed and decompressed in isolation, -// without retaining sliding window or dictionary state across messages. For -// more details refer to RFC 7692. -// -// Use of compression is experimental and may result in decreased performance. -package websocket diff --git a/vendor/github.com/gorilla/websocket/json.go b/vendor/github.com/gorilla/websocket/json.go deleted file mode 100644 index 4f0e36875..000000000 --- a/vendor/github.com/gorilla/websocket/json.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package websocket - -import ( - "encoding/json" - "io" -) - -// WriteJSON is deprecated, use c.WriteJSON instead. -func WriteJSON(c *Conn, v interface{}) error { - return c.WriteJSON(v) -} - -// WriteJSON writes the JSON encoding of v to the connection. -// -// See the documentation for encoding/json Marshal for details about the -// conversion of Go values to JSON. -func (c *Conn) WriteJSON(v interface{}) error { - w, err := c.NextWriter(TextMessage) - if err != nil { - return err - } - err1 := json.NewEncoder(w).Encode(v) - err2 := w.Close() - if err1 != nil { - return err1 - } - return err2 -} - -// ReadJSON is deprecated, use c.ReadJSON instead. -func ReadJSON(c *Conn, v interface{}) error { - return c.ReadJSON(v) -} - -// ReadJSON reads the next JSON-encoded message from the connection and stores -// it in the value pointed to by v. -// -// See the documentation for the encoding/json Unmarshal function for details -// about the conversion of JSON to a Go value. -func (c *Conn) ReadJSON(v interface{}) error { - _, r, err := c.NextReader() - if err != nil { - return err - } - err = json.NewDecoder(r).Decode(v) - if err == io.EOF { - // One value is expected in the message. - err = io.ErrUnexpectedEOF - } - return err -} diff --git a/vendor/github.com/gorilla/websocket/mask.go b/vendor/github.com/gorilla/websocket/mask.go deleted file mode 100644 index 6a88bbc74..000000000 --- a/vendor/github.com/gorilla/websocket/mask.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of -// this source code is governed by a BSD-style license that can be found in the -// LICENSE file. - -// +build !appengine - -package websocket - -import "unsafe" - -const wordSize = int(unsafe.Sizeof(uintptr(0))) - -func maskBytes(key [4]byte, pos int, b []byte) int { - - // Mask one byte at a time for small buffers. - if len(b) < 2*wordSize { - for i := range b { - b[i] ^= key[pos&3] - pos++ - } - return pos & 3 - } - - // Mask one byte at a time to word boundary. - if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 { - n = wordSize - n - for i := range b[:n] { - b[i] ^= key[pos&3] - pos++ - } - b = b[n:] - } - - // Create aligned word size key. - var k [wordSize]byte - for i := range k { - k[i] = key[(pos+i)&3] - } - kw := *(*uintptr)(unsafe.Pointer(&k)) - - // Mask one word at a time. - n := (len(b) / wordSize) * wordSize - for i := 0; i < n; i += wordSize { - *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(i))) ^= kw - } - - // Mask one byte at a time for remaining bytes. - b = b[n:] - for i := range b { - b[i] ^= key[pos&3] - pos++ - } - - return pos & 3 -} diff --git a/vendor/github.com/gorilla/websocket/mask_safe.go b/vendor/github.com/gorilla/websocket/mask_safe.go deleted file mode 100644 index 2aac060e5..000000000 --- a/vendor/github.com/gorilla/websocket/mask_safe.go +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of -// this source code is governed by a BSD-style license that can be found in the -// LICENSE file. - -// +build appengine - -package websocket - -func maskBytes(key [4]byte, pos int, b []byte) int { - for i := range b { - b[i] ^= key[pos&3] - pos++ - } - return pos & 3 -} diff --git a/vendor/github.com/gorilla/websocket/prepared.go b/vendor/github.com/gorilla/websocket/prepared.go deleted file mode 100644 index 1efffbd1e..000000000 --- a/vendor/github.com/gorilla/websocket/prepared.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package websocket - -import ( - "bytes" - "net" - "sync" - "time" -) - -// PreparedMessage caches on the wire representations of a message payload. -// Use PreparedMessage to efficiently send a message payload to multiple -// connections. PreparedMessage is especially useful when compression is used -// because the CPU and memory expensive compression operation can be executed -// once for a given set of compression options. -type PreparedMessage struct { - messageType int - data []byte - err error - mu sync.Mutex - frames map[prepareKey]*preparedFrame -} - -// prepareKey defines a unique set of options to cache prepared frames in PreparedMessage. -type prepareKey struct { - isServer bool - compress bool - compressionLevel int -} - -// preparedFrame contains data in wire representation. -type preparedFrame struct { - once sync.Once - data []byte -} - -// NewPreparedMessage returns an initialized PreparedMessage. You can then send -// it to connection using WritePreparedMessage method. Valid wire -// representation will be calculated lazily only once for a set of current -// connection options. -func NewPreparedMessage(messageType int, data []byte) (*PreparedMessage, error) { - pm := &PreparedMessage{ - messageType: messageType, - frames: make(map[prepareKey]*preparedFrame), - data: data, - } - - // Prepare a plain server frame. - _, frameData, err := pm.frame(prepareKey{isServer: true, compress: false}) - if err != nil { - return nil, err - } - - // To protect against caller modifying the data argument, remember the data - // copied to the plain server frame. - pm.data = frameData[len(frameData)-len(data):] - return pm, nil -} - -func (pm *PreparedMessage) frame(key prepareKey) (int, []byte, error) { - pm.mu.Lock() - frame, ok := pm.frames[key] - if !ok { - frame = &preparedFrame{} - pm.frames[key] = frame - } - pm.mu.Unlock() - - var err error - frame.once.Do(func() { - // Prepare a frame using a 'fake' connection. - // TODO: Refactor code in conn.go to allow more direct construction of - // the frame. - mu := make(chan bool, 1) - mu <- true - var nc prepareConn - c := &Conn{ - conn: &nc, - mu: mu, - isServer: key.isServer, - compressionLevel: key.compressionLevel, - enableWriteCompression: true, - writeBuf: make([]byte, defaultWriteBufferSize+maxFrameHeaderSize), - } - if key.compress { - c.newCompressionWriter = compressNoContextTakeover - } - err = c.WriteMessage(pm.messageType, pm.data) - frame.data = nc.buf.Bytes() - }) - return pm.messageType, frame.data, err -} - -type prepareConn struct { - buf bytes.Buffer - net.Conn -} - -func (pc *prepareConn) Write(p []byte) (int, error) { return pc.buf.Write(p) } -func (pc *prepareConn) SetWriteDeadline(t time.Time) error { return nil } diff --git a/vendor/github.com/gorilla/websocket/server.go b/vendor/github.com/gorilla/websocket/server.go deleted file mode 100644 index 3495e0f1a..000000000 --- a/vendor/github.com/gorilla/websocket/server.go +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package websocket - -import ( - "bufio" - "errors" - "net" - "net/http" - "net/url" - "strings" - "time" -) - -// HandshakeError describes an error with the handshake from the peer. -type HandshakeError struct { - message string -} - -func (e HandshakeError) Error() string { return e.message } - -// Upgrader specifies parameters for upgrading an HTTP connection to a -// WebSocket connection. -type Upgrader struct { - // HandshakeTimeout specifies the duration for the handshake to complete. - HandshakeTimeout time.Duration - - // ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer - // size is zero, then buffers allocated by the HTTP server are used. The - // I/O buffer sizes do not limit the size of the messages that can be sent - // or received. - ReadBufferSize, WriteBufferSize int - - // Subprotocols specifies the server's supported protocols in order of - // preference. If this field is set, then the Upgrade method negotiates a - // subprotocol by selecting the first match in this list with a protocol - // requested by the client. - Subprotocols []string - - // Error specifies the function for generating HTTP error responses. If Error - // is nil, then http.Error is used to generate the HTTP response. - Error func(w http.ResponseWriter, r *http.Request, status int, reason error) - - // CheckOrigin returns true if the request Origin header is acceptable. If - // CheckOrigin is nil, the host in the Origin header must not be set or - // must match the host of the request. - CheckOrigin func(r *http.Request) bool - - // EnableCompression specify if the server should attempt to negotiate per - // message compression (RFC 7692). Setting this value to true does not - // guarantee that compression will be supported. Currently only "no context - // takeover" modes are supported. - EnableCompression bool -} - -func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) { - err := HandshakeError{reason} - if u.Error != nil { - u.Error(w, r, status, err) - } else { - w.Header().Set("Sec-Websocket-Version", "13") - http.Error(w, http.StatusText(status), status) - } - return nil, err -} - -// checkSameOrigin returns true if the origin is not set or is equal to the request host. -func checkSameOrigin(r *http.Request) bool { - origin := r.Header["Origin"] - if len(origin) == 0 { - return true - } - u, err := url.Parse(origin[0]) - if err != nil { - return false - } - return u.Host == r.Host -} - -func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string { - if u.Subprotocols != nil { - clientProtocols := Subprotocols(r) - for _, serverProtocol := range u.Subprotocols { - for _, clientProtocol := range clientProtocols { - if clientProtocol == serverProtocol { - return clientProtocol - } - } - } - } else if responseHeader != nil { - return responseHeader.Get("Sec-Websocket-Protocol") - } - return "" -} - -// Upgrade upgrades the HTTP server connection to the WebSocket protocol. -// -// The responseHeader is included in the response to the client's upgrade -// request. Use the responseHeader to specify cookies (Set-Cookie) and the -// application negotiated subprotocol (Sec-Websocket-Protocol). -// -// If the upgrade fails, then Upgrade replies to the client with an HTTP error -// response. -func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) { - if r.Method != "GET" { - return u.returnError(w, r, http.StatusMethodNotAllowed, "websocket: not a websocket handshake: request method is not GET") - } - - if _, ok := responseHeader["Sec-Websocket-Extensions"]; ok { - return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific 'Sec-Websocket-Extensions' headers are unsupported") - } - - if !tokenListContainsValue(r.Header, "Connection", "upgrade") { - return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'upgrade' token not found in 'Connection' header") - } - - if !tokenListContainsValue(r.Header, "Upgrade", "websocket") { - return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'websocket' token not found in 'Upgrade' header") - } - - if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") { - return u.returnError(w, r, http.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header") - } - - checkOrigin := u.CheckOrigin - if checkOrigin == nil { - checkOrigin = checkSameOrigin - } - if !checkOrigin(r) { - return u.returnError(w, r, http.StatusForbidden, "websocket: 'Origin' header value not allowed") - } - - challengeKey := r.Header.Get("Sec-Websocket-Key") - if challengeKey == "" { - return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: `Sec-Websocket-Key' header is missing or blank") - } - - subprotocol := u.selectSubprotocol(r, responseHeader) - - // Negotiate PMCE - var compress bool - if u.EnableCompression { - for _, ext := range parseExtensions(r.Header) { - if ext[""] != "permessage-deflate" { - continue - } - compress = true - break - } - } - - var ( - netConn net.Conn - err error - ) - - h, ok := w.(http.Hijacker) - if !ok { - return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker") - } - var brw *bufio.ReadWriter - netConn, brw, err = h.Hijack() - if err != nil { - return u.returnError(w, r, http.StatusInternalServerError, err.Error()) - } - - if brw.Reader.Buffered() > 0 { - netConn.Close() - return nil, errors.New("websocket: client sent data before handshake is complete") - } - - c := newConnBRW(netConn, true, u.ReadBufferSize, u.WriteBufferSize, brw) - c.subprotocol = subprotocol - - if compress { - c.newCompressionWriter = compressNoContextTakeover - c.newDecompressionReader = decompressNoContextTakeover - } - - p := c.writeBuf[:0] - p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...) - p = append(p, computeAcceptKey(challengeKey)...) - p = append(p, "\r\n"...) - if c.subprotocol != "" { - p = append(p, "Sec-Websocket-Protocol: "...) - p = append(p, c.subprotocol...) - p = append(p, "\r\n"...) - } - if compress { - p = append(p, "Sec-Websocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n"...) - } - for k, vs := range responseHeader { - if k == "Sec-Websocket-Protocol" { - continue - } - for _, v := range vs { - p = append(p, k...) - p = append(p, ": "...) - for i := 0; i < len(v); i++ { - b := v[i] - if b <= 31 { - // prevent response splitting. - b = ' ' - } - p = append(p, b) - } - p = append(p, "\r\n"...) - } - } - p = append(p, "\r\n"...) - - // Clear deadlines set by HTTP server. - netConn.SetDeadline(time.Time{}) - - if u.HandshakeTimeout > 0 { - netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout)) - } - if _, err = netConn.Write(p); err != nil { - netConn.Close() - return nil, err - } - if u.HandshakeTimeout > 0 { - netConn.SetWriteDeadline(time.Time{}) - } - - return c, nil -} - -// Upgrade upgrades the HTTP server connection to the WebSocket protocol. -// -// This function is deprecated, use websocket.Upgrader instead. -// -// The application is responsible for checking the request origin before -// calling Upgrade. An example implementation of the same origin policy is: -// -// if req.Header.Get("Origin") != "http://"+req.Host { -// http.Error(w, "Origin not allowed", 403) -// return -// } -// -// If the endpoint supports subprotocols, then the application is responsible -// for negotiating the protocol used on the connection. Use the Subprotocols() -// function to get the subprotocols requested by the client. Use the -// Sec-Websocket-Protocol response header to specify the subprotocol selected -// by the application. -// -// The responseHeader is included in the response to the client's upgrade -// request. Use the responseHeader to specify cookies (Set-Cookie) and the -// negotiated subprotocol (Sec-Websocket-Protocol). -// -// The connection buffers IO to the underlying network connection. The -// readBufSize and writeBufSize parameters specify the size of the buffers to -// use. Messages can be larger than the buffers. -// -// If the request is not a valid WebSocket handshake, then Upgrade returns an -// error of type HandshakeError. Applications should handle this error by -// replying to the client with an HTTP error response. -func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) { - u := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize} - u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) { - // don't return errors to maintain backwards compatibility - } - u.CheckOrigin = func(r *http.Request) bool { - // allow all connections by default - return true - } - return u.Upgrade(w, r, responseHeader) -} - -// Subprotocols returns the subprotocols requested by the client in the -// Sec-Websocket-Protocol header. -func Subprotocols(r *http.Request) []string { - h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol")) - if h == "" { - return nil - } - protocols := strings.Split(h, ",") - for i := range protocols { - protocols[i] = strings.TrimSpace(protocols[i]) - } - return protocols -} - -// IsWebSocketUpgrade returns true if the client requested upgrade to the -// WebSocket protocol. -func IsWebSocketUpgrade(r *http.Request) bool { - return tokenListContainsValue(r.Header, "Connection", "upgrade") && - tokenListContainsValue(r.Header, "Upgrade", "websocket") -} diff --git a/vendor/github.com/gorilla/websocket/util.go b/vendor/github.com/gorilla/websocket/util.go deleted file mode 100644 index 9a4908df2..000000000 --- a/vendor/github.com/gorilla/websocket/util.go +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package websocket - -import ( - "crypto/rand" - "crypto/sha1" - "encoding/base64" - "io" - "net/http" - "strings" -) - -var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11") - -func computeAcceptKey(challengeKey string) string { - h := sha1.New() - h.Write([]byte(challengeKey)) - h.Write(keyGUID) - return base64.StdEncoding.EncodeToString(h.Sum(nil)) -} - -func generateChallengeKey() (string, error) { - p := make([]byte, 16) - if _, err := io.ReadFull(rand.Reader, p); err != nil { - return "", err - } - return base64.StdEncoding.EncodeToString(p), nil -} - -// Octet types from RFC 2616. -var octetTypes [256]byte - -const ( - isTokenOctet = 1 << iota - isSpaceOctet -) - -func init() { - // From RFC 2616 - // - // OCTET = - // CHAR = - // CTL = - // CR = - // LF = - // SP = - // HT = - // <"> = - // CRLF = CR LF - // LWS = [CRLF] 1*( SP | HT ) - // TEXT = - // separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> - // | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT - // token = 1* - // qdtext = > - - for c := 0; c < 256; c++ { - var t byte - isCtl := c <= 31 || c == 127 - isChar := 0 <= c && c <= 127 - isSeparator := strings.IndexRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) >= 0 - if strings.IndexRune(" \t\r\n", rune(c)) >= 0 { - t |= isSpaceOctet - } - if isChar && !isCtl && !isSeparator { - t |= isTokenOctet - } - octetTypes[c] = t - } -} - -func skipSpace(s string) (rest string) { - i := 0 - for ; i < len(s); i++ { - if octetTypes[s[i]]&isSpaceOctet == 0 { - break - } - } - return s[i:] -} - -func nextToken(s string) (token, rest string) { - i := 0 - for ; i < len(s); i++ { - if octetTypes[s[i]]&isTokenOctet == 0 { - break - } - } - return s[:i], s[i:] -} - -func nextTokenOrQuoted(s string) (value string, rest string) { - if !strings.HasPrefix(s, "\"") { - return nextToken(s) - } - s = s[1:] - for i := 0; i < len(s); i++ { - switch s[i] { - case '"': - return s[:i], s[i+1:] - case '\\': - p := make([]byte, len(s)-1) - j := copy(p, s[:i]) - escape := true - for i = i + 1; i < len(s); i++ { - b := s[i] - switch { - case escape: - escape = false - p[j] = b - j += 1 - case b == '\\': - escape = true - case b == '"': - return string(p[:j]), s[i+1:] - default: - p[j] = b - j += 1 - } - } - return "", "" - } - } - return "", "" -} - -// tokenListContainsValue returns true if the 1#token header with the given -// name contains token. -func tokenListContainsValue(header http.Header, name string, value string) bool { -headers: - for _, s := range header[name] { - for { - var t string - t, s = nextToken(skipSpace(s)) - if t == "" { - continue headers - } - s = skipSpace(s) - if s != "" && s[0] != ',' { - continue headers - } - if strings.EqualFold(t, value) { - return true - } - if s == "" { - continue headers - } - s = s[1:] - } - } - return false -} - -// parseExtensiosn parses WebSocket extensions from a header. -func parseExtensions(header http.Header) []map[string]string { - - // From RFC 6455: - // - // Sec-WebSocket-Extensions = extension-list - // extension-list = 1#extension - // extension = extension-token *( ";" extension-param ) - // extension-token = registered-token - // registered-token = token - // extension-param = token [ "=" (token | quoted-string) ] - // ;When using the quoted-string syntax variant, the value - // ;after quoted-string unescaping MUST conform to the - // ;'token' ABNF. - - var result []map[string]string -headers: - for _, s := range header["Sec-Websocket-Extensions"] { - for { - var t string - t, s = nextToken(skipSpace(s)) - if t == "" { - continue headers - } - ext := map[string]string{"": t} - for { - s = skipSpace(s) - if !strings.HasPrefix(s, ";") { - break - } - var k string - k, s = nextToken(skipSpace(s[1:])) - if k == "" { - continue headers - } - s = skipSpace(s) - var v string - if strings.HasPrefix(s, "=") { - v, s = nextTokenOrQuoted(skipSpace(s[1:])) - s = skipSpace(s) - } - if s != "" && s[0] != ',' && s[0] != ';' { - continue headers - } - ext[k] = v - } - if s != "" && s[0] != ',' { - continue headers - } - result = append(result, ext) - if s == "" { - continue headers - } - s = s[1:] - } - } - return result -} diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/.golangci.yml b/vendor/github.com/hashicorp/aws-sdk-go-base/.golangci.yml new file mode 100644 index 000000000..687b0c780 --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/.golangci.yml @@ -0,0 +1,26 @@ +issues: + max-per-linter: 0 + max-same-issues: 0 + +linters: + disable-all: true + enable: + - deadcode + - dogsled + - errcheck + - goconst + - gofmt + - gomnd + - gosimple + - ineffassign + - interfacer + - misspell + - scopelint + - staticcheck + - structcheck + - unconvert + - unparam + - unused + - typecheck + - varcheck + - vet diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/CHANGELOG.md b/vendor/github.com/hashicorp/aws-sdk-go-base/CHANGELOG.md new file mode 100644 index 000000000..f6ff4cc32 --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/CHANGELOG.md @@ -0,0 +1,53 @@ +# v0.6.0 (unreleased) + +BREAKING CHANGES + +* AWS error checking function have been moved to `tfawserr` package. `IsAWSErr` has been renamed to `ErrMessageContains` and `IsAWSErrExtended` has been renamed to `ErrMessageAndOrigErrContain`. #37 + +ENHANCEMENTS + +* Additional AWS error checking function have been added to the `tfawserr` package - `ErrCodeEquals`, `ErrCodeContains` and `ErrStatusCodeEquals`. + +# v0.5.0 (June 4, 2020) + +BREAKING CHANGES + +* Credential ordering has changed from static, environment, shared credentials, EC2 metadata, default AWS Go SDK (shared configuration, web identity, ECS, EC2 Metadata) to static, environment, shared credentials, default AWS Go SDK (shared configuration, web identity, ECS, EC2 Metadata). #20 +* The `AWS_METADATA_TIMEOUT` environment variable no longer has any effect as we now depend on the default AWS Go SDK EC2 Metadata client timeout of one second with two retries. #20 / #44 + +ENHANCEMENTS + +* Always enable AWS shared configuration file support (no longer require `AWS_SDK_LOAD_CONFIG` environment variable) #38 +* Automatically expand `~` prefix for home directories in shared credentials filename handling #40 +* Support assume role duration, policy ARNs, tags, and transitive tag keys via configuration #39 +* Add `CannotAssumeRoleError` and `NoValidCredentialSourcesError` error types with helpers #42 + +BUG FIXES + +* Properly use custom STS endpoint during AssumeRole API calls triggered by Terraform AWS Provider and S3 Backend configurations #32 +* Properly use custom EC2 metadata endpoint during API calls triggered by fallback credentials lookup #32 +* Prefer shared configuration handling over EC2 metadata #20 +* Prefer ECS credentials over EC2 metadata #20 +* Remove hardcoded AWS Provider messaging in error messages #31 / #42 + +# v0.4.0 (October 3, 2019) + +BUG FIXES + +* awsauth: fixed credentials retrieval, validation, and error handling + +# v0.3.0 (February 26, 2019) + +BUG FIXES + +* session: Return error instead of logging with AWS Account ID lookup failure [GH-3] + +# v0.2.0 (February 20, 2019) + +ENHANCEMENTS + +* validation: Add `ValidateAccountID` and `ValidateRegion` functions [GH-1] + +# v0.1.0 (February 18, 2019) + +* Initial release after split from github.com/terraform-providers/terraform-provider-aws diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/GNUmakefile b/vendor/github.com/hashicorp/aws-sdk-go-base/GNUmakefile new file mode 100644 index 000000000..3001f2ee4 --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/GNUmakefile @@ -0,0 +1,17 @@ +default: test lint + +fmt: + @echo "==> Fixing source code with gofmt..." + gofmt -s -w ./ + +lint: + @echo "==> Checking source code against linters..." + @golangci-lint run ./... + +test: + go test -timeout=30s -parallel=4 ./... + +tools: + GO111MODULE=off go get -u github.com/golangci/golangci-lint/cmd/golangci-lint + +.PHONY: lint test tools diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/LICENSE b/vendor/github.com/hashicorp/aws-sdk-go-base/LICENSE new file mode 100644 index 000000000..a612ad981 --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/README.md b/vendor/github.com/hashicorp/aws-sdk-go-base/README.md new file mode 100644 index 000000000..ad824ce1e --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/README.md @@ -0,0 +1,40 @@ +# aws-sdk-go-base + +An opinionated [AWS Go SDK](https://github.com/aws/aws-sdk-go) library for consistent authentication configuration between projects and additional helper functions. This library was originally started in [HashiCorp Terraform](https://github.com/hashicorp/terraform), migrated with the [Terraform AWS Provider](https://github.com/terraform-providers/terraform-provider-aws) during the Terraform 0.10 Core and Provider split, and now is offered as a separate library to allow easier dependency management in the Terraform ecosystem. + +**NOTE:** This library is not currently designed or intended for usage outside the [Terraform S3 Backend](https://www.terraform.io/docs/backends/types/s3.html) and the [Terraform AWS Provider](https://www.terraform.io/docs/providers/aws/index.html). + +## Requirements + +- [Go](https://golang.org/doc/install) 1.13 + +## Development + +Testing this project can be done through Go standard library functionality or if [Make](https://www.gnu.org/software/make/) is available: + +```sh +$ go test -v ./... +# Optionally if Make is available; both run the same testing +$ make test +``` + +Code quality assurance uses [golangci-lint](https://github.com/golangci/golangci-lint): + +```sh +$ golangci-lint run ./... +# Optionally if Make is available; both run the same linting +$ make lint +``` + +## Release Process + +- Push a new `vX.Y.Z` tag to the repository +- Close associated `vX.Y.Z` milestone +- For Terraform AWS Provider: Renovate will automatically detect the update and submit a dependency pull request (usually within an hour) +- For Terraform S3 Backend: Submit a new dependency pull request by running: + +```sh +go get github.com/hashicorp/aws-sdk-go-base@vX.Y.Z +go mod tidy +go mod vendor +``` diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/awsauth.go b/vendor/github.com/hashicorp/aws-sdk-go-base/awsauth.go new file mode 100644 index 000000000..3b1763ecd --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/awsauth.go @@ -0,0 +1,341 @@ +package awsbase + +import ( + "errors" + "fmt" + "log" + "os" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/arn" + "github.com/aws/aws-sdk-go/aws/awserr" + awsCredentials "github.com/aws/aws-sdk-go/aws/credentials" + "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds" + "github.com/aws/aws-sdk-go/aws/credentials/stscreds" + "github.com/aws/aws-sdk-go/aws/ec2metadata" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/sts" + "github.com/hashicorp/aws-sdk-go-base/tfawserr" + "github.com/hashicorp/go-cleanhttp" + "github.com/hashicorp/go-multierror" + homedir "github.com/mitchellh/go-homedir" +) + +const ( + // Default amount of time for EC2/ECS metadata client operations. + // Keep this value low to prevent long delays in non-EC2/ECS environments. + DefaultMetadataClientTimeout = 100 * time.Millisecond +) + +// GetAccountIDAndPartition gets the account ID and associated partition. +func GetAccountIDAndPartition(iamconn *iam.IAM, stsconn *sts.STS, authProviderName string) (string, string, error) { + var accountID, partition string + var err, errors error + + if authProviderName == ec2rolecreds.ProviderName { + accountID, partition, err = GetAccountIDAndPartitionFromEC2Metadata() + } else { + accountID, partition, err = GetAccountIDAndPartitionFromIAMGetUser(iamconn) + } + if accountID != "" { + return accountID, partition, nil + } + errors = multierror.Append(errors, err) + + accountID, partition, err = GetAccountIDAndPartitionFromSTSGetCallerIdentity(stsconn) + if accountID != "" { + return accountID, partition, nil + } + errors = multierror.Append(errors, err) + + accountID, partition, err = GetAccountIDAndPartitionFromIAMListRoles(iamconn) + if accountID != "" { + return accountID, partition, nil + } + errors = multierror.Append(errors, err) + + return accountID, partition, errors +} + +// GetAccountIDAndPartitionFromEC2Metadata gets the account ID and associated +// partition from EC2 metadata. +func GetAccountIDAndPartitionFromEC2Metadata() (string, string, error) { + log.Println("[DEBUG] Trying to get account information via EC2 Metadata") + + cfg := &aws.Config{} + setOptionalEndpoint(cfg) + sess, err := session.NewSession(cfg) + if err != nil { + return "", "", fmt.Errorf("error creating EC2 Metadata session: %w", err) + } + + metadataClient := ec2metadata.New(sess) + info, err := metadataClient.IAMInfo() + if err != nil { + // We can end up here if there's an issue with the instance metadata service + // or if we're getting credentials from AdRoll's Hologram (in which case IAMInfo will + // error out). + err = fmt.Errorf("failed getting account information via EC2 Metadata IAM information: %w", err) + log.Printf("[DEBUG] %s", err) + return "", "", err + } + + return parseAccountIDAndPartitionFromARN(info.InstanceProfileArn) +} + +// GetAccountIDAndPartitionFromIAMGetUser gets the account ID and associated +// partition from IAM. +func GetAccountIDAndPartitionFromIAMGetUser(iamconn *iam.IAM) (string, string, error) { + log.Println("[DEBUG] Trying to get account information via iam:GetUser") + + output, err := iamconn.GetUser(&iam.GetUserInput{}) + if err != nil { + // AccessDenied and ValidationError can be raised + // if credentials belong to federated profile, so we ignore these + if awsErr, ok := err.(awserr.Error); ok { + switch awsErr.Code() { + case "AccessDenied", "InvalidClientTokenId", "ValidationError": + return "", "", nil + } + } + err = fmt.Errorf("failed getting account information via iam:GetUser: %w", err) + log.Printf("[DEBUG] %s", err) + return "", "", err + } + + if output == nil || output.User == nil { + err = errors.New("empty iam:GetUser response") + log.Printf("[DEBUG] %s", err) + return "", "", err + } + + return parseAccountIDAndPartitionFromARN(aws.StringValue(output.User.Arn)) +} + +// GetAccountIDAndPartitionFromIAMListRoles gets the account ID and associated +// partition from listing IAM roles. +func GetAccountIDAndPartitionFromIAMListRoles(iamconn *iam.IAM) (string, string, error) { + log.Println("[DEBUG] Trying to get account information via iam:ListRoles") + + output, err := iamconn.ListRoles(&iam.ListRolesInput{ + MaxItems: aws.Int64(int64(1)), + }) + if err != nil { + err = fmt.Errorf("failed getting account information via iam:ListRoles: %w", err) + log.Printf("[DEBUG] %s", err) + return "", "", err + } + + if output == nil || len(output.Roles) < 1 { + err = fmt.Errorf("empty iam:ListRoles response") + log.Printf("[DEBUG] %s", err) + return "", "", err + } + + return parseAccountIDAndPartitionFromARN(aws.StringValue(output.Roles[0].Arn)) +} + +// GetAccountIDAndPartitionFromSTSGetCallerIdentity gets the account ID and associated +// partition from STS caller identity. +func GetAccountIDAndPartitionFromSTSGetCallerIdentity(stsconn *sts.STS) (string, string, error) { + log.Println("[DEBUG] Trying to get account information via sts:GetCallerIdentity") + + output, err := stsconn.GetCallerIdentity(&sts.GetCallerIdentityInput{}) + if err != nil { + return "", "", fmt.Errorf("error calling sts:GetCallerIdentity: %w", err) + } + + if output == nil || output.Arn == nil { + err = errors.New("empty sts:GetCallerIdentity response") + log.Printf("[DEBUG] %s", err) + return "", "", err + } + + return parseAccountIDAndPartitionFromARN(aws.StringValue(output.Arn)) +} + +func parseAccountIDAndPartitionFromARN(inputARN string) (string, string, error) { + arn, err := arn.Parse(inputARN) + if err != nil { + return "", "", fmt.Errorf("error parsing ARN (%s): %s", inputARN, err) + } + return arn.AccountID, arn.Partition, nil +} + +// GetCredentialsFromSession returns credentials derived from a session. A +// session uses the AWS SDK Go chain of providers so may use a provider (e.g., +// ProcessProvider) that is not part of the Terraform provider chain. +func GetCredentialsFromSession(c *Config) (*awsCredentials.Credentials, error) { + log.Printf("[INFO] Attempting to use session-derived credentials") + + // Avoid setting HTTPClient here as it will prevent the ec2metadata + // client from automatically lowering the timeout to 1 second. + options := &session.Options{ + Config: aws.Config{ + EndpointResolver: c.EndpointResolver(), + MaxRetries: aws.Int(0), + Region: aws.String(c.Region), + }, + Profile: c.Profile, + SharedConfigState: session.SharedConfigEnable, + } + + sess, err := session.NewSessionWithOptions(*options) + if err != nil { + if tfawserr.ErrCodeEquals(err, "NoCredentialProviders") { + return nil, c.NewNoValidCredentialSourcesError(err) + } + return nil, fmt.Errorf("Error creating AWS session: %w", err) + } + + creds := sess.Config.Credentials + cp, err := sess.Config.Credentials.Get() + if err != nil { + return nil, c.NewNoValidCredentialSourcesError(err) + } + + log.Printf("[INFO] Successfully derived credentials from session") + log.Printf("[INFO] AWS Auth provider used: %q", cp.ProviderName) + return creds, nil +} + +// GetCredentials gets credentials from the environment, shared credentials, +// the session (which may include a credential process), or ECS/EC2 metadata endpoints. +// GetCredentials also validates the credentials and the ability to assume a role +// or will return an error if unsuccessful. +func GetCredentials(c *Config) (*awsCredentials.Credentials, error) { + sharedCredentialsFilename, err := homedir.Expand(c.CredsFilename) + + if err != nil { + return nil, fmt.Errorf("error expanding shared credentials filename: %w", err) + } + + // build a chain provider, lazy-evaluated by aws-sdk + providers := []awsCredentials.Provider{ + &awsCredentials.StaticProvider{Value: awsCredentials.Value{ + AccessKeyID: c.AccessKey, + SecretAccessKey: c.SecretKey, + SessionToken: c.Token, + }}, + &awsCredentials.EnvProvider{}, + &awsCredentials.SharedCredentialsProvider{ + Filename: sharedCredentialsFilename, + Profile: c.Profile, + }, + } + + // Validate the credentials before returning them + creds := awsCredentials.NewChainCredentials(providers) + cp, err := creds.Get() + if err != nil { + if tfawserr.ErrCodeEquals(err, "NoCredentialProviders") { + creds, err = GetCredentialsFromSession(c) + if err != nil { + return nil, err + } + } else { + return nil, fmt.Errorf("Error loading credentials for AWS Provider: %w", err) + } + } else { + log.Printf("[INFO] AWS Auth provider used: %q", cp.ProviderName) + } + + // This is the "normal" flow (i.e. not assuming a role) + if c.AssumeRoleARN == "" { + return creds, nil + } + + // Otherwise we need to construct an STS client with the main credentials, and verify + // that we can assume the defined role. + log.Printf("[INFO] Attempting to AssumeRole %s (SessionName: %q, ExternalId: %q)", + c.AssumeRoleARN, c.AssumeRoleSessionName, c.AssumeRoleExternalID) + + awsConfig := &aws.Config{ + Credentials: creds, + EndpointResolver: c.EndpointResolver(), + Region: aws.String(c.Region), + MaxRetries: aws.Int(c.MaxRetries), + HTTPClient: cleanhttp.DefaultClient(), + } + + assumeRoleSession, err := session.NewSession(awsConfig) + + if err != nil { + return nil, fmt.Errorf("error creating assume role session: %w", err) + } + + stsclient := sts.New(assumeRoleSession) + assumeRoleProvider := &stscreds.AssumeRoleProvider{ + Client: stsclient, + RoleARN: c.AssumeRoleARN, + } + + if c.AssumeRoleDurationSeconds > 0 { + assumeRoleProvider.Duration = time.Duration(c.AssumeRoleDurationSeconds) * time.Second + } + + if c.AssumeRoleExternalID != "" { + assumeRoleProvider.ExternalID = aws.String(c.AssumeRoleExternalID) + } + + if c.AssumeRolePolicy != "" { + assumeRoleProvider.Policy = aws.String(c.AssumeRolePolicy) + } + + if len(c.AssumeRolePolicyARNs) > 0 { + var policyDescriptorTypes []*sts.PolicyDescriptorType + + for _, policyARN := range c.AssumeRolePolicyARNs { + policyDescriptorType := &sts.PolicyDescriptorType{ + Arn: aws.String(policyARN), + } + policyDescriptorTypes = append(policyDescriptorTypes, policyDescriptorType) + } + + assumeRoleProvider.PolicyArns = policyDescriptorTypes + } + + if c.AssumeRoleSessionName != "" { + assumeRoleProvider.RoleSessionName = c.AssumeRoleSessionName + } + + if len(c.AssumeRoleTags) > 0 { + var tags []*sts.Tag + + for k, v := range c.AssumeRoleTags { + tag := &sts.Tag{ + Key: aws.String(k), + Value: aws.String(v), + } + tags = append(tags, tag) + } + + assumeRoleProvider.Tags = tags + } + + if len(c.AssumeRoleTransitiveTagKeys) > 0 { + assumeRoleProvider.TransitiveTagKeys = aws.StringSlice(c.AssumeRoleTransitiveTagKeys) + } + + providers = []awsCredentials.Provider{assumeRoleProvider} + + assumeRoleCreds := awsCredentials.NewChainCredentials(providers) + _, err = assumeRoleCreds.Get() + if err != nil { + return nil, c.NewCannotAssumeRoleError(err) + } + + return assumeRoleCreds, nil +} + +func setOptionalEndpoint(cfg *aws.Config) string { + endpoint := os.Getenv("AWS_METADATA_URL") + if endpoint != "" { + log.Printf("[INFO] Setting custom metadata endpoint: %q", endpoint) + cfg.Endpoint = aws.String(endpoint) + return endpoint + } + return "" +} diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/config.go b/vendor/github.com/hashicorp/aws-sdk-go-base/config.go new file mode 100644 index 000000000..c5f9daafb --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/config.go @@ -0,0 +1,35 @@ +package awsbase + +type Config struct { + AccessKey string + AssumeRoleARN string + AssumeRoleDurationSeconds int + AssumeRoleExternalID string + AssumeRolePolicy string + AssumeRolePolicyARNs []string + AssumeRoleSessionName string + AssumeRoleTags map[string]string + AssumeRoleTransitiveTagKeys []string + CallerDocumentationURL string + CallerName string + CredsFilename string + DebugLogging bool + IamEndpoint string + Insecure bool + MaxRetries int + Profile string + Region string + SecretKey string + SkipCredsValidation bool + SkipMetadataApiCheck bool + SkipRequestingAccountId bool + StsEndpoint string + Token string + UserAgentProducts []*UserAgentProduct +} + +type UserAgentProduct struct { + Extra []string + Name string + Version string +} diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/endpoints.go b/vendor/github.com/hashicorp/aws-sdk-go-base/endpoints.go new file mode 100644 index 000000000..c3f64d1cd --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/endpoints.go @@ -0,0 +1,46 @@ +package awsbase + +import ( + "log" + "os" + + "github.com/aws/aws-sdk-go/aws/ec2metadata" + "github.com/aws/aws-sdk-go/aws/endpoints" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/sts" +) + +func (c *Config) EndpointResolver() endpoints.Resolver { + resolver := func(service, region string, optFns ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) { + // Ensure we pass all existing information (e.g. SigningRegion) and + // only override the URL, otherwise a MissingRegion error can occur + // when aws.Config.Region is not defined. + resolvedEndpoint, err := endpoints.DefaultResolver().EndpointFor(service, region, optFns...) + + if err != nil { + return resolvedEndpoint, err + } + + switch service { + case ec2metadata.ServiceName: + if endpoint := os.Getenv("AWS_METADATA_URL"); endpoint != "" { + log.Printf("[INFO] Setting custom EC2 metadata endpoint: %s", endpoint) + resolvedEndpoint.URL = endpoint + } + case iam.ServiceName: + if endpoint := c.IamEndpoint; endpoint != "" { + log.Printf("[INFO] Setting custom IAM endpoint: %s", endpoint) + resolvedEndpoint.URL = endpoint + } + case sts.ServiceName: + if endpoint := c.StsEndpoint; endpoint != "" { + log.Printf("[INFO] Setting custom STS endpoint: %s", endpoint) + resolvedEndpoint.URL = endpoint + } + } + + return resolvedEndpoint, nil + } + + return endpoints.ResolverFunc(resolver) +} diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/errors.go b/vendor/github.com/hashicorp/aws-sdk-go-base/errors.go new file mode 100644 index 000000000..2d5f1677c --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/errors.go @@ -0,0 +1,76 @@ +package awsbase + +import ( + "errors" + "fmt" +) + +// CannotAssumeRoleError occurs when AssumeRole cannot complete. +type CannotAssumeRoleError struct { + Config *Config + Err error +} + +func (e CannotAssumeRoleError) Error() string { + if e.Config == nil { + return fmt.Sprintf("cannot assume role: %s", e.Err) + } + + return fmt.Sprintf(`IAM Role (%s) cannot be assumed. + +There are a number of possible causes of this - the most common are: + * The credentials used in order to assume the role are invalid + * The credentials do not have appropriate permission to assume the role + * The role ARN is not valid + +Error: %s +`, e.Config.AssumeRoleARN, e.Err) +} + +func (e CannotAssumeRoleError) Unwrap() error { + return e.Err +} + +// IsCannotAssumeRoleError returns true if the error contains the CannotAssumeRoleError type. +func IsCannotAssumeRoleError(err error) bool { + var e CannotAssumeRoleError + return errors.As(err, &e) +} + +func (c *Config) NewCannotAssumeRoleError(err error) CannotAssumeRoleError { + return CannotAssumeRoleError{Config: c, Err: err} +} + +// NoValidCredentialSourcesError occurs when all credential lookup methods have been exhausted without results. +type NoValidCredentialSourcesError struct { + Config *Config + Err error +} + +func (e NoValidCredentialSourcesError) Error() string { + if e.Config == nil { + return fmt.Sprintf("no valid credential sources found: %s", e.Err) + } + + return fmt.Sprintf(`no valid credential sources for %s found. + +Please see %s +for more information about providing credentials. + +Error: %s +`, e.Config.CallerName, e.Config.CallerDocumentationURL, e.Err) +} + +func (e NoValidCredentialSourcesError) Unwrap() error { + return e.Err +} + +// IsNoValidCredentialSourcesError returns true if the error contains the NoValidCredentialSourcesError type. +func IsNoValidCredentialSourcesError(err error) bool { + var e NoValidCredentialSourcesError + return errors.As(err, &e) +} + +func (c *Config) NewNoValidCredentialSourcesError(err error) NoValidCredentialSourcesError { + return NoValidCredentialSourcesError{Config: c, Err: err} +} diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/go.mod b/vendor/github.com/hashicorp/aws-sdk-go-base/go.mod new file mode 100644 index 000000000..d4cba362a --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/go.mod @@ -0,0 +1,10 @@ +module github.com/hashicorp/aws-sdk-go-base + +require ( + github.com/aws/aws-sdk-go v1.31.9 + github.com/hashicorp/go-cleanhttp v0.5.0 + github.com/hashicorp/go-multierror v1.0.0 + github.com/mitchellh/go-homedir v1.1.0 +) + +go 1.13 diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/go.sum b/vendor/github.com/hashicorp/aws-sdk-go-base/go.sum new file mode 100644 index 000000000..eabfab4b5 --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/go.sum @@ -0,0 +1,31 @@ +github.com/aws/aws-sdk-go v1.31.9 h1:n+b34ydVfgC30j0Qm69yaapmjejQPW2BoDBX7Uy/tLI= +github.com/aws/aws-sdk-go v1.31.9/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0= +github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-cleanhttp v0.5.0 h1:wvCrVc9TjDls6+YGAF2hAifE1E5U1+b4tH6KdvN3Gig= +github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o= +github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= +github.com/jmespath/go-jmespath v0.3.0 h1:OS12ieG61fsCg5+qLJ+SsW9NicxNkg3b25OyT2yCeUc= +github.com/jmespath/go-jmespath v0.3.0/go.mod h1:9QtRXoHjLGCJ5IBSaohpXITPlowMeeYCZ7fLUTSywik= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2 h1:CCH4IOTTfewWjGOlSp+zGcjutRKlBEZQ6wTn8ozI/nI= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/logger.go b/vendor/github.com/hashicorp/aws-sdk-go-base/logger.go new file mode 100644 index 000000000..467d7acea --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/logger.go @@ -0,0 +1,18 @@ +package awsbase + +import ( + "log" + "strings" +) + +type DebugLogger struct{} + +func (l DebugLogger) Log(args ...interface{}) { + tokens := make([]string, 0, len(args)) + for _, arg := range args { + if token, ok := arg.(string); ok { + tokens = append(tokens, token) + } + } + log.Printf("[DEBUG] [aws-sdk-go] %s", strings.Join(tokens, " ")) +} diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/mock.go b/vendor/github.com/hashicorp/aws-sdk-go-base/mock.go new file mode 100644 index 000000000..253140188 --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/mock.go @@ -0,0 +1,512 @@ +package awsbase + +import ( + "bytes" + "encoding/json" + "fmt" + "log" + "net/http" + "net/http/httptest" + "net/url" + "os" + "time" + + "github.com/aws/aws-sdk-go/aws" + awsCredentials "github.com/aws/aws-sdk-go/aws/credentials" + "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds" + "github.com/aws/aws-sdk-go/aws/credentials/endpointcreds" + "github.com/aws/aws-sdk-go/aws/credentials/stscreds" + "github.com/aws/aws-sdk-go/aws/session" +) + +const ( + MockEc2MetadataAccessKey = `Ec2MetadataAccessKey` + MockEc2MetadataSecretKey = `Ec2MetadataSecretKey` + MockEc2MetadataSessionToken = `Ec2MetadataSessionToken` + + MockEcsCredentialsAccessKey = `EcsCredentialsAccessKey` + MockEcsCredentialsSecretKey = `EcsCredentialsSecretKey` + MockEcsCredentialsSessionToken = `EcsCredentialsSessionToken` + + MockEnvAccessKey = `EnvAccessKey` + MockEnvSecretKey = `EnvSecretKey` + MockEnvSessionToken = `EnvSessionToken` + + MockStaticAccessKey = `StaticAccessKey` + MockStaticSecretKey = `StaticSecretKey` + + MockStsAssumeRoleAccessKey = `AssumeRoleAccessKey` + MockStsAssumeRoleArn = `arn:aws:iam::555555555555:role/AssumeRole` + MockStsAssumeRoleExternalId = `AssumeRoleExternalId` + MockStsAssumeRoleInvalidResponseBodyInvalidClientTokenId = ` + + Sender + InvalidClientTokenId + The security token included in the request is invalid. + +4d0cf5ec-892a-4d3f-84e4-30e9987d9bdd +` + MockStsAssumeRolePolicy = `{ + "Version": "2012-10-17", + "Statement": { + "Effect": "Allow", + "Action": "*", + "Resource": "*", + } +}` + MockStsAssumeRolePolicyArn = `arn:aws:iam::555555555555:policy/AssumeRolePolicy1` + MockStsAssumeRoleSecretKey = `AssumeRoleSecretKey` + MockStsAssumeRoleSessionName = `AssumeRoleSessionName` + MockStsAssumeRoleSessionToken = `AssumeRoleSessionToken` + MockStsAssumeRoleTagKey = `AssumeRoleTagKey` + MockStsAssumeRoleTagValue = `AssumeRoleTagValue` + MockStsAssumeRoleTransitiveTagKey = `AssumeRoleTagKey` + MockStsAssumeRoleValidResponseBody = ` + + + arn:aws:sts::555555555555:assumed-role/role/AssumeRoleSessionName + ARO123EXAMPLE123:AssumeRoleSessionName + + + AssumeRoleAccessKey + AssumeRoleSecretKey + AssumeRoleSessionToken + 2099-12-31T23:59:59Z + + + + 01234567-89ab-cdef-0123-456789abcdef + +` + + MockStsAssumeRoleWithWebIdentityAccessKey = `AssumeRoleWithWebIdentityAccessKey` + MockStsAssumeRoleWithWebIdentityArn = `arn:aws:iam::666666666666:role/WebIdentityToken` + MockStsAssumeRoleWithWebIdentitySecretKey = `AssumeRoleWithWebIdentitySecretKey` + MockStsAssumeRoleWithWebIdentitySessionName = `AssumeRoleWithWebIdentitySessionName` + MockStsAssumeRoleWithWebIdentitySessionToken = `AssumeRoleWithWebIdentitySessionToken` + MockStsAssumeRoleWithWebIdentityValidResponseBody = ` + + amzn1.account.AF6RHO7KZU5XRVQJGXK6HB56KR2A + client.6666666666666666666.6666@apps.example.com + + arn:aws:sts::666666666666:assumed-role/FederatedWebIdentityRole/AssumeRoleWithWebIdentitySessionName + ARO123EXAMPLE123:AssumeRoleWithWebIdentitySessionName + + + AssumeRoleWithWebIdentitySessionToken + AssumeRoleWithWebIdentitySecretKey + 2099-12-31T23:59:59Z + AssumeRoleWithWebIdentityAccessKey + + www.amazon.com + + + 01234567-89ab-cdef-0123-456789abcdef + +` + + MockStsGetCallerIdentityAccountID = `222222222222` + MockStsGetCallerIdentityInvalidResponseBodyAccessDenied = ` + + Sender + AccessDenied + User: arn:aws:iam::123456789012:user/Bob is not authorized to perform: sts:GetCallerIdentity + +01234567-89ab-cdef-0123-456789abcdef +` + MockStsGetCallerIdentityPartition = `aws` + MockStsGetCallerIdentityValidResponseBody = ` + + arn:aws:iam::222222222222:user/Alice + AKIAI44QH8DHBEXAMPLE + 222222222222 + + + 01234567-89ab-cdef-0123-456789abcdef + +` + + MockWebIdentityToken = `WebIdentityToken` +) + +var ( + MockEc2MetadataCredentials = awsCredentials.Value{ + AccessKeyID: MockEc2MetadataAccessKey, + ProviderName: ec2rolecreds.ProviderName, + SecretAccessKey: MockEc2MetadataSecretKey, + SessionToken: MockEc2MetadataSessionToken, + } + + MockEcsCredentialsCredentials = awsCredentials.Value{ + AccessKeyID: MockEcsCredentialsAccessKey, + ProviderName: endpointcreds.ProviderName, + SecretAccessKey: MockEcsCredentialsSecretKey, + SessionToken: MockEcsCredentialsSessionToken, + } + + MockEnvCredentials = awsCredentials.Value{ + AccessKeyID: MockEnvAccessKey, + ProviderName: awsCredentials.EnvProviderName, + SecretAccessKey: MockEnvSecretKey, + } + + MockEnvCredentialsWithSessionToken = awsCredentials.Value{ + AccessKeyID: MockEnvAccessKey, + ProviderName: awsCredentials.EnvProviderName, + SecretAccessKey: MockEnvSecretKey, + SessionToken: MockEnvSessionToken, + } + + MockStaticCredentials = awsCredentials.Value{ + AccessKeyID: MockStaticAccessKey, + ProviderName: awsCredentials.StaticProviderName, + SecretAccessKey: MockStaticSecretKey, + } + + MockStsAssumeRoleCredentials = awsCredentials.Value{ + AccessKeyID: MockStsAssumeRoleAccessKey, + ProviderName: stscreds.ProviderName, + SecretAccessKey: MockStsAssumeRoleSecretKey, + SessionToken: MockStsAssumeRoleSessionToken, + } + MockStsAssumeRoleInvalidEndpointInvalidClientTokenId = &MockEndpoint{ + Request: &MockRequest{ + Body: url.Values{ + "Action": []string{"AssumeRole"}, + "DurationSeconds": []string{"900"}, + "RoleArn": []string{MockStsAssumeRoleArn}, + "RoleSessionName": []string{MockStsAssumeRoleSessionName}, + "Version": []string{"2011-06-15"}, + }.Encode(), + Method: http.MethodPost, + Uri: "/", + }, + Response: &MockResponse{ + Body: MockStsAssumeRoleInvalidResponseBodyInvalidClientTokenId, + ContentType: "text/xml", + StatusCode: http.StatusForbidden, + }, + } + MockStsAssumeRoleValidEndpoint = &MockEndpoint{ + Request: &MockRequest{ + Body: url.Values{ + "Action": []string{"AssumeRole"}, + "DurationSeconds": []string{"900"}, + "RoleArn": []string{MockStsAssumeRoleArn}, + "RoleSessionName": []string{MockStsAssumeRoleSessionName}, + "Version": []string{"2011-06-15"}, + }.Encode(), + Method: http.MethodPost, + Uri: "/", + }, + Response: &MockResponse{ + Body: MockStsAssumeRoleValidResponseBody, + ContentType: "text/xml", + StatusCode: http.StatusOK, + }, + } + + MockStsAssumeRoleWithWebIdentityValidEndpoint = &MockEndpoint{ + Request: &MockRequest{ + Body: url.Values{ + "Action": []string{"AssumeRoleWithWebIdentity"}, + "RoleArn": []string{MockStsAssumeRoleWithWebIdentityArn}, + "RoleSessionName": []string{MockStsAssumeRoleWithWebIdentitySessionName}, + "Version": []string{"2011-06-15"}, + "WebIdentityToken": []string{MockWebIdentityToken}, + }.Encode(), + Method: http.MethodPost, + Uri: "/", + }, + Response: &MockResponse{ + Body: MockStsAssumeRoleWithWebIdentityValidResponseBody, + ContentType: "text/xml", + StatusCode: http.StatusOK, + }, + } + + MockStsAssumeRoleWithWebIdentityCredentials = awsCredentials.Value{ + AccessKeyID: MockStsAssumeRoleWithWebIdentityAccessKey, + ProviderName: stscreds.WebIdentityProviderName, + SecretAccessKey: MockStsAssumeRoleWithWebIdentitySecretKey, + SessionToken: MockStsAssumeRoleWithWebIdentitySessionToken, + } + + MockStsGetCallerIdentityInvalidEndpointAccessDenied = &MockEndpoint{ + Request: &MockRequest{ + Body: url.Values{ + "Action": []string{"GetCallerIdentity"}, + "Version": []string{"2011-06-15"}, + }.Encode(), + Method: http.MethodPost, + Uri: "/", + }, + Response: &MockResponse{ + Body: MockStsGetCallerIdentityInvalidResponseBodyAccessDenied, + ContentType: "text/xml", + StatusCode: http.StatusForbidden, + }, + } + MockStsGetCallerIdentityValidEndpoint = &MockEndpoint{ + Request: &MockRequest{ + Body: url.Values{ + "Action": []string{"GetCallerIdentity"}, + "Version": []string{"2011-06-15"}, + }.Encode(), + Method: http.MethodPost, + Uri: "/", + }, + Response: &MockResponse{ + Body: MockStsGetCallerIdentityValidResponseBody, + ContentType: "text/xml", + StatusCode: http.StatusOK, + }, + } +) + +// MockAwsApiServer establishes a httptest server to simulate behaviour of a real AWS API server +func MockAwsApiServer(svcName string, endpoints []*MockEndpoint) *httptest.Server { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + buf := new(bytes.Buffer) + if _, err := buf.ReadFrom(r.Body); err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprintf(w, "Error reading from HTTP Request Body: %s", err) + return + } + requestBody := buf.String() + + log.Printf("[DEBUG] Received %s API %q request to %q: %s", + svcName, r.Method, r.RequestURI, requestBody) + + for _, e := range endpoints { + if r.Method == e.Request.Method && r.RequestURI == e.Request.Uri && requestBody == e.Request.Body { + log.Printf("[DEBUG] Mocked %s API responding with %d: %s", + svcName, e.Response.StatusCode, e.Response.Body) + + w.WriteHeader(e.Response.StatusCode) + w.Header().Set("Content-Type", e.Response.ContentType) + w.Header().Set("X-Amzn-Requestid", "1b206dd1-f9a8-11e5-becf-051c60f11c4a") + w.Header().Set("Date", time.Now().Format(time.RFC1123)) + + fmt.Fprintln(w, e.Response.Body) + return + } + } + + w.WriteHeader(http.StatusBadRequest) + })) + + return ts +} + +// GetMockedAwsApiSession establishes an AWS session to a simulated AWS API server for a given service and route endpoints. +func GetMockedAwsApiSession(svcName string, endpoints []*MockEndpoint) (func(), *session.Session, error) { + ts := MockAwsApiServer(svcName, endpoints) + + sc := awsCredentials.NewStaticCredentials("accessKey", "secretKey", "") + + sess, err := session.NewSession(&aws.Config{ + Credentials: sc, + Region: aws.String("us-east-1"), + Endpoint: aws.String(ts.URL), + CredentialsChainVerboseErrors: aws.Bool(true), + }) + + return ts.Close, sess, err +} + +// awsMetadataApiMock establishes a httptest server to mock out the internal AWS Metadata +// service. IAM Credentials are retrieved by the EC2RoleProvider, which makes +// API calls to this internal URL. By replacing the server with a test server, +// we can simulate an AWS environment +func awsMetadataApiMock(responses []*MetadataResponse) func() { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/plain") + w.Header().Add("Server", "MockEC2") + log.Printf("[DEBUG] Mock EC2 metadata server received request: %s", r.RequestURI) + for _, e := range responses { + if r.RequestURI == e.Uri { + fmt.Fprintln(w, e.Body) + return + } + } + w.WriteHeader(http.StatusBadRequest) + })) + + os.Setenv("AWS_METADATA_URL", ts.URL+"/latest") + return ts.Close +} + +// ecsCredentialsApiMock establishes a httptest server to mock out the ECS credentials API. +func ecsCredentialsApiMock() func() { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Header().Add("Server", "MockECS") + log.Printf("[DEBUG] Mock ECS credentials server received request: %s", r.RequestURI) + if r.RequestURI == "/creds" { + _ = json.NewEncoder(w).Encode(map[string]string{ + "AccessKeyId": MockEcsCredentialsAccessKey, + "Expiration": time.Now().UTC().Format(time.RFC3339), + "RoleArn": "arn:aws:iam::000000000000:role/EcsCredentials", + "SecretAccessKey": MockEcsCredentialsSecretKey, + "Token": MockEcsCredentialsSessionToken, + }) + return + } + w.WriteHeader(http.StatusBadRequest) + })) + + os.Setenv("AWS_CONTAINER_CREDENTIALS_FULL_URI", ts.URL+"/creds") + return ts.Close +} + +// MockStsAssumeRoleValidEndpointWithOptions returns a valid STS AssumeRole response with configurable request options. +func MockStsAssumeRoleValidEndpointWithOptions(options map[string]string) *MockEndpoint { + urlValues := url.Values{ + "Action": []string{"AssumeRole"}, + "DurationSeconds": []string{"900"}, + "RoleArn": []string{MockStsAssumeRoleArn}, + "RoleSessionName": []string{MockStsAssumeRoleSessionName}, + "Version": []string{"2011-06-15"}, + } + + for k, v := range options { + urlValues.Set(k, v) + } + + return &MockEndpoint{ + Request: &MockRequest{ + Body: urlValues.Encode(), + Method: http.MethodPost, + Uri: "/", + }, + Response: &MockResponse{ + Body: MockStsAssumeRoleValidResponseBody, + ContentType: "text/xml", + StatusCode: http.StatusOK, + }, + } +} + +// MockEndpoint represents a basic request and response that can be used for creating simple httptest server routes. +type MockEndpoint struct { + Request *MockRequest + Response *MockResponse +} + +// MockRequest represents a basic HTTP request +type MockRequest struct { + Method string + Uri string + Body string +} + +// MockResponse represents a basic HTTP response. +type MockResponse struct { + StatusCode int + Body string + ContentType string +} + +// MetadataResponse represents a metadata server response URI and body +type MetadataResponse struct { + Uri string `json:"uri"` + Body string `json:"body"` +} + +var ec2metadata_instanceIdEndpoint = &MetadataResponse{ + Uri: "/latest/meta-data/instance-id", + Body: "mock-instance-id", +} + +var ec2metadata_securityCredentialsEndpoints = []*MetadataResponse{ + { + Uri: "/latest/api/token", + Body: "Ec2MetadataApiToken", + }, + { + Uri: "/latest/meta-data/iam/security-credentials/", + Body: "test_role", + }, + { + Uri: "/latest/meta-data/iam/security-credentials/test_role", + Body: "{\"Code\":\"Success\",\"LastUpdated\":\"2015-12-11T17:17:25Z\",\"Type\":\"AWS-HMAC\",\"AccessKeyId\":\"Ec2MetadataAccessKey\",\"SecretAccessKey\":\"Ec2MetadataSecretKey\",\"Token\":\"Ec2MetadataSessionToken\"}", + }, +} + +var ec2metadata_iamInfoEndpoint = &MetadataResponse{ + Uri: "/latest/meta-data/iam/info", + Body: "{\"Code\": \"Success\",\"LastUpdated\": \"2016-03-17T12:27:32Z\",\"InstanceProfileArn\": \"arn:aws:iam::000000000000:instance-profile/my-instance-profile\",\"InstanceProfileId\": \"AIPAABCDEFGHIJKLMN123\"}", +} + +const ec2metadata_iamInfoEndpoint_expectedAccountID = `000000000000` +const ec2metadata_iamInfoEndpoint_expectedPartition = `aws` + +const iamResponse_GetUser_valid = ` + + + AIDACKCEVSQ6C2EXAMPLE + /division_abc/subdivision_xyz/ + Bob + arn:aws:iam::111111111111:user/division_abc/subdivision_xyz/Bob + 2013-10-02T17:01:44Z + 2014-10-10T14:37:51Z + + + + 7a62c49f-347e-4fc4-9331-6e8eEXAMPLE + +` + +const iamResponse_GetUser_valid_expectedAccountID = `111111111111` +const iamResponse_GetUser_valid_expectedPartition = `aws` + +const iamResponse_GetUser_unauthorized = ` + + Sender + AccessDenied + User: arn:aws:iam::123456789012:user/Bob is not authorized to perform: iam:GetUser on resource: arn:aws:iam::123456789012:user/Bob + + 7a62c49f-347e-4fc4-9331-6e8eEXAMPLE +` + +const iamResponse_GetUser_federatedFailure = ` + + Sender + ValidationError + Must specify userName when calling with non-User credentials + + 7a62c49f-347e-4fc4-9331-6e8eEXAMPLE +` + +const iamResponse_ListRoles_valid = ` + + true + AWceSSsKsazQ4IEplT9o4hURCzBs00iavlEvEXAMPLE + + + / + %7B%22Version%22%3A%222008-10-17%22%2C%22Statement%22%3A%5B%7B%22Sid%22%3A%22%22%2C%22Effect%22%3A%22Allow%22%2C%22Principal%22%3A%7B%22Service%22%3A%22ec2.amazonaws.com%22%7D%2C%22Action%22%3A%22sts%3AAssumeRole%22%7D%5D%7D + AROACKCEVSQ6C2EXAMPLE + elasticbeanstalk-role + arn:aws:iam::444444444444:role/elasticbeanstalk-role + 2013-10-02T17:01:44Z + + + + + 7a62c49f-347e-4fc4-9331-6e8eEXAMPLE + +` + +const iamResponse_ListRoles_valid_expectedAccountID = `444444444444` +const iamResponse_ListRoles_valid_expectedPartition = `aws` + +const iamResponse_ListRoles_unauthorized = ` + + Sender + AccessDenied + User: arn:aws:iam::123456789012:user/Bob is not authorized to perform: iam:ListRoles on resource: arn:aws:iam::123456789012:role/ + + 7a62c49f-347e-4fc4-9331-6e8eEXAMPLE +` diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/session.go b/vendor/github.com/hashicorp/aws-sdk-go-base/session.go new file mode 100644 index 000000000..24ed95bd7 --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/session.go @@ -0,0 +1,193 @@ +package awsbase + +import ( + "crypto/tls" + "fmt" + "log" + "net/http" + "os" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/endpoints" + "github.com/aws/aws-sdk-go/aws/request" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/sts" + "github.com/hashicorp/aws-sdk-go-base/tfawserr" + "github.com/hashicorp/go-cleanhttp" +) + +const ( + // AppendUserAgentEnvVar is a conventionally used environment variable + // containing additional HTTP User-Agent information. + // If present and its value is non-empty, it is directly appended to the + // User-Agent header for HTTP requests. + AppendUserAgentEnvVar = "TF_APPEND_USER_AGENT" + // Maximum network retries. + // We depend on the AWS Go SDK DefaultRetryer exponential backoff. + // Ensure that if the AWS Config MaxRetries is set high (which it is by + // default), that we only retry for a few seconds with typically + // unrecoverable network errors, such as DNS lookup failures. + MaxNetworkRetryCount = 9 +) + +// GetSessionOptions attempts to return valid AWS Go SDK session authentication +// options based on pre-existing credential provider, configured profile, or +// fallback to automatically a determined session via the AWS Go SDK. +func GetSessionOptions(c *Config) (*session.Options, error) { + options := &session.Options{ + Config: aws.Config{ + EndpointResolver: c.EndpointResolver(), + HTTPClient: cleanhttp.DefaultClient(), + MaxRetries: aws.Int(0), + Region: aws.String(c.Region), + }, + Profile: c.Profile, + SharedConfigState: session.SharedConfigEnable, + } + + // get and validate credentials + creds, err := GetCredentials(c) + if err != nil { + return nil, err + } + + // add the validated credentials to the session options + options.Config.Credentials = creds + + if c.Insecure { + transport := options.Config.HTTPClient.Transport.(*http.Transport) + transport.TLSClientConfig = &tls.Config{ + InsecureSkipVerify: true, + } + } + + if c.DebugLogging { + options.Config.LogLevel = aws.LogLevel(aws.LogDebugWithHTTPBody | aws.LogDebugWithRequestRetries | aws.LogDebugWithRequestErrors) + options.Config.Logger = DebugLogger{} + } + + return options, nil +} + +// GetSession attempts to return valid AWS Go SDK session. +func GetSession(c *Config) (*session.Session, error) { + if c.SkipMetadataApiCheck { + os.Setenv("AWS_EC2_METADATA_DISABLED", "true") + } + + options, err := GetSessionOptions(c) + + if err != nil { + return nil, err + } + + sess, err := session.NewSessionWithOptions(*options) + if err != nil { + if tfawserr.ErrCodeEquals(err, "NoCredentialProviders") { + return nil, c.NewNoValidCredentialSourcesError(err) + } + return nil, fmt.Errorf("Error creating AWS session: %w", err) + } + + if c.MaxRetries > 0 { + sess = sess.Copy(&aws.Config{MaxRetries: aws.Int(c.MaxRetries)}) + } + + for _, product := range c.UserAgentProducts { + sess.Handlers.Build.PushBack(request.MakeAddToUserAgentHandler(product.Name, product.Version, product.Extra...)) + } + + // Add custom input from ENV to the User-Agent request header + // Reference: https://github.com/terraform-providers/terraform-provider-aws/issues/9149 + if v := os.Getenv(AppendUserAgentEnvVar); v != "" { + log.Printf("[DEBUG] Using additional User-Agent Info: %s", v) + sess.Handlers.Build.PushBack(request.MakeAddToUserAgentFreeFormHandler(v)) + } + + // Generally, we want to configure a lower retry theshold for networking issues + // as the session retry threshold is very high by default and can mask permanent + // networking failures, such as a non-existent service endpoint. + // MaxRetries will override this logic if it has a lower retry threshold. + // NOTE: This logic can be fooled by other request errors raising the retry count + // before any networking error occurs + sess.Handlers.Retry.PushBack(func(r *request.Request) { + if r.RetryCount < MaxNetworkRetryCount { + return + } + // RequestError: send request failed + // caused by: Post https://FQDN/: dial tcp: lookup FQDN: no such host + if tfawserr.ErrMessageAndOrigErrContain(r.Error, "RequestError", "send request failed", "no such host") { + log.Printf("[WARN] Disabling retries after next request due to networking issue") + r.Retryable = aws.Bool(false) + } + // RequestError: send request failed + // caused by: Post https://FQDN/: dial tcp IPADDRESS:443: connect: connection refused + if tfawserr.ErrMessageAndOrigErrContain(r.Error, "RequestError", "send request failed", "connection refused") { + log.Printf("[WARN] Disabling retries after next request due to networking issue") + r.Retryable = aws.Bool(false) + } + }) + + if !c.SkipCredsValidation { + if _, _, err := GetAccountIDAndPartitionFromSTSGetCallerIdentity(sts.New(sess)); err != nil { + return nil, fmt.Errorf("error validating provider credentials: %w", err) + } + } + + return sess, nil +} + +// GetSessionWithAccountIDAndPartition attempts to return valid AWS Go SDK session +// along with account ID and partition information if available +func GetSessionWithAccountIDAndPartition(c *Config) (*session.Session, string, string, error) { + sess, err := GetSession(c) + + if err != nil { + return nil, "", "", err + } + + if c.AssumeRoleARN != "" { + accountID, partition, _ := parseAccountIDAndPartitionFromARN(c.AssumeRoleARN) + return sess, accountID, partition, nil + } + + iamClient := iam.New(sess) + stsClient := sts.New(sess) + + if !c.SkipCredsValidation { + accountID, partition, err := GetAccountIDAndPartitionFromSTSGetCallerIdentity(stsClient) + + if err != nil { + return nil, "", "", fmt.Errorf("error validating provider credentials: %w", err) + } + + return sess, accountID, partition, nil + } + + if !c.SkipRequestingAccountId { + credentialsProviderName := "" + + if credentialsValue, err := sess.Config.Credentials.Get(); err == nil { + credentialsProviderName = credentialsValue.ProviderName + } + + accountID, partition, err := GetAccountIDAndPartition(iamClient, stsClient, credentialsProviderName) + + if err == nil { + return sess, accountID, partition, nil + } + + return nil, "", "", fmt.Errorf( + "AWS account ID not previously found and failed retrieving via all available methods. "+ + "See https://www.terraform.io/docs/providers/aws/index.html#skip_requesting_account_id for workaround and implications. "+ + "Errors: %w", err) + } + + var partition string + if p, ok := endpoints.PartitionForRegion(endpoints.DefaultPartitions(), c.Region); ok { + partition = p.ID() + } + + return sess, "", partition, nil +} diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/tfawserr/awserr.go b/vendor/github.com/hashicorp/aws-sdk-go-base/tfawserr/awserr.go new file mode 100644 index 000000000..20af60606 --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/tfawserr/awserr.go @@ -0,0 +1,77 @@ +package tfawserr + +import ( + "errors" + "strings" + + "github.com/aws/aws-sdk-go/aws/awserr" +) + +// ErrMessageAndOrigErrContain returns true if the error matches all these conditions: +// * err is of type awserr.Error +// * Error.Code() matches code +// * Error.Message() contains message +// * Error.OrigErr() contains origErrMessage +func ErrMessageAndOrigErrContain(err error, code string, message string, origErrMessage string) bool { + if !ErrMessageContains(err, code, message) { + return false + } + + if origErrMessage == "" { + return true + } + + // Ensure OrigErr() is non-nil, to prevent panics + if origErr := err.(awserr.Error).OrigErr(); origErr != nil { + return strings.Contains(origErr.Error(), origErrMessage) + } + + return false +} + +// ErrCodeEquals returns true if the error matches all these conditions: +// * err is of type awserr.Error +// * Error.Code() equals code +func ErrCodeEquals(err error, code string) bool { + var awsErr awserr.Error + if errors.As(err, &awsErr) { + return awsErr.Code() == code + } + return false +} + +// ErrCodeContains returns true if the error matches all these conditions: +// * err is of type awserr.Error +// * Error.Code() contains code +func ErrCodeContains(err error, code string) bool { + var awsErr awserr.Error + if errors.As(err, &awsErr) { + return strings.Contains(awsErr.Code(), code) + } + return false +} + +// ErrMessageContains returns true if the error matches all these conditions: +// * err is of type awserr.Error +// * Error.Code() equals code +// * Error.Message() contains message +func ErrMessageContains(err error, code string, message string) bool { + var awsErr awserr.Error + if errors.As(err, &awsErr) { + return awsErr.Code() == code && strings.Contains(awsErr.Message(), message) + } + return false +} + +// ErrStatusCodeEquals returns true if the error matches all these conditions: +// * err is of type awserr.RequestFailure +// * RequestFailure.StatusCode() equals statusCode +// It is always preferable to use ErrMessageContains() except in older APIs (e.g. S3) +// that sometimes only respond with status codes. +func ErrStatusCodeEquals(err error, statusCode int) bool { + var awsErr awserr.RequestFailure + if errors.As(err, &awsErr) { + return awsErr.StatusCode() == statusCode + } + return false +} diff --git a/vendor/github.com/hashicorp/aws-sdk-go-base/validation.go b/vendor/github.com/hashicorp/aws-sdk-go-base/validation.go new file mode 100644 index 000000000..0e97557c3 --- /dev/null +++ b/vendor/github.com/hashicorp/aws-sdk-go-base/validation.go @@ -0,0 +1,44 @@ +package awsbase + +import ( + "fmt" + + "github.com/aws/aws-sdk-go/aws/endpoints" +) + +// ValidateAccountID checks if the given AWS account ID is specifically allowed or forbidden. +// The allowedAccountIDs can be used as a whitelist and forbiddenAccountIDs can be used as a blacklist. +func ValidateAccountID(accountID string, allowedAccountIDs, forbiddenAccountIDs []string) error { + if len(forbiddenAccountIDs) > 0 { + for _, forbiddenAccountID := range forbiddenAccountIDs { + if accountID == forbiddenAccountID { + return fmt.Errorf("Forbidden AWS Account ID: %s", accountID) + } + } + } + + if len(allowedAccountIDs) > 0 { + for _, allowedAccountID := range allowedAccountIDs { + if accountID == allowedAccountID { + return nil + } + } + + return fmt.Errorf("AWS Account ID not allowed: %s", accountID) + } + + return nil +} + +// ValidateRegion checks if the given region is a valid AWS region. +func ValidateRegion(region string) error { + for _, partition := range endpoints.DefaultPartitions() { + for _, partitionRegion := range partition.Regions() { + if region == partitionRegion.ID() { + return nil + } + } + } + + return fmt.Errorf("Invalid AWS Region: %s", region) +} diff --git a/vendor/github.com/hashicorp/go-cty-funcs/LICENSE b/vendor/github.com/hashicorp/go-cty-funcs/LICENSE new file mode 100644 index 000000000..c33dcc7c9 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty-funcs/LICENSE @@ -0,0 +1,354 @@ +Mozilla Public License, version 2.0 + +1. Definitions + +1.1. “Contributor” + + means each individual or legal entity that creates, contributes to the + creation of, or owns Covered Software. + +1.2. “Contributor Version” + + means the combination of the Contributions of others (if any) used by a + Contributor and that particular Contributor’s Contribution. + +1.3. “Contribution” + + means Covered Software of a particular Contributor. + +1.4. “Covered Software” + + means Source Code Form to which the initial Contributor has attached the + notice in Exhibit A, the Executable Form of such Source Code Form, and + Modifications of such Source Code Form, in each case including portions + thereof. + +1.5. “Incompatible With Secondary Licenses” + means + + a. that the initial Contributor has attached the notice described in + Exhibit B to the Covered Software; or + + b. that the Covered Software was made available under the terms of version + 1.1 or earlier of the License, but not also under the terms of a + Secondary License. + +1.6. “Executable Form” + + means any form of the work other than Source Code Form. + +1.7. “Larger Work” + + means a work that combines Covered Software with other material, in a separate + file or files, that is not Covered Software. + +1.8. “License” + + means this document. + +1.9. “Licensable” + + means having the right to grant, to the maximum extent possible, whether at the + time of the initial grant or subsequently, any and all of the rights conveyed by + this License. + +1.10. “Modifications” + + means any of the following: + + a. any file in Source Code Form that results from an addition to, deletion + from, or modification of the contents of Covered Software; or + + b. any new file in Source Code Form that contains any Covered Software. + +1.11. “Patent Claims” of a Contributor + + means any patent claim(s), including without limitation, method, process, + and apparatus claims, in any patent Licensable by such Contributor that + would be infringed, but for the grant of the License, by the making, + using, selling, offering for sale, having made, import, or transfer of + either its Contributions or its Contributor Version. + +1.12. “Secondary License” + + means either the GNU General Public License, Version 2.0, the GNU Lesser + General Public License, Version 2.1, the GNU Affero General Public + License, Version 3.0, or any later versions of those licenses. + +1.13. “Source Code Form” + + means the form of the work preferred for making modifications. + +1.14. “You” (or “Your”) + + means an individual or a legal entity exercising rights under this + License. For legal entities, “You” includes any entity that controls, is + controlled by, or is under common control with You. For purposes of this + definition, “control” means (a) the power, direct or indirect, to cause + the direction or management of such entity, whether by contract or + otherwise, or (b) ownership of more than fifty percent (50%) of the + outstanding shares or beneficial ownership of such entity. + + +2. License Grants and Conditions + +2.1. Grants + + Each Contributor hereby grants You a world-wide, royalty-free, + non-exclusive license: + + a. under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or as + part of a Larger Work; and + + b. under Patent Claims of such Contributor to make, use, sell, offer for + sale, have made, import, and otherwise transfer either its Contributions + or its Contributor Version. + +2.2. Effective Date + + The licenses granted in Section 2.1 with respect to any Contribution become + effective for each Contribution on the date the Contributor first distributes + such Contribution. + +2.3. Limitations on Grant Scope + + The licenses granted in this Section 2 are the only rights granted under this + License. No additional rights or licenses will be implied from the distribution + or licensing of Covered Software under this License. Notwithstanding Section + 2.1(b) above, no patent license is granted by a Contributor: + + a. for any code that a Contributor has removed from Covered Software; or + + b. for infringements caused by: (i) Your and any other third party’s + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + + c. under Patent Claims infringed by Covered Software in the absence of its + Contributions. + + This License does not grant any rights in the trademarks, service marks, or + logos of any Contributor (except as may be necessary to comply with the + notice requirements in Section 3.4). + +2.4. Subsequent Licenses + + No Contributor makes additional grants as a result of Your choice to + distribute the Covered Software under a subsequent version of this License + (see Section 10.2) or under the terms of a Secondary License (if permitted + under the terms of Section 3.3). + +2.5. Representation + + Each Contributor represents that the Contributor believes its Contributions + are its original creation(s) or it has sufficient rights to grant the + rights to its Contributions conveyed by this License. + +2.6. Fair Use + + This License is not intended to limit any rights You have under applicable + copyright doctrines of fair use, fair dealing, or other equivalents. + +2.7. Conditions + + Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in + Section 2.1. + + +3. Responsibilities + +3.1. Distribution of Source Form + + All distribution of Covered Software in Source Code Form, including any + Modifications that You create or to which You contribute, must be under the + terms of this License. You must inform recipients that the Source Code Form + of the Covered Software is governed by the terms of this License, and how + they can obtain a copy of this License. You may not attempt to alter or + restrict the recipients’ rights in the Source Code Form. + +3.2. Distribution of Executable Form + + If You distribute Covered Software in Executable Form then: + + a. such Covered Software must also be made available in Source Code Form, + as described in Section 3.1, and You must inform recipients of the + Executable Form how they can obtain a copy of such Source Code Form by + reasonable means in a timely manner, at a charge no more than the cost + of distribution to the recipient; and + + b. You may distribute such Executable Form under the terms of this License, + or sublicense it under different terms, provided that the license for + the Executable Form does not attempt to limit or alter the recipients’ + rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + + You may create and distribute a Larger Work under terms of Your choice, + provided that You also comply with the requirements of this License for the + Covered Software. If the Larger Work is a combination of Covered Software + with a work governed by one or more Secondary Licenses, and the Covered + Software is not Incompatible With Secondary Licenses, this License permits + You to additionally distribute such Covered Software under the terms of + such Secondary License(s), so that the recipient of the Larger Work may, at + their option, further distribute the Covered Software under the terms of + either this License or such Secondary License(s). + +3.4. Notices + + You may not remove or alter the substance of any license notices (including + copyright notices, patent notices, disclaimers of warranty, or limitations + of liability) contained within the Source Code Form of the Covered + Software, except that You may alter any license notices to the extent + required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + + You may choose to offer, and to charge a fee for, warranty, support, + indemnity or liability obligations to one or more recipients of Covered + Software. However, You may do so only on Your own behalf, and not on behalf + of any Contributor. You must make it absolutely clear that any such + warranty, support, indemnity, or liability obligation is offered by You + alone, and You hereby agree to indemnify every Contributor for any + liability incurred by such Contributor as a result of warranty, support, + indemnity or liability terms You offer. You may include additional + disclaimers of warranty and limitations of liability specific to any + jurisdiction. + +4. Inability to Comply Due to Statute or Regulation + + If it is impossible for You to comply with any of the terms of this License + with respect to some or all of the Covered Software due to statute, judicial + order, or regulation then You must: (a) comply with the terms of this License + to the maximum extent possible; and (b) describe the limitations and the code + they affect. Such description must be placed in a text file included with all + distributions of the Covered Software under this License. Except to the + extent prohibited by statute or regulation, such description must be + sufficiently detailed for a recipient of ordinary skill to be able to + understand it. + +5. Termination + +5.1. The rights granted under this License will terminate automatically if You + fail to comply with any of its terms. However, if You become compliant, + then the rights granted under this License from a particular Contributor + are reinstated (a) provisionally, unless and until such Contributor + explicitly and finally terminates Your grants, and (b) on an ongoing basis, + if such Contributor fails to notify You of the non-compliance by some + reasonable means prior to 60 days after You have come back into compliance. + Moreover, Your grants from a particular Contributor are reinstated on an + ongoing basis if such Contributor notifies You of the non-compliance by + some reasonable means, this is the first time You have received notice of + non-compliance with this License from such Contributor, and You become + compliant prior to 30 days after Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent + infringement claim (excluding declaratory judgment actions, counter-claims, + and cross-claims) alleging that a Contributor Version directly or + indirectly infringes any patent, then the rights granted to You by any and + all Contributors for the Covered Software under Section 2.1 of this License + shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user + license agreements (excluding distributors and resellers) which have been + validly granted by You or Your distributors under this License prior to + termination shall survive termination. + +6. Disclaimer of Warranty + + Covered Software is provided under this License on an “as is” basis, without + warranty of any kind, either expressed, implied, or statutory, including, + without limitation, warranties that the Covered Software is free of defects, + merchantable, fit for a particular purpose or non-infringing. The entire + risk as to the quality and performance of the Covered Software is with You. + Should any Covered Software prove defective in any respect, You (not any + Contributor) assume the cost of any necessary servicing, repair, or + correction. This disclaimer of warranty constitutes an essential part of this + License. No use of any Covered Software is authorized under this License + except under this disclaimer. + +7. Limitation of Liability + + Under no circumstances and under no legal theory, whether tort (including + negligence), contract, or otherwise, shall any Contributor, or anyone who + distributes Covered Software as permitted above, be liable to You for any + direct, indirect, special, incidental, or consequential damages of any + character including, without limitation, damages for lost profits, loss of + goodwill, work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses, even if such party shall have been + informed of the possibility of such damages. This limitation of liability + shall not apply to liability for death or personal injury resulting from such + party’s negligence to the extent applicable law prohibits such limitation. + Some jurisdictions do not allow the exclusion or limitation of incidental or + consequential damages, so this exclusion and limitation may not apply to You. + +8. Litigation + + Any litigation relating to this License may be brought only in the courts of + a jurisdiction where the defendant maintains its principal place of business + and such litigation shall be governed by laws of that jurisdiction, without + reference to its conflict-of-law provisions. Nothing in this Section shall + prevent a party’s ability to bring cross-claims or counter-claims. + +9. Miscellaneous + + This License represents the complete agreement concerning the subject matter + hereof. If any provision of this License is held to be unenforceable, such + provision shall be reformed only to the extent necessary to make it + enforceable. Any law or regulation which provides that the language of a + contract shall be construed against the drafter shall not be used to construe + this License against a Contributor. + + +10. Versions of the License + +10.1. New Versions + + Mozilla Foundation is the license steward. Except as provided in Section + 10.3, no one other than the license steward has the right to modify or + publish new versions of this License. Each version will be given a + distinguishing version number. + +10.2. Effect of New Versions + + You may distribute the Covered Software under the terms of the version of + the License under which You originally received the Covered Software, or + under the terms of any subsequent version published by the license + steward. + +10.3. Modified Versions + + If you create software not governed by this License, and you want to + create a new license for such software, you may create and use a modified + version of this License if you rename the license and remove any + references to the name of the license steward (except to note that such + modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses + If You choose to distribute Source Code Form that is Incompatible With + Secondary Licenses under the terms of this version of the License, the + notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice + + This Source Code Form is subject to the + terms of the Mozilla Public License, v. + 2.0. If a copy of the MPL was not + distributed with this file, You can + obtain one at + http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, then +You may include the notice in a location (such as a LICENSE file in a relevant +directory) where a recipient would be likely to look for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - “Incompatible With Secondary Licenses” Notice + + This Source Code Form is “Incompatible + With Secondary Licenses”, as defined by + the Mozilla Public License, v. 2.0. + diff --git a/vendor/github.com/hashicorp/go-cty-funcs/collection/coalesce.go b/vendor/github.com/hashicorp/go-cty-funcs/collection/coalesce.go new file mode 100644 index 000000000..75b6ca8e8 --- /dev/null +++ b/vendor/github.com/hashicorp/go-cty-funcs/collection/coalesce.go @@ -0,0 +1,60 @@ +package collection + +import ( + "errors" + + "github.com/zclconf/go-cty/cty" + "github.com/zclconf/go-cty/cty/convert" + "github.com/zclconf/go-cty/cty/function" +) + +// Coalesce takes any number of arguments and returns the first one that isn't +// empty. +func Coalesce(args ...cty.Value) (cty.Value, error) { + return CoalesceFunc.Call(args) +} + +// CoalesceFunc constructs a function that takes any number of arguments and +// returns the first one that isn't empty. This function was copied from go-cty +// stdlib and modified so that it returns the first *non-empty* non-null +// element from a sequence, instead of merely the first non-null. +var CoalesceFunc = function.New(&function.Spec{ + Params: []function.Parameter{}, + VarParam: &function.Parameter{ + Name: "vals", + Type: cty.DynamicPseudoType, + AllowUnknown: true, + AllowDynamicType: true, + AllowNull: true, + }, + Type: func(args []cty.Value) (ret cty.Type, err error) { + argTypes := make([]cty.Type, len(args)) + for i, val := range args { + argTypes[i] = val.Type() + } + retType, _ := convert.UnifyUnsafe(argTypes) + if retType == cty.NilType { + return cty.NilType, errors.New("all arguments must have the same type") + } + return retType, nil + }, + Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { + for _, argVal := range args { + // We already know this will succeed because of the checks in our + // Type func above + argVal, _ = convert.Convert(argVal, retType) + if !argVal.IsKnown() { + return cty.UnknownVal(retType), nil + } + if argVal.IsNull() { + continue + } + if retType == cty.String && argVal.RawEquals(cty.StringVal("")) { + continue + } + + return argVal, nil + } + return cty.NilVal, errors.New("no non-null, non-empty-string arguments") + }, +}) diff --git a/vendor/github.com/moul/anonuuid/.gitignore b/vendor/github.com/moul/anonuuid/.gitignore deleted file mode 100644 index 8124bf789..000000000 --- a/vendor/github.com/moul/anonuuid/.gitignore +++ /dev/null @@ -1,28 +0,0 @@ -anonuuid - -/dist - -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/vendor/github.com/moul/anonuuid/.godir b/vendor/github.com/moul/anonuuid/.godir deleted file mode 100644 index ea28ac285..000000000 --- a/vendor/github.com/moul/anonuuid/.godir +++ /dev/null @@ -1 +0,0 @@ -github.com/moul/anonuuid diff --git a/vendor/github.com/moul/anonuuid/.goxc.json b/vendor/github.com/moul/anonuuid/.goxc.json deleted file mode 100644 index 16f0b4589..000000000 --- a/vendor/github.com/moul/anonuuid/.goxc.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "AppName": "anonuuid", - "ArtifactsDest": "dist", - "OutPath": "{{.Dest}}{{.PS}}{{.Version}}{{.PS}}{{.Os}}_{{.Arch}}{{.PS}}{{.ExeName}}{{.Ext}}", - "TasksExclude": [ - "go-test", - "go-vet" - ], - "MainDirsExclude": "vendor,Godeps,testdata", - "PackageVersion": "1.0", - "ConfigVersion": "0.9" -} diff --git a/vendor/github.com/moul/anonuuid/.travis.yml b/vendor/github.com/moul/anonuuid/.travis.yml deleted file mode 100644 index 94f52d1b6..000000000 --- a/vendor/github.com/moul/anonuuid/.travis.yml +++ /dev/null @@ -1,30 +0,0 @@ -language: go - - -go: -- 1.3 -- 1.4 -- 1.5 -- tip - - -matrix: - allow_failures: - - go: tip - - -before_install: -- go get -u github.com/axw/gocov/gocov -- go get -u github.com/mattn/goveralls -- go get golang.org/x/tools/cmd/cover - - -#install: -#- go get -d -v -t ./... - - -script: -- go build -v ./cmd/... -- go test -v ./ -- go test -covermode=count -coverprofile=profile.out . -- goveralls -covermode=count -service=travis-ci -v -coverprofile=profile.out diff --git a/vendor/github.com/moul/anonuuid/LICENSE b/vendor/github.com/moul/anonuuid/LICENSE deleted file mode 100644 index 492e2c629..000000000 --- a/vendor/github.com/moul/anonuuid/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Manfred Touron - -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/moul/anonuuid/Makefile b/vendor/github.com/moul/anonuuid/Makefile deleted file mode 100644 index 4e2f3bb44..000000000 --- a/vendor/github.com/moul/anonuuid/Makefile +++ /dev/null @@ -1,73 +0,0 @@ -# Project-specific variables -BINARIES ?= anonuuid -CONVEY_PORT ?= 9042 - - -# Common variables -SOURCES := $(shell find . -name "*.go") -COMMANDS := $(shell go list ./... | grep -v /vendor/ | grep /cmd/) -PACKAGES := $(shell go list ./... | grep -v /vendor/ | grep -v /cmd/) -GOENV ?= GO15VENDOREXPERIMENT=1 -GO ?= $(GOENV) go -GODEP ?= $(GOENV) godep -USER ?= $(shell whoami) - - -all: build - - -.PHONY: build -build: $(BINARIES) - - -$(BINARIES): $(SOURCES) - $(GO) build -o $@ ./cmd/$@ - - -.PHONY: test -test: - $(GO) get -t . - $(GO) test -v . - - -.PHONY: godep-save -godep-save: - $(GODEP) save $(PACKAGES) $(COMMANDS) - - -.PHONY: clean -clean: - rm -f $(BINARIES) - - -.PHONY: re -re: clean all - - -.PHONY: convey -convey: - $(GO) get github.com/smartystreets/goconvey - goconvey -cover -port=$(CONVEY_PORT) -workDir="$(realpath .)" -depth=1 - - -.PHONY: cover -cover: profile.out - - -profile.out: $(SOURCES) - rm -f $@ - $(GO) test -covermode=count -coverpkg=. -coverprofile=$@ . - - -.PHONY: docker-build -docker-build: - go get github.com/laher/goxc - rm -rf contrib/docker/linux_386 - for binary in $(BINARIES); do \ - goxc -bc="linux,386" -d . -pv contrib/docker -n $$binary xc; \ - mv contrib/docker/linux_386/$$binary contrib/docker/entrypoint; \ - docker build -t $(USER)/$$binary contrib/docker; \ - docker run -it --rm $(USER)/$$binary || true; \ - docker inspect --type=image --format="{{ .Id }}" moul/$$binary || true; \ - echo "Now you can run 'docker push $(USER)/$$binary'"; \ - done diff --git a/vendor/github.com/moul/anonuuid/README.md b/vendor/github.com/moul/anonuuid/README.md deleted file mode 100644 index f5c9a57eb..000000000 --- a/vendor/github.com/moul/anonuuid/README.md +++ /dev/null @@ -1,170 +0,0 @@ -# AnonUUID - -[![Build Status](https://travis-ci.org/moul/anonuuid.svg)](https://travis-ci.org/moul/anonuuid) -[![GoDoc](https://godoc.org/github.com/moul/anonuuid?status.svg)](https://godoc.org/github.com/moul/anonuuid) -[![Coverage Status](https://coveralls.io/repos/moul/anonuuid/badge.svg?branch=master&service=github)](https://coveralls.io/github/moul/anonuuid?branch=master) - -:wrench: Anonymize UUIDs outputs (written in Golang) - -![AnonUUID Logo](https://raw.githubusercontent.com/moul/anonuuid/master/assets/anonuuid.png) - -**anonuuid** anonymize an input string by replacing all UUIDs by an anonymized -new one. - -The fake UUIDs are cached, so if AnonUUID encounter the same real UUIDs multiple -times, the translation will be the same. - -## Usage - -```console -$ anonuuid --help -NAME: - anonuuid - Anonymize UUIDs outputs - -USAGE: - anonuuid [global options] command [command options] [arguments...] - -VERSION: - 1.0.0-dev - -AUTHOR(S): - Manfred Touron - -COMMANDS: - help, h Shows a list of commands or help for one command - -GLOBAL OPTIONS: - --hexspeak Generate hexspeak style fake UUIDs - --random, -r Generate random fake UUIDs - --keep-beginning Keep first part of the UUID unchanged - --keep-end Keep last part of the UUID unchanged - --prefix, -p Prefix generated UUIDs - --suffix Suffix generated UUIDs - --help, -h show help - --version, -v print the version - ``` - -## Example - -Replace all UUIDs and cache the correspondance. - -```command -$ anonuuid git:(master) ✗ cat < 32 { - part = part[:32] - } - uuid := part[:8] + "-" + part[8:12] + "-1" + part[13:16] + "-" + part[16:20] + "-" + part[20:32] - - err := IsUUID(uuid) - if err != nil { - return "", err - } - - return uuid, nil -} - -// GenerateRandomUUID returns an UUID based on random strings -func GenerateRandomUUID(length int) (string, error) { - var letters = []rune("abcdef0123456789") - - b := make([]rune, length) - for i := range b { - b[i] = letters[rand.Intn(len(letters))] - } - return FormatUUID(string(b)) -} - -// GenerateHexspeakUUID returns an UUID formatted string containing hexspeak words -func GenerateHexspeakUUID(i int) (string, error) { - if i < 0 { - i = -i - } - hexspeaks := []string{ - "0ff1ce", - "31337", - "4b1d", - "badc0de", - "badcafe", - "badf00d", - "deadbabe", - "deadbeef", - "deadc0de", - "deadfeed", - "fee1bad", - } - return FormatUUID(hexspeaks[i%len(hexspeaks)]) -} - -// GenerateLenUUID returns an UUID formatted string based on an index number -func GenerateLenUUID(i int) (string, error) { - if i < 0 { - i = 2<<29 + i - } - return FormatUUID(fmt.Sprintf("%x", i)) -} diff --git a/vendor/github.com/moul/gotty-client/.gitignore b/vendor/github.com/moul/gotty-client/.gitignore deleted file mode 100644 index ef713932b..000000000 --- a/vendor/github.com/moul/gotty-client/.gitignore +++ /dev/null @@ -1,27 +0,0 @@ -/gotty-client -/dist - -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof diff --git a/vendor/github.com/moul/gotty-client/.goxc.json b/vendor/github.com/moul/gotty-client/.goxc.json deleted file mode 100644 index 3c3675a6e..000000000 --- a/vendor/github.com/moul/gotty-client/.goxc.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "AppName": "gotty-client", - "ArtifactsDest": "dist", - "BuildConstraints": "!plan9,!nacl,!solaris", - "OutPath": "{{.Dest}}{{.PS}}{{.Version}}{{.PS}}{{.ExeName}}_{{.Version}}_{{.Os}}_{{.Arch}}{{.Ext}}", - "TasksExclude": [ - "go-test", - "go-vet" - ], - "MainDirsExclude": "vendor,Godeps,testdata", - "PackageVersion": "1.6.1+dev", - "ConfigVersion": "0.9" -} diff --git a/vendor/github.com/moul/gotty-client/.travis.yml b/vendor/github.com/moul/gotty-client/.travis.yml deleted file mode 100644 index d0ae7abcb..000000000 --- a/vendor/github.com/moul/gotty-client/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: go - -go: -- 1.7 -- 1.8 -- tip - -matrix: - allow_failures: - - go: tip - -script: -- go build ./cmd/... -- go run ./cmd/gotty-client/main.go --help || true diff --git a/vendor/github.com/moul/gotty-client/Dockerfile b/vendor/github.com/moul/gotty-client/Dockerfile deleted file mode 100644 index e598be675..000000000 --- a/vendor/github.com/moul/gotty-client/Dockerfile +++ /dev/null @@ -1,11 +0,0 @@ -# build -FROM golang:1.9 as builder -RUN apt update && apt -y install jq -COPY . /go/src/github.com/moul/gotty-client -WORKDIR /go/src/github.com/moul/gotty-client -RUN make install - -# minimal runtime -FROM scratch -COPY --from=builder /go/bin/gotty-client /bin/gotty-client -ENTRYPOINT ["/bin/gotty-client"] diff --git a/vendor/github.com/moul/gotty-client/LICENSE b/vendor/github.com/moul/gotty-client/LICENSE deleted file mode 100644 index 492e2c629..000000000 --- a/vendor/github.com/moul/gotty-client/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Manfred Touron - -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/moul/gotty-client/LICENSE.apache b/vendor/github.com/moul/gotty-client/LICENSE.apache deleted file mode 100644 index 6fe259dd5..000000000 --- a/vendor/github.com/moul/gotty-client/LICENSE.apache +++ /dev/null @@ -1,192 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2013-2017 Docker, Inc. - - 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 - - https://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. - diff --git a/vendor/github.com/moul/gotty-client/Makefile b/vendor/github.com/moul/gotty-client/Makefile deleted file mode 100644 index e8ff3b579..000000000 --- a/vendor/github.com/moul/gotty-client/Makefile +++ /dev/null @@ -1,73 +0,0 @@ -# Project-specific variables -BINARIES ?= gotty-client -GOTTY_URL := http://localhost:8081/ -VERSION := $(shell cat .goxc.json | jq -c .PackageVersion | sed 's/"//g') - -CONVEY_PORT ?= 9042 - - -# Common variables -SOURCES := $(shell find . -type f -name "*.go") -COMMANDS := $(shell go list ./... | grep -v /vendor/ | grep /cmd/) -PACKAGES := $(shell go list ./... | grep -v /vendor/ | grep -v /cmd/) -GOENV ?= GO15VENDOREXPERIMENT=1 -GO ?= $(GOENV) go -GODEP ?= $(GOENV) godep -USER ?= $(shell whoami) - - -all: build - - -.PHONY: build -build: $(BINARIES) - - -.PHONY: install -install: - $(GO) install ./cmd/gotty-client - - -$(BINARIES): $(SOURCES) - $(GO) build -i -o $@ ./cmd/$@ - - -.PHONY: test -test: -# $(GO) get -t . - $(GO) test -i -v . - $(GO) test -v . - - -.PHONY: godep-save -godep-save: - $(GODEP) save $(PACKAGES) $(COMMANDS) - - -.PHONY: clean -clean: - rm -f $(BINARIES) - - -.PHONY: re -re: clean all - - -.PHONY: convey -convey: - $(GO) get github.com/smartystreets/goconvey - goconvey -cover -port=$(CONVEY_PORT) -workDir="$(realpath .)" -depth=1 - - -.PHONY: cover -cover: profile.out - - -profile.out: $(SOURCES) - rm -f $@ - $(GO) test -covermode=count -coverpkg=. -coverprofile=$@ . - - -.PHONY: docker-build -docker-build: - docker build -t moul/gotty-client . diff --git a/vendor/github.com/moul/gotty-client/README.md b/vendor/github.com/moul/gotty-client/README.md deleted file mode 100644 index 91d3be331..000000000 --- a/vendor/github.com/moul/gotty-client/README.md +++ /dev/null @@ -1,205 +0,0 @@ -# gotty-client -:wrench: Terminal client for [GoTTY](https://github.com/yudai/gotty). - -![](https://raw.githubusercontent.com/moul/gotty-client/master/resources/gotty-client.png) - -[![Build Status](https://travis-ci.org/moul/gotty-client.svg?branch=master)](https://travis-ci.org/moul/gotty-client) -[![GoDoc](https://godoc.org/github.com/moul/gotty-client?status.svg)](https://godoc.org/github.com/moul/gotty-client) -[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmoul%2Fgotty-client.svg?type=shield)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmoul%2Fgotty-client?ref=badge_shield) - -```ruby - ┌─────────────────┐ - ┌──────▶│ /bin/bash │ - │ └─────────────────┘ - ┌──────────────┐ ┌──────────┐ - │ │ │ Gotty │ -┌───────┐ ┌──▶│ Browser │───────┐ │ │ -│ │ │ │ │ │ │ │ -│ │ │ └──────────────┘ │ │ │ ┌─────────────────┐ -│ Bob │───┤ websockets─▶│ │─▶│ emacs /var/www │ -│ │ │ ╔═ ══ ══ ══ ══ ╗ │ │ │ └─────────────────┘ -│ │ │ ║ ║ │ │ │ -└───────┘ └──▶║ gotty-client ───────┘ │ │ - ║ │ │ - ╚═ ══ ══ ══ ══ ╝ └──────────┘ - │ ┌─────────────────┐ - └──────▶│ tmux attach │ - └─────────────────┘ -``` - -## Example - -Server side ([GoTTY](https://github.com/yudai/gotty)) - -```console -$ gotty -p 9191 sh -c 'while true; do date; sleep 1; done' -2015/08/24 18:54:31 Server is starting with command: sh -c while true; do date; sleep 1; done -2015/08/24 18:54:31 URL: http://[::1]:9191/ -2015/08/24 18:54:34 GET /ws -2015/08/24 18:54:34 New client connected: 127.0.0.1:61811 -2015/08/24 18:54:34 Command is running for client 127.0.0.1:61811 with PID 64834 -2015/08/24 18:54:39 Command exited for: 127.0.0.1:61811 -2015/08/24 18:54:39 Connection closed: 127.0.0.1:61811 -... -``` - -**Client side** - -```console -$ gotty-client http://localhost:9191/ -INFO[0000] New title: GoTTY - sh -c while true; do date; sleep 1; done (jean-michel-van-damme.local) -WARN[0000] Unhandled protocol message: json pref: 2{} -Mon Aug 24 18:54:34 CEST 2015 -Mon Aug 24 18:54:35 CEST 2015 -Mon Aug 24 18:54:36 CEST 2015 -Mon Aug 24 18:54:37 CEST 2015 -Mon Aug 24 18:54:38 CEST 2015 -^C -``` - -## Usage - -```console -$ gotty-client -h -NAME: - gotty-client - GoTTY client for your terminal - -USAGE: - gotty-client [global options] command [command options] GOTTY_URL - -VERSION: - 1.3.0+ - -AUTHOR(S): - Manfred Touron - -COMMANDS: - help, h Shows a list of commands or help for one command - -GLOBAL OPTIONS: - --debug, -D Enable debug mode [$GOTTY_CLIENT_DEBUG] - --help, -h show help - --version, -v print the version -``` - -## Install - -Install latest version using Golang (recommended) - -```console -$ go get github.com/moul/gotty-client/cmd/gotty-client -``` - ---- - -Install latest version using Homebrew (Mac OS X) - -```console -$ brew install https://raw.githubusercontent.com/moul/gotty-client/master/contrib/homebrew/gotty-client.rb --HEAD -``` - -or the latest released version - -```console -$ brew install https://raw.githubusercontent.com/moul/gotty-client/master/contrib/homebrew/gotty-client.rb -``` - -## Changelog - -### master (unreleased) - -* Add `--detach-keys` option ([#52](https://github.com/moul/gotty-client/issues/52)) - -[full commits list](https://github.com/moul/gotty-client/compare/v1.6.1...master) - -### [v1.6.1](https://github.com/moul/gotty-client/releases/tag/v1.6.1) (2017-01-19) - -* Do not exit on EOF ([#45](https://github.com/moul/gotty-client/pull/45)) ([@gurjeet](https://github.com/gurjeet)) - -[full commits list](https://github.com/moul/gotty-client/compare/v1.6.0...v1.6.1) - -### [v1.6.0](https://github.com/moul/gotty-client/releases/tag/v1.6.0) (2016-05-23) - -* Support of `--use-proxy-from-env` (Add Proxy support) ([#36](https://github.com/moul/gotty-client/pull/36)) ([@byung2](https://github.com/byung2)) -* Add debug mode ([#18](https://github.com/moul/gotty-client/issues/18)) -* Fix argument passing ([#16](https://github.com/moul/gotty-client/issues/16)) -* Remove warnings + golang fixes and refactoring ([@QuentinPerez](https://github.com/QuentinPerez)) - -[full commits list](https://github.com/moul/gotty-client/compare/v1.5.0...v1.6.0) - -### [v1.5.0](https://github.com/moul/gotty-client/releases/tag/v1.5.0) (2016-02-18) - -* Add autocomplete support ([#19](https://github.com/moul/gotty-client/issues/19)) -* Switch from `Party` to `Godep` -* Fix terminal data being interpreted as format string ([#34](https://github.com/moul/gotty-client/pull/34)) ([@mickael9](https://github.com/mickael9)) - -[full commits list](https://github.com/moul/gotty-client/compare/v1.4.0...v1.5.0) - -### [v1.4.0](https://github.com/moul/gotty-client/releases/tag/v1.4.0) (2015-12-09) - -* Remove solaris,plan9,nacl for `.goxc.json` -* Add an error if the go version is lower than 1.5 -* Flexible parsing of the input URL -* Add tests -* Support of `--skip-tls-verify` - -[full commits list](https://github.com/moul/gotty-client/compare/v1.3.0...v1.4.0) - -### [v1.3.0](https://github.com/moul/gotty-client/releases/tag/v1.3.0) (2015-10-27) - -* Fix `connected` state when using `Connect()` + `Loop()` methods -* Add `ExitLoop` which allow to exit from `Loop` function - -[full commits list](https://github.com/moul/gotty-client/compare/v1.2.0...v1.3.0) - -### [v1.2.0](https://github.com/moul/gotty-client/releases/tag/v1.2.0) (2015-10-23) - -* Removed an annoying warning when exiting connection ([#22](https://github.com/moul/gotty-client/issues/22)) ([@QuentinPerez](https://github.com/QuentinPerez)) -* Add the ability to configure alternative stdout ([#21](https://github.com/moul/gotty-client/issues/21)) ([@QuentinPerez](https://github.com/QuentinPerez)) -* Refactored the goroutine system with select, improve speed and stability ([@QuentinPerez](https://github.com/QuentinPerez)) -* Add debug mode (`--debug`/`-D`) ([#18](https://github.com/moul/gotty-client/issues/18)) -* Improve error message when connecting by checking HTTP status code -* Fix arguments passing ([#16](https://github.com/moul/gotty-client/issues/16)) -* Dropped support for golang<1.5 -* Small fixes - -[full commits list](https://github.com/moul/gotty-client/compare/v1.1.0...v1.2.0) - -### [v1.1.0](https://github.com/moul/gotty-client/releases/tag/v1.1.0) (2015-10-10) - -* Handling arguments + using mutexes (thanks to [@QuentinPerez](https://github.com/QuentinPerez)) -* Add logo ([#9](https://github.com/moul/gotty-client/issues/9)) -* Using codegansta/cli for CLI parsing ([#3](https://github.com/moul/gotty-client/issues/3)) -* Fix panic when running on older GoTTY server ([#13](https://github.com/moul/gotty-client/issues/13)) -* Add 'homebrew support' ([#1](https://github.com/moul/gotty-client/issues/1)) -* Add Changelog ([#5](https://github.com/moul/gotty-client/issues/5)) -* Add GOXC configuration to build binaries for multiple architectures ([#2](https://github.com/moul/gotty-client/issues/2)) - -[full commits list](https://github.com/moul/gotty-client/compare/v1.0.1...v1.1.0) - -### [v1.0.1](https://github.com/moul/gotty-client/releases/tag/v1.0.1) (2015-09-27) - -* Using party to manage dependencies - -[full commits list](https://github.com/moul/gotty-client/compare/v1.0.0...v1.0.1) - -### [v1.0.0](https://github.com/moul/gotty-client/releases/tag/v1.0.0) (2015-09-27) - -Compatible with [GoTTY](https://github.com/yudai/gotty) version: [v0.0.10](https://github.com/yudai/gotty/releases/tag/v0.0.10) - -#### Features - -* Support **basic-auth** -* Support **terminal-(re)size** -* Support **write** -* Support **title** -* Support **custom URI** - -[full commits list](https://github.com/moul/gotty-client/compare/cf0c1146c7ce20fe0bd65764c13253bc575cd43a...v1.0.0) - -## License - -MIT - - -[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmoul%2Fgotty-client.svg?type=large)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmoul%2Fgotty-client?ref=badge_large) diff --git a/vendor/github.com/moul/gotty-client/arch.go b/vendor/github.com/moul/gotty-client/arch.go deleted file mode 100644 index 77a4deaec..000000000 --- a/vendor/github.com/moul/gotty-client/arch.go +++ /dev/null @@ -1,32 +0,0 @@ -// +build !windows - -package gottyclient - -import ( - "encoding/json" - "fmt" - "golang.org/x/sys/unix" - "os" - "os/signal" - "syscall" -) - -func notifySignalSIGWINCH(c chan<- os.Signal) { - signal.Notify(c, syscall.SIGWINCH) -} - -func resetSignalSIGWINCH() { - signal.Reset(syscall.SIGWINCH) -} - -func syscallTIOCGWINSZ() ([]byte, error) { - ws, err := unix.IoctlGetWinsize(0, 0) - if err != nil { - return nil, fmt.Errorf("ioctl error: %v", err) - } - b, err := json.Marshal(ws) - if err != nil { - return nil, fmt.Errorf("json.Marshal error: %v", err) - } - return b, err -} diff --git a/vendor/github.com/moul/gotty-client/arch_windows.go b/vendor/github.com/moul/gotty-client/arch_windows.go deleted file mode 100644 index 53aaffc5f..000000000 --- a/vendor/github.com/moul/gotty-client/arch_windows.go +++ /dev/null @@ -1,16 +0,0 @@ -package gottyclient - -import ( - "errors" - "os" -) - -func notifySignalSIGWINCH(c chan<- os.Signal) { -} - -func resetSignalSIGWINCH() { -} - -func syscallTIOCGWINSZ() ([]byte, error) { - return nil, errors.New("SIGWINCH isn't supported on this ARCH") -} diff --git a/vendor/github.com/moul/gotty-client/gotty-client.go b/vendor/github.com/moul/gotty-client/gotty-client.go deleted file mode 100644 index 58f4a8547..000000000 --- a/vendor/github.com/moul/gotty-client/gotty-client.go +++ /dev/null @@ -1,473 +0,0 @@ -package gottyclient - -import ( - "crypto/tls" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "os" - "regexp" - "strings" - "sync" - "time" - - "github.com/creack/goselect" - "github.com/gorilla/websocket" - "github.com/sirupsen/logrus" - "golang.org/x/crypto/ssh/terminal" -) - -// GetAuthTokenURL transforms a GoTTY http URL to its AuthToken file URL -func GetAuthTokenURL(httpURL string) (*url.URL, *http.Header, error) { - header := http.Header{} - target, err := url.Parse(httpURL) - if err != nil { - return nil, nil, err - } - - target.Path = strings.TrimLeft(target.Path+"auth_token.js", "/") - - if target.User != nil { - header.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(target.User.String()))) - target.User = nil - } - - return target, &header, nil -} - -// GetURLQuery returns url.query -func GetURLQuery(rawurl string) (url.Values, error) { - target, err := url.Parse(rawurl) - if err != nil { - return nil, err - } - return target.Query(), nil -} - -// GetWebsocketURL transforms a GoTTY http URL to its WebSocket URL -func GetWebsocketURL(httpURL string) (*url.URL, *http.Header, error) { - header := http.Header{} - target, err := url.Parse(httpURL) - if err != nil { - return nil, nil, err - } - - if target.Scheme == "https" { - target.Scheme = "wss" - } else { - target.Scheme = "ws" - } - - target.Path = strings.TrimLeft(target.Path+"ws", "/") - - if target.User != nil { - header.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(target.User.String()))) - target.User = nil - } - - return target, &header, nil -} - -type Client struct { - Dialer *websocket.Dialer - Conn *websocket.Conn - URL string - WriteMutex *sync.Mutex - Output io.Writer - poison chan bool - SkipTLSVerify bool - UseProxyFromEnv bool - Connected bool - EscapeKeys []byte -} - -type querySingleType struct { - AuthToken string `json:"AuthToken"` - Arguments string `json:"Arguments"` -} - -func (c *Client) write(data []byte) error { - c.WriteMutex.Lock() - defer c.WriteMutex.Unlock() - return c.Conn.WriteMessage(websocket.TextMessage, data) -} - -// GetAuthToken retrieves an Auth Token from dynamic auth_token.js file -func (c *Client) GetAuthToken() (string, error) { - target, header, err := GetAuthTokenURL(c.URL) - if err != nil { - return "", err - } - - logrus.Debugf("Fetching auth token auth-token: %q", target.String()) - req, err := http.NewRequest("GET", target.String(), nil) - req.Header = *header - tr := &http.Transport{} - if c.SkipTLSVerify { - conf := &tls.Config{InsecureSkipVerify: true} - tr.TLSClientConfig = conf - } - if c.UseProxyFromEnv { - tr.Proxy = http.ProxyFromEnvironment - } - client := &http.Client{Transport: tr} - resp, err := client.Do(req) - if err != nil { - return "", err - } - - switch resp.StatusCode { - case 200: - // Everything is OK - default: - return "", fmt.Errorf("unknown status code: %d (%s)", resp.StatusCode, http.StatusText(resp.StatusCode)) - } - - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return "", err - } - - re := regexp.MustCompile("var gotty_auth_token = '(.*)'") - output := re.FindStringSubmatch(string(body)) - if len(output) == 0 { - return "", fmt.Errorf("Cannot fetch GoTTY auth-token, please upgrade your GoTTY server.") - } - - return output[1], nil -} - -// Connect tries to dial a websocket server -func (c *Client) Connect() error { - // Retrieve AuthToken - authToken, err := c.GetAuthToken() - if err != nil { - return err - } - logrus.Debugf("Auth-token: %q", authToken) - - // Open WebSocket connection - target, header, err := GetWebsocketURL(c.URL) - if err != nil { - return err - } - logrus.Debugf("Connecting to websocket: %q", target.String()) - if c.SkipTLSVerify { - c.Dialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} - } - if c.UseProxyFromEnv { - c.Dialer.Proxy = http.ProxyFromEnvironment - } - conn, _, err := c.Dialer.Dial(target.String(), *header) - if err != nil { - return err - } - c.Conn = conn - c.Connected = true - - // Pass arguments and auth-token - query, err := GetURLQuery(c.URL) - if err != nil { - return err - } - querySingle := querySingleType{ - Arguments: "?" + query.Encode(), - AuthToken: authToken, - } - json, err := json.Marshal(querySingle) - if err != nil { - logrus.Errorf("Failed to parse init message %v", err) - return err - } - // Send Json - logrus.Debugf("Sending arguments and auth-token") - err = c.write(json) - if err != nil { - return err - } - - go c.pingLoop() - - return nil -} - -func (c *Client) pingLoop() { - for { - logrus.Debugf("Sending ping") - c.write([]byte("1")) - time.Sleep(30 * time.Second) - } -} - -// Close will nicely close the dialer -func (c *Client) Close() { - c.Conn.Close() -} - -// ExitLoop will kill all goroutines launched by c.Loop() -// ExitLoop() -> wait Loop() -> Close() -func (c *Client) ExitLoop() { - fname := "ExitLoop" - openPoison(fname, c.poison) -} - -// Loop will look indefinitely for new messages -func (c *Client) Loop() error { - if !c.Connected { - err := c.Connect() - if err != nil { - return err - } - } - - wg := &sync.WaitGroup{} - - wg.Add(1) - go c.termsizeLoop(wg) - - wg.Add(1) - go c.readLoop(wg) - - wg.Add(1) - go c.writeLoop(wg) - - /* Wait for all of the above goroutines to finish */ - wg.Wait() - - logrus.Debug("Client.Loop() exiting") - return nil -} - -type winsize struct { - Rows uint16 `json:"rows"` - Columns uint16 `json:"columns"` - // unused - x uint16 - y uint16 -} - -type posionReason int - -const ( - committedSuicide = iota - killed -) - -func openPoison(fname string, poison chan bool) posionReason { - logrus.Debug(fname + " suicide") - - /* - * The close() may raise panic if multiple goroutines commit suicide at the - * same time. Prevent that panic from bubbling up. - */ - defer func() { - if r := recover(); r != nil { - logrus.Debug("Prevented panic() of simultaneous suicides", r) - } - }() - - /* Signal others to die */ - close(poison) - return committedSuicide -} - -func die(fname string, poison chan bool) posionReason { - logrus.Debug(fname + " died") - - wasOpen := <-poison - if wasOpen { - logrus.Error("ERROR: The channel was open when it wasn't suppoed to be") - } - - return killed -} - -func (c *Client) termsizeLoop(wg *sync.WaitGroup) posionReason { - - defer wg.Done() - fname := "termsizeLoop" - - ch := make(chan os.Signal, 1) - notifySignalSIGWINCH(ch) - defer resetSignalSIGWINCH() - - for { - if b, err := syscallTIOCGWINSZ(); err != nil { - logrus.Warn(err) - } else { - if err = c.write(append([]byte("2"), b...)); err != nil { - logrus.Warnf("ws.WriteMessage failed: %v", err) - } - } - select { - case <-c.poison: - /* Somebody poisoned the well; die */ - return die(fname, c.poison) - case <-ch: - } - } -} - -type exposeFd interface { - Fd() uintptr -} - -func (c *Client) writeLoop(wg *sync.WaitGroup) posionReason { - defer wg.Done() - fname := "writeLoop" - - buff := make([]byte, 128) - oldState, err := terminal.MakeRaw(0) - if err == nil { - defer terminal.Restore(0, oldState) - } - - rdfs := &goselect.FDSet{} - reader := io.ReadCloser(os.Stdin) - - pr := NewEscapeProxy(reader, c.EscapeKeys) - defer reader.Close() - - for { - select { - case <-c.poison: - /* Somebody poisoned the well; die */ - return die(fname, c.poison) - default: - } - - rdfs.Zero() - rdfs.Set(reader.(exposeFd).Fd()) - err := goselect.Select(1, rdfs, nil, nil, 50*time.Millisecond) - if err != nil { - return openPoison(fname, c.poison) - } - if rdfs.IsSet(reader.(exposeFd).Fd()) { - size, err := pr.Read(buff) - - if err != nil { - if err == io.EOF { - // Send EOF to GoTTY - - // Send 'Input' marker, as defined in GoTTY::client_context.go, - // followed by EOT (a translation of Ctrl-D for terminals) - err = c.write(append([]byte("0"), byte(4))) - - if err != nil { - return openPoison(fname, c.poison) - } - continue - } else { - return openPoison(fname, c.poison) - } - } - - if size <= 0 { - continue - } - - data := buff[:size] - err = c.write(append([]byte("0"), data...)) - if err != nil { - return openPoison(fname, c.poison) - } - } - } -} - -func (c *Client) readLoop(wg *sync.WaitGroup) posionReason { - - defer wg.Done() - fname := "readLoop" - - type MessageNonBlocking struct { - Data []byte - Err error - } - msgChan := make(chan MessageNonBlocking) - - for { - go func() { - _, data, err := c.Conn.ReadMessage() - msgChan <- MessageNonBlocking{Data: data, Err: err} - }() - - select { - case <-c.poison: - /* Somebody poisoned the well; die */ - return die(fname, c.poison) - case msg := <-msgChan: - if msg.Err != nil { - - if _, ok := msg.Err.(*websocket.CloseError); !ok { - logrus.Warnf("c.Conn.ReadMessage: %v", msg.Err) - } - return openPoison(fname, c.poison) - } - if len(msg.Data) == 0 { - - logrus.Warnf("An error has occured") - return openPoison(fname, c.poison) - } - switch msg.Data[0] { - case '0': // data - buf, err := base64.StdEncoding.DecodeString(string(msg.Data[1:])) - if err != nil { - logrus.Warnf("Invalid base64 content: %q", msg.Data[1:]) - break - } - c.Output.Write(buf) - case '1': // pong - case '2': // new title - newTitle := string(msg.Data[1:]) - fmt.Fprintf(c.Output, "\033]0;%s\007", newTitle) - case '3': // json prefs - logrus.Debugf("Unhandled protocol message: json pref: %s", string(msg.Data[1:])) - case '4': // autoreconnect - logrus.Debugf("Unhandled protocol message: autoreconnect: %s", string(msg.Data)) - default: - logrus.Warnf("Unhandled protocol message: %s", string(msg.Data)) - } - } - } -} - -// SetOutput changes the output stream -func (c *Client) SetOutput(w io.Writer) { - c.Output = w -} - -// ParseURL parses an URL which may be incomplete and tries to standardize it -func ParseURL(input string) (string, error) { - parsed, err := url.Parse(input) - if err != nil { - return "", err - } - switch parsed.Scheme { - case "http", "https": - // everything is ok - default: - return ParseURL(fmt.Sprintf("http://%s", input)) - } - return parsed.String(), nil -} - -// NewClient returns a GoTTY client object -func NewClient(inputURL string) (*Client, error) { - url, err := ParseURL(inputURL) - if err != nil { - return nil, err - } - return &Client{ - Dialer: &websocket.Dialer{}, - URL: url, - WriteMutex: &sync.Mutex{}, - Output: os.Stdout, - poison: make(chan bool), - }, nil -} diff --git a/vendor/github.com/moul/gotty-client/proxy.go b/vendor/github.com/moul/gotty-client/proxy.go deleted file mode 100644 index e42143ca8..000000000 --- a/vendor/github.com/moul/gotty-client/proxy.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2013-2017 Docker, Inc. -// -// 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. - -// CHANGES: -// - update package - - -package gottyclient - -import ( - "io" -) - -// EscapeError is special error which returned by a TTY proxy reader's Read() -// method in case its detach escape sequence is read. -type EscapeError struct{} - -func (EscapeError) Error() string { - return "read escape sequence" -} - -// escapeProxy is used only for attaches with a TTY. It is used to proxy -// stdin keypresses from the underlying reader and look for the passed in -// escape key sequence to signal a detach. -type escapeProxy struct { - escapeKeys []byte - escapeKeyPos int - r io.Reader -} - -// NewEscapeProxy returns a new TTY proxy reader which wraps the given reader -// and detects when the specified escape keys are read, in which case the Read -// method will return an error of type EscapeError. -func NewEscapeProxy(r io.Reader, escapeKeys []byte) io.Reader { - return &escapeProxy{ - escapeKeys: escapeKeys, - r: r, - } -} - -func (r *escapeProxy) Read(buf []byte) (int, error) { - nr, err := r.r.Read(buf) - - preserve := func() { - // this preserves the original key presses in the passed in buffer - nr += r.escapeKeyPos - preserve := make([]byte, 0, r.escapeKeyPos+len(buf)) - preserve = append(preserve, r.escapeKeys[:r.escapeKeyPos]...) - preserve = append(preserve, buf...) - r.escapeKeyPos = 0 - copy(buf[0:nr], preserve) - } - - if nr != 1 || err != nil { - if r.escapeKeyPos > 0 { - preserve() - } - return nr, err - } - - if buf[0] != r.escapeKeys[r.escapeKeyPos] { - if r.escapeKeyPos > 0 { - preserve() - } - return nr, nil - } - - if r.escapeKeyPos == len(r.escapeKeys)-1 { - return 0, EscapeError{} - } - - // Looks like we've got an escape key, but we need to match again on the next - // read. - // Store the current escape key we found so we can look for the next one on - // the next read. - // Since this is an escape key, make sure we don't let the caller read it - // If later on we find that this is not the escape sequence, we'll add the - // keys back - r.escapeKeyPos++ - return nr - r.escapeKeyPos, nil -} diff --git a/vendor/github.com/renstrom/fuzzysearch/LICENSE b/vendor/github.com/renstrom/fuzzysearch/LICENSE deleted file mode 100644 index 9cc753370..000000000 --- a/vendor/github.com/renstrom/fuzzysearch/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Peter Renström - -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/renstrom/fuzzysearch/fuzzy/fuzzy.go b/vendor/github.com/renstrom/fuzzysearch/fuzzy/fuzzy.go deleted file mode 100644 index 63277d51e..000000000 --- a/vendor/github.com/renstrom/fuzzysearch/fuzzy/fuzzy.go +++ /dev/null @@ -1,167 +0,0 @@ -// Fuzzy searching allows for flexibly matching a string with partial input, -// useful for filtering data very quickly based on lightweight user input. -package fuzzy - -import ( - "unicode" - "unicode/utf8" -) - -var noop = func(r rune) rune { return r } - -// Match returns true if source matches target using a fuzzy-searching -// algorithm. Note that it doesn't implement Levenshtein distance (see -// RankMatch instead), but rather a simplified version where there's no -// approximation. The method will return true only if each character in the -// source can be found in the target and occurs after the preceding matches. -func Match(source, target string) bool { - return match(source, target, noop) -} - -// MatchFold is a case-insensitive version of Match. -func MatchFold(source, target string) bool { - return match(source, target, unicode.ToLower) -} - -func match(source, target string, fn func(rune) rune) bool { - lenDiff := len(target) - len(source) - - if lenDiff < 0 { - return false - } - - if lenDiff == 0 && source == target { - return true - } - -Outer: - for _, r1 := range source { - for i, r2 := range target { - if fn(r1) == fn(r2) { - target = target[i+utf8.RuneLen(r2):] - continue Outer - } - } - return false - } - - return true -} - -// Find will return a list of strings in targets that fuzzy matches source. -func Find(source string, targets []string) []string { - return find(source, targets, noop) -} - -// FindFold is a case-insensitive version of Find. -func FindFold(source string, targets []string) []string { - return find(source, targets, unicode.ToLower) -} - -func find(source string, targets []string, fn func(rune) rune) []string { - var matches []string - - for _, target := range targets { - if match(source, target, fn) { - matches = append(matches, target) - } - } - - return matches -} - -// RankMatch is similar to Match except it will measure the Levenshtein -// distance between the source and the target and return its result. If there -// was no match, it will return -1. -// Given the requirements of match, RankMatch only needs to perform a subset of -// the Levenshtein calculation, only deletions need be considered, required -// additions and substitutions would fail the match test. -func RankMatch(source, target string) int { - return rank(source, target, noop) -} - -// RankMatchFold is a case-insensitive version of RankMatch. -func RankMatchFold(source, target string) int { - return rank(source, target, unicode.ToLower) -} - -func rank(source, target string, fn func(rune) rune) int { - lenDiff := len(target) - len(source) - - if lenDiff < 0 { - return -1 - } - - if lenDiff == 0 && source == target { - return 0 - } - - runeDiff := 0 - -Outer: - for _, r1 := range source { - for i, r2 := range target { - if fn(r1) == fn(r2) { - target = target[i+utf8.RuneLen(r2):] - continue Outer - } else { - runeDiff++ - } - } - return -1 - } - - // Count up remaining char - for len(target) > 0 { - target = target[utf8.RuneLen(rune(target[0])):] - runeDiff++ - } - - return runeDiff -} - -// RankFind is similar to Find, except it will also rank all matches using -// Levenshtein distance. -func RankFind(source string, targets []string) Ranks { - var r Ranks - for _, target := range find(source, targets, noop) { - distance := LevenshteinDistance(source, target) - r = append(r, Rank{source, target, distance}) - } - return r -} - -// RankFindFold is a case-insensitive version of RankFind. -func RankFindFold(source string, targets []string) Ranks { - var r Ranks - for _, target := range find(source, targets, unicode.ToLower) { - distance := LevenshteinDistance(source, target) - r = append(r, Rank{source, target, distance}) - } - return r -} - -type Rank struct { - // Source is used as the source for matching. - Source string - - // Target is the word matched against. - Target string - - // Distance is the Levenshtein distance between Source and Target. - Distance int -} - -type Ranks []Rank - -func (r Ranks) Len() int { - return len(r) -} - -func (r Ranks) Swap(i, j int) { - r[i], r[j] = r[j], r[i] -} - -func (r Ranks) Less(i, j int) bool { - return r[i].Distance < r[j].Distance -} diff --git a/vendor/github.com/renstrom/fuzzysearch/fuzzy/levenshtein.go b/vendor/github.com/renstrom/fuzzysearch/fuzzy/levenshtein.go deleted file mode 100644 index 237923d34..000000000 --- a/vendor/github.com/renstrom/fuzzysearch/fuzzy/levenshtein.go +++ /dev/null @@ -1,43 +0,0 @@ -package fuzzy - -// LevenshteinDistance measures the difference between two strings. -// The Levenshtein distance between two words is the minimum number of -// single-character edits (i.e. insertions, deletions or substitutions) -// required to change one word into the other. -// -// This implemention is optimized to use O(min(m,n)) space and is based on the -// optimized C version found here: -// http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Levenshtein_distance#C -func LevenshteinDistance(s, t string) int { - r1, r2 := []rune(s), []rune(t) - column := make([]int, len(r1)+1) - - for y := 1; y <= len(r1); y++ { - column[y] = y - } - - for x := 1; x <= len(r2); x++ { - column[0] = x - - for y, lastDiag := 1, x-1; y <= len(r1); y++ { - oldDiag := column[y] - cost := 0 - if r1[y-1] != r2[x-1] { - cost = 1 - } - column[y] = min(column[y]+1, column[y-1]+1, lastDiag+cost) - lastDiag = oldDiag - } - } - - return column[len(r1)] -} - -func min(a, b, c int) int { - if a < b && a < c { - return a - } else if b < c { - return b - } - return c -} diff --git a/vendor/github.com/scaleway/scaleway-cli/LICENSE.md b/vendor/github.com/scaleway/scaleway-cli/LICENSE.md deleted file mode 100644 index 7503a16ca..000000000 --- a/vendor/github.com/scaleway/scaleway-cli/LICENSE.md +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License -=============== - -Copyright (c) **2014-2016 Scaleway ([@scaleway](https://twitter.com/scaleway))** - -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/scaleway/scaleway-cli/pkg/api/README.md b/vendor/github.com/scaleway/scaleway-cli/pkg/api/README.md deleted file mode 100644 index 62dade6b9..000000000 --- a/vendor/github.com/scaleway/scaleway-cli/pkg/api/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Scaleway's API - -## Deprecated in favor of https://github.com/scaleway/go-scaleway diff --git a/vendor/github.com/scaleway/scaleway-cli/pkg/api/api.go b/vendor/github.com/scaleway/scaleway-cli/pkg/api/api.go deleted file mode 100644 index 2b3d0288c..000000000 --- a/vendor/github.com/scaleway/scaleway-cli/pkg/api/api.go +++ /dev/null @@ -1,2844 +0,0 @@ -// Copyright (C) 2015 Scaleway. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE.md file. - -// Interact with Scaleway API - -// Package api contains client and functions to interact with Scaleway API -package api - -import ( - "bytes" - "crypto/tls" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "net" - "net/http" - "net/http/httputil" - "net/url" - "os" - "sort" - "strconv" - "strings" - "text/tabwriter" - "text/template" - "time" - - "golang.org/x/sync/errgroup" -) - -// Default values -var ( - AccountAPI = "https://account.scaleway.com/" - MetadataAPI = "http://169.254.42.42/" - MarketplaceAPI = "https://api-marketplace.scaleway.com" - ComputeAPIPar1 = "https://cp-par1.scaleway.com/" - ComputeAPIAms1 = "https://cp-ams1.scaleway.com" - - URLPublicDNS = ".pub.cloud.scaleway.com" - URLPrivateDNS = ".priv.cloud.scaleway.com" -) - -func init() { - if url := os.Getenv("SCW_ACCOUNT_API"); url != "" { - AccountAPI = url - } - if url := os.Getenv("SCW_METADATA_API"); url != "" { - MetadataAPI = url - } - if url := os.Getenv("SCW_MARKETPLACE_API"); url != "" { - MarketplaceAPI = url - } - if url := os.Getenv("SCW_COMPUTE_PAR1_API"); url != "" { - ComputeAPIPar1 = url - } - if url := os.Getenv("SCW_COMPUTE_AMS1_API"); url != "" { - ComputeAPIAms1 = url - } -} - -const ( - perPage = 50 -) - -// ScalewayAPI is the interface used to communicate with the Scaleway API -type ScalewayAPI struct { - // Organization is the identifier of the Scaleway organization - Organization string - - // Token is the authentication token for the Scaleway organization - Token string - - // Password is the authentication password - password string - - userAgent string - - // Cache is used to quickly resolve identifiers from names - Cache *ScalewayCache - - client *http.Client - verbose bool - computeAPI string - - Region string - // - Logger -} - -// ScalewayAPIError represents a Scaleway API Error -type ScalewayAPIError struct { - // Message is a human-friendly error message - APIMessage string `json:"message,omitempty"` - - // Type is a string code that defines the kind of error - Type string `json:"type,omitempty"` - - // Fields contains detail about validation error - Fields map[string][]string `json:"fields,omitempty"` - - // StatusCode is the HTTP status code received - StatusCode int `json:"-"` - - // Message - Message string `json:"-"` -} - -// Error returns a string representing the error -func (e ScalewayAPIError) Error() string { - var b bytes.Buffer - - fmt.Fprintf(&b, "StatusCode: %v, ", e.StatusCode) - fmt.Fprintf(&b, "Type: %v, ", e.Type) - fmt.Fprintf(&b, "APIMessage: \x1b[31m%v\x1b[0m", e.APIMessage) - if len(e.Fields) > 0 { - fmt.Fprintf(&b, ", Details: %v", e.Fields) - } - return b.String() -} - -// HideAPICredentials removes API credentials from a string -func (s *ScalewayAPI) HideAPICredentials(input string) string { - output := input - if s.Token != "" { - output = strings.Replace(output, s.Token, "00000000-0000-4000-8000-000000000000", -1) - } - if s.Organization != "" { - output = strings.Replace(output, s.Organization, "00000000-0000-5000-9000-000000000000", -1) - } - if s.password != "" { - output = strings.Replace(output, s.password, "XX-XX-XX-XX", -1) - } - return output -} - -// ScalewayIPAddress represents a Scaleway IP address -type ScalewayIPAddress struct { - // Identifier is a unique identifier for the IP address - Identifier string `json:"id,omitempty"` - - // IP is an IPv4 address - IP string `json:"address,omitempty"` - - // Dynamic is a flag that defines an IP that change on each reboot - Dynamic *bool `json:"dynamic,omitempty"` -} - -// ScalewayVolume represents a Scaleway Volume -type ScalewayVolume struct { - // Identifier is a unique identifier for the volume - Identifier string `json:"id,omitempty"` - - // Size is the allocated size of the volume - Size uint64 `json:"size,omitempty"` - - // CreationDate is the creation date of the volume - CreationDate string `json:"creation_date,omitempty"` - - // ModificationDate is the date of the last modification of the volume - ModificationDate string `json:"modification_date,omitempty"` - - // Organization is the organization owning the volume - Organization string `json:"organization,omitempty"` - - // Name is the name of the volume - Name string `json:"name,omitempty"` - - // Server is the server using this image - Server *struct { - Identifier string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - } `json:"server,omitempty"` - - // VolumeType is a Scaleway identifier for the kind of volume (default: l_ssd) - VolumeType string `json:"volume_type,omitempty"` - - // ExportURI represents the url used by initrd/scripts to attach the volume - ExportURI string `json:"export_uri,omitempty"` -} - -// ScalewayOneVolume represents the response of a GET /volumes/UUID API call -type ScalewayOneVolume struct { - Volume ScalewayVolume `json:"volume,omitempty"` -} - -// ScalewayVolumes represents a group of Scaleway volumes -type ScalewayVolumes struct { - // Volumes holds scaleway volumes of the response - Volumes []ScalewayVolume `json:"volumes,omitempty"` -} - -// ScalewayVolumeDefinition represents a Scaleway volume definition -type ScalewayVolumeDefinition struct { - // Name is the user-defined name of the volume - Name string `json:"name"` - - // Image is the image used by the volume - Size uint64 `json:"size"` - - // Bootscript is the bootscript used by the volume - Type string `json:"volume_type"` - - // Organization is the owner of the volume - Organization string `json:"organization"` -} - -// ScalewayVolumePutDefinition represents a Scaleway volume with nullable fields (for PUT) -type ScalewayVolumePutDefinition struct { - Identifier *string `json:"id,omitempty"` - Size *uint64 `json:"size,omitempty"` - CreationDate *string `json:"creation_date,omitempty"` - ModificationDate *string `json:"modification_date,omitempty"` - Organization *string `json:"organization,omitempty"` - Name *string `json:"name,omitempty"` - Server struct { - Identifier *string `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - } `json:"server,omitempty"` - VolumeType *string `json:"volume_type,omitempty"` - ExportURI *string `json:"export_uri,omitempty"` -} - -// ScalewayImage represents a Scaleway Image -type ScalewayImage struct { - // Identifier is a unique identifier for the image - Identifier string `json:"id,omitempty"` - - // Name is a user-defined name for the image - Name string `json:"name,omitempty"` - - // CreationDate is the creation date of the image - CreationDate string `json:"creation_date,omitempty"` - - // ModificationDate is the date of the last modification of the image - ModificationDate string `json:"modification_date,omitempty"` - - // RootVolume is the root volume bound to the image - RootVolume ScalewayVolume `json:"root_volume,omitempty"` - - // Public is true for public images and false for user images - Public bool `json:"public,omitempty"` - - // Bootscript is the bootscript bound to the image - DefaultBootscript *ScalewayBootscript `json:"default_bootscript,omitempty"` - - // Organization is the owner of the image - Organization string `json:"organization,omitempty"` - - // Arch is the architecture target of the image - Arch string `json:"arch,omitempty"` - - // FIXME: extra_volumes -} - -// ScalewayImageIdentifier represents a Scaleway Image Identifier -type ScalewayImageIdentifier struct { - Identifier string - Arch string - Region string - Owner string -} - -// ScalewayOneImage represents the response of a GET /images/UUID API call -type ScalewayOneImage struct { - Image ScalewayImage `json:"image,omitempty"` -} - -// ScalewayImages represents a group of Scaleway images -type ScalewayImages struct { - // Images holds scaleway images of the response - Images []ScalewayImage `json:"images,omitempty"` -} - -// ProductNetworkInterface gives interval and external allowed bandwidth -type ProductNetworkInterface struct { - InternalBandwidth uint64 `json:"internal_bandwidth,omitempty"` - InternetBandwidth uint64 `json:"internet_bandwidth,omitempty"` -} - -// ProductNetwork lists all the network interfaces -type ProductNetwork struct { - Interfaces []ProductNetworkInterface `json:"interfaces,omitempty"` - TotalInternalBandwidth uint64 `json:"sum_internal_bandwidth,omitempty"` - TotalInternetBandwidth uint64 `json:"sum_internet_bandwidth,omitempty"` - IPv6_Support bool `json:"ipv6_support,omitempty"` -} - -// ProductVolumeConstraint contains any volume constraint that the offer has -type ProductVolumeConstraint struct { - MinSize uint64 `json:"min_size,omitempty"` - MaxSize uint64 `json:"max_size,omitempty"` -} - -// ProductServerOffer represents a specific offer -type ProductServer struct { - Arch string `json:"arch,omitempty"` - Ncpus uint64 `json:"ncpus,omitempty"` - Ram uint64 `json:"ram,omitempty"` - Baremetal bool `json:"baremetal,omitempty"` - VolumesConstraint ProductVolumeConstraint `json:"volumes_constraint,omitempty"` - AltNames []string `json:"alt_names,omitempty"` - Network ProductNetwork `json:"network,omitempty"` -} - -// Products holds a map of all Scaleway servers -type ScalewayProductsServers struct { - Servers map[string]ProductServer `json:"servers"` -} - -// ScalewaySnapshot represents a Scaleway Snapshot -type ScalewaySnapshot struct { - // Identifier is a unique identifier for the snapshot - Identifier string `json:"id,omitempty"` - - // Name is a user-defined name for the snapshot - Name string `json:"name,omitempty"` - - // CreationDate is the creation date of the snapshot - CreationDate string `json:"creation_date,omitempty"` - - // ModificationDate is the date of the last modification of the snapshot - ModificationDate string `json:"modification_date,omitempty"` - - // Size is the allocated size of the volume - Size uint64 `json:"size,omitempty"` - - // Organization is the owner of the snapshot - Organization string `json:"organization"` - - // State is the current state of the snapshot - State string `json:"state"` - - // VolumeType is the kind of volume behind the snapshot - VolumeType string `json:"volume_type"` - - // BaseVolume is the volume from which the snapshot inherits - BaseVolume ScalewayVolume `json:"base_volume,omitempty"` -} - -// ScalewayOneSnapshot represents the response of a GET /snapshots/UUID API call -type ScalewayOneSnapshot struct { - Snapshot ScalewaySnapshot `json:"snapshot,omitempty"` -} - -// ScalewaySnapshots represents a group of Scaleway snapshots -type ScalewaySnapshots struct { - // Snapshots holds scaleway snapshots of the response - Snapshots []ScalewaySnapshot `json:"snapshots,omitempty"` -} - -// ScalewayBootscript represents a Scaleway Bootscript -type ScalewayBootscript struct { - Bootcmdargs string `json:"bootcmdargs,omitempty"` - Dtb string `json:"dtb,omitempty"` - Initrd string `json:"initrd,omitempty"` - Kernel string `json:"kernel,omitempty"` - - // Arch is the architecture target of the bootscript - Arch string `json:"architecture,omitempty"` - - // Identifier is a unique identifier for the bootscript - Identifier string `json:"id,omitempty"` - - // Organization is the owner of the bootscript - Organization string `json:"organization,omitempty"` - - // Name is a user-defined name for the bootscript - Title string `json:"title,omitempty"` - - // Public is true for public bootscripts and false for user bootscripts - Public bool `json:"public,omitempty"` - - Default bool `json:"default,omitempty"` -} - -// ScalewayOneBootscript represents the response of a GET /bootscripts/UUID API call -type ScalewayOneBootscript struct { - Bootscript ScalewayBootscript `json:"bootscript,omitempty"` -} - -// ScalewayBootscripts represents a group of Scaleway bootscripts -type ScalewayBootscripts struct { - // Bootscripts holds Scaleway bootscripts of the response - Bootscripts []ScalewayBootscript `json:"bootscripts,omitempty"` -} - -// ScalewayTask represents a Scaleway Task -type ScalewayTask struct { - // Identifier is a unique identifier for the task - Identifier string `json:"id,omitempty"` - - // StartDate is the start date of the task - StartDate string `json:"started_at,omitempty"` - - // TerminationDate is the termination date of the task - TerminationDate string `json:"terminated_at,omitempty"` - - HrefFrom string `json:"href_from,omitempty"` - - Description string `json:"description,omitempty"` - - Status string `json:"status,omitempty"` - - Progress int `json:"progress,omitempty"` -} - -// ScalewayOneTask represents the response of a GET /tasks/UUID API call -type ScalewayOneTask struct { - Task ScalewayTask `json:"task,omitempty"` -} - -// ScalewayTasks represents a group of Scaleway tasks -type ScalewayTasks struct { - // Tasks holds scaleway tasks of the response - Tasks []ScalewayTask `json:"tasks,omitempty"` -} - -// ScalewaySecurityGroupRule definition -type ScalewaySecurityGroupRule struct { - Direction string `json:"direction"` - Protocol string `json:"protocol"` - IPRange string `json:"ip_range"` - DestPortFrom int `json:"dest_port_from,omitempty"` - Action string `json:"action"` - Position int `json:"position"` - DestPortTo string `json:"dest_port_to"` - Editable bool `json:"editable"` - ID string `json:"id"` -} - -// ScalewayGetSecurityGroupRules represents the response of a GET /security_group/{groupID}/rules -type ScalewayGetSecurityGroupRules struct { - Rules []ScalewaySecurityGroupRule `json:"rules"` -} - -// ScalewayGetSecurityGroupRule represents the response of a GET /security_group/{groupID}/rules/{ruleID} -type ScalewayGetSecurityGroupRule struct { - Rules ScalewaySecurityGroupRule `json:"rule"` -} - -// ScalewayNewSecurityGroupRule definition POST/PUT request /security_group/{groupID} -type ScalewayNewSecurityGroupRule struct { - Action string `json:"action"` - Direction string `json:"direction"` - IPRange string `json:"ip_range"` - Protocol string `json:"protocol"` - DestPortFrom int `json:"dest_port_from,omitempty"` -} - -// ScalewaySecurityGroups definition -type ScalewaySecurityGroups struct { - Description string `json:"description"` - ID string `json:"id"` - Organization string `json:"organization"` - Name string `json:"name"` - Servers []ScalewaySecurityGroup `json:"servers"` - EnableDefaultSecurity bool `json:"enable_default_security"` - OrganizationDefault bool `json:"organization_default"` - Stateful bool `json:"stateful"` - InboundDefaultPolicy string `json:"inbound_default_policy"` - OutboundDefaultPolicy string `json:"outbound_default_policy"` -} - -// ScalewayGetSecurityGroups represents the response of a GET /security_groups/ -type ScalewayGetSecurityGroups struct { - SecurityGroups []ScalewaySecurityGroups `json:"security_groups"` -} - -// ScalewayGetSecurityGroup represents the response of a GET /security_groups/{groupID} -type ScalewayGetSecurityGroup struct { - SecurityGroups ScalewaySecurityGroups `json:"security_group"` -} - -// ScalewayIPDefinition represents the IP's fields -type ScalewayIPDefinition struct { - Organization string `json:"organization"` - Reverse *string `json:"reverse"` - ID string `json:"id"` - Server *struct { - Identifier string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - } `json:"server"` - Address string `json:"address"` -} - -// ScalewayGetIPS represents the response of a GET /ips/ -type ScalewayGetIPS struct { - IPS []ScalewayIPDefinition `json:"ips"` -} - -// ScalewayGetIP represents the response of a GET /ips/{id_ip} -type ScalewayGetIP struct { - IP ScalewayIPDefinition `json:"ip"` -} - -// ScalewaySecurityGroup represents a Scaleway security group -type ScalewaySecurityGroup struct { - // Identifier is a unique identifier for the security group - Identifier string `json:"id,omitempty"` - - // Name is the user-defined name of the security group - Name string `json:"name,omitempty"` -} - -// ScalewayNewSecurityGroup definition POST request /security_groups -type ScalewayNewSecurityGroup struct { - Organization string `json:"organization"` - Name string `json:"name"` - Description string `json:"description"` - Stateful bool `json:"stateful"` - InboundDefaultPolicy string `json:"inbound_default_policy"` - OutboundDefaultPolicy string `json:"outbound_default_policy"` -} - -// ScalewayUpdateSecurityGroup definition PUT request /security_groups -type ScalewayUpdateSecurityGroup struct { - Organization string `json:"organization"` - Name string `json:"name"` - Description string `json:"description"` - OrganizationDefault bool `json:"organization_default"` - Stateful bool `json:"stateful"` - InboundDefaultPolicy string `json:"inbound_default_policy"` - OutboundDefaultPolicy string `json:"outbound_default_policy"` -} - -// ScalewayServer represents a Scaleway server -type ScalewayServer struct { - // Arch is the architecture target of the server - Arch string `json:"arch,omitempty"` - - // Identifier is a unique identifier for the server - Identifier string `json:"id,omitempty"` - - // Name is the user-defined name of the server - Name string `json:"name,omitempty"` - - // CreationDate is the creation date of the server - CreationDate string `json:"creation_date,omitempty"` - - // ModificationDate is the date of the last modification of the server - ModificationDate string `json:"modification_date,omitempty"` - - // Image is the image used by the server - Image ScalewayImage `json:"image,omitempty"` - - // DynamicIPRequired is a flag that defines a server with a dynamic ip address attached - DynamicIPRequired *bool `json:"dynamic_ip_required,omitempty"` - - // PublicIP is the public IP address bound to the server - PublicAddress ScalewayIPAddress `json:"public_ip,omitempty"` - - // State is the current status of the server - State string `json:"state,omitempty"` - - // BootType is the boot method used, can be local or bootscript - BootType string `json:"boot_type,omitempty"` - - // StateDetail is the detailed status of the server - StateDetail string `json:"state_detail,omitempty"` - - // PrivateIP represents the private IPV4 attached to the server (changes on each boot) - PrivateIP string `json:"private_ip,omitempty"` - - // Bootscript is the unique identifier of the selected bootscript - Bootscript *ScalewayBootscript `json:"bootscript,omitempty"` - - // Hostname represents the ServerName in a format compatible with unix's hostname - Hostname string `json:"hostname,omitempty"` - - // Tags represents user-defined tags - Tags []string `json:"tags,omitempty"` - - // Volumes are the attached volumes - Volumes map[string]ScalewayVolume `json:"volumes,omitempty"` - - // SecurityGroup is the selected security group object - SecurityGroup ScalewaySecurityGroup `json:"security_group,omitempty"` - - // Organization is the owner of the server - Organization string `json:"organization,omitempty"` - - // CommercialType is the commercial type of the server (i.e: C1, C2[SML], START1-S) - CommercialType string `json:"commercial_type,omitempty"` - - // Location of the server - Location struct { - Platform string `json:"platform_id,omitempty"` - Chassis string `json:"chassis_id,omitempty"` - Cluster string `json:"cluster_id,omitempty"` - Hypervisor string `json:"hypervisor_id,omitempty"` - Blade string `json:"blade_id,omitempty"` - Node string `json:"node_id,omitempty"` - ZoneID string `json:"zone_id,omitempty"` - } `json:"location,omitempty"` - - IPV6 *ScalewayIPV6Definition `json:"ipv6,omitempty"` - - EnableIPV6 bool `json:"enable_ipv6,omitempty"` - - // This fields are not returned by the API, we generate it - DNSPublic string `json:"dns_public,omitempty"` - DNSPrivate string `json:"dns_private,omitempty"` -} - -// ScalewayIPV6Definition represents a Scaleway ipv6 -type ScalewayIPV6Definition struct { - Netmask string `json:"netmask"` - Gateway string `json:"gateway"` - Address string `json:"address"` -} - -// ScalewayServerPatchDefinition represents a Scaleway server with nullable fields (for PATCH) -type ScalewayServerPatchDefinition struct { - Arch *string `json:"arch,omitempty"` - Name *string `json:"name,omitempty"` - CreationDate *string `json:"creation_date,omitempty"` - ModificationDate *string `json:"modification_date,omitempty"` - Image *ScalewayImage `json:"image,omitempty"` - DynamicIPRequired *bool `json:"dynamic_ip_required,omitempty"` - PublicAddress *ScalewayIPAddress `json:"public_ip,omitempty"` - State *string `json:"state,omitempty"` - StateDetail *string `json:"state_detail,omitempty"` - PrivateIP *string `json:"private_ip,omitempty"` - Bootscript *string `json:"bootscript,omitempty"` - Hostname *string `json:"hostname,omitempty"` - Volumes *map[string]ScalewayVolume `json:"volumes,omitempty"` - SecurityGroup *ScalewaySecurityGroup `json:"security_group,omitempty"` - Organization *string `json:"organization,omitempty"` - Tags *[]string `json:"tags,omitempty"` - IPV6 *ScalewayIPV6Definition `json:"ipv6,omitempty"` - EnableIPV6 *bool `json:"enable_ipv6,omitempty"` - BootType *string `json:"boot_type,omitempty"` -} - -// ScalewayServerDefinition represents a Scaleway server with image definition -type ScalewayServerDefinition struct { - // Name is the user-defined name of the server - Name string `json:"name"` - - // Image is the image used by the server - Image *string `json:"image,omitempty"` - - // Volumes are the attached volumes - Volumes map[string]string `json:"volumes,omitempty"` - - // DynamicIPRequired is a flag that defines a server with a dynamic ip address attached - DynamicIPRequired *bool `json:"dynamic_ip_required,omitempty"` - - // Bootscript is the bootscript used by the server - Bootscript *string `json:"bootscript"` - - // Tags are the metadata tags attached to the server - Tags []string `json:"tags,omitempty"` - - // Organization is the owner of the server - Organization string `json:"organization"` - - // CommercialType is the commercial type of the server (i.e: C1, C2[SML], START1-S) - CommercialType string `json:"commercial_type"` - - PublicIP string `json:"public_ip,omitempty"` - - EnableIPV6 bool `json:"enable_ipv6,omitempty"` - - SecurityGroup string `json:"security_group,omitempty"` - - BootType string `json:"boot_type,omitempty"` -} - -// ScalewayOneServer represents the response of a GET /servers/UUID API call -type ScalewayOneServer struct { - Server ScalewayServer `json:"server,omitempty"` -} - -// ScalewayServers represents a group of Scaleway servers -type ScalewayServers struct { - // Servers holds scaleway servers of the response - Servers []ScalewayServer `json:"servers,omitempty"` -} - -// ScalewayServerAction represents an action to perform on a Scaleway server -type ScalewayServerAction struct { - // Action is the name of the action to trigger - Action string `json:"action,omitempty"` -} - -// ScalewaySnapshotDefinition represents a Scaleway snapshot definition -type ScalewaySnapshotDefinition struct { - VolumeIDentifier string `json:"volume_id"` - Name string `json:"name,omitempty"` - Organization string `json:"organization"` -} - -// ScalewayImageDefinition represents a Scaleway image definition -type ScalewayImageDefinition struct { - SnapshotIDentifier string `json:"root_volume"` - Name string `json:"name,omitempty"` - Organization string `json:"organization"` - Arch string `json:"arch"` - DefaultBootscript *string `json:"default_bootscript,omitempty"` -} - -// ScalewayRoleDefinition represents a Scaleway Token UserId Role -type ScalewayRoleDefinition struct { - Organization ScalewayOrganizationDefinition `json:"organization,omitempty"` - Role string `json:"role,omitempty"` -} - -// ScalewayTokenDefinition represents a Scaleway Token -type ScalewayTokenDefinition struct { - UserID string `json:"user_id"` - Description string `json:"description,omitempty"` - Roles ScalewayRoleDefinition `json:"roles"` - Expires string `json:"expires"` - InheritsUsersPerms bool `json:"inherits_user_perms"` - ID string `json:"id"` -} - -// ScalewayTokensDefinition represents a Scaleway Tokens -type ScalewayTokensDefinition struct { - Token ScalewayTokenDefinition `json:"token"` -} - -// ScalewayGetTokens represents a list of Scaleway Tokens -type ScalewayGetTokens struct { - Tokens []ScalewayTokenDefinition `json:"tokens"` -} - -// ScalewayContainerData represents a Scaleway container data (S3) -type ScalewayContainerData struct { - LastModified string `json:"last_modified"` - Name string `json:"name"` - Size string `json:"size"` -} - -// ScalewayGetContainerDatas represents a list of Scaleway containers data (S3) -type ScalewayGetContainerDatas struct { - Container []ScalewayContainerData `json:"container"` -} - -// ScalewayContainer represents a Scaleway container (S3) -type ScalewayContainer struct { - ScalewayOrganizationDefinition `json:"organization"` - Name string `json:"name"` - Size string `json:"size"` -} - -// ScalewayGetContainers represents a list of Scaleway containers (S3) -type ScalewayGetContainers struct { - Containers []ScalewayContainer `json:"containers"` -} - -// ScalewayConnectResponse represents the answer from POST /tokens -type ScalewayConnectResponse struct { - Token ScalewayTokenDefinition `json:"token"` -} - -// ScalewayConnect represents the data to connect -type ScalewayConnect struct { - Email string `json:"email"` - Password string `json:"password"` - Description string `json:"description"` - Expires bool `json:"expires"` -} - -// ScalewayConnectInterface is the interface implemented by ScalewayConnect, -// ScalewayConnectByOTP and ScalewayConnectByBackupCode -type ScalewayConnectInterface interface { - GetPassword() string -} - -func (s *ScalewayConnect) GetPassword() string { - return s.Password -} - -type ScalewayConnectByOTP struct { - ScalewayConnect - TwoFAToken string `json:"2FA_token"` -} - -type ScalewayConnectByBackupCode struct { - ScalewayConnect - TwoFABackupCode string `json:"2FA_backup_code"` -} - -// ScalewayOrganizationDefinition represents a Scaleway Organization -type ScalewayOrganizationDefinition struct { - ID string `json:"id"` - Name string `json:"name"` - Users []ScalewayUserDefinition `json:"users"` -} - -// ScalewayOrganizationsDefinition represents a Scaleway Organizations -type ScalewayOrganizationsDefinition struct { - Organizations []ScalewayOrganizationDefinition `json:"organizations"` -} - -// ScalewayUserDefinition represents a Scaleway User -type ScalewayUserDefinition struct { - Email string `json:"email"` - Firstname string `json:"firstname"` - Fullname string `json:"fullname"` - ID string `json:"id"` - Lastname string `json:"lastname"` - Organizations []ScalewayOrganizationDefinition `json:"organizations"` - Roles []ScalewayRoleDefinition `json:"roles"` - SSHPublicKeys []ScalewayKeyDefinition `json:"ssh_public_keys"` -} - -// ScalewayUsersDefinition represents the response of a GET /user -type ScalewayUsersDefinition struct { - User ScalewayUserDefinition `json:"user"` -} - -// ScalewayKeyDefinition represents a key -type ScalewayKeyDefinition struct { - Key string `json:"key"` - Fingerprint string `json:"fingerprint,omitempty"` -} - -// ScalewayUserPatchSSHKeyDefinition represents a User Patch -type ScalewayUserPatchSSHKeyDefinition struct { - SSHPublicKeys []ScalewayKeyDefinition `json:"ssh_public_keys"` -} - -// ScalewayDashboardResp represents a dashboard received from the API -type ScalewayDashboardResp struct { - Dashboard ScalewayDashboard -} - -// ScalewayDashboard represents a dashboard -type ScalewayDashboard struct { - VolumesCount int `json:"volumes_count"` - RunningServersCount int `json:"running_servers_count"` - ImagesCount int `json:"images_count"` - SnapshotsCount int `json:"snapshots_count"` - ServersCount int `json:"servers_count"` - IPsCount int `json:"ips_count"` -} - -// ScalewayPermissions represents the response of GET /permissions -type ScalewayPermissions map[string]ScalewayPermCategory - -// ScalewayPermCategory represents ScalewayPermissions's fields -type ScalewayPermCategory map[string][]string - -// ScalewayPermissionDefinition represents the permissions -type ScalewayPermissionDefinition struct { - Permissions ScalewayPermissions `json:"permissions"` -} - -// ScalewayUserdatas represents the response of a GET /user_data -type ScalewayUserdatas struct { - UserData []string `json:"user_data"` -} - -// ScalewayQuota represents a map of quota (name, value) -type ScalewayQuota map[string]int - -// ScalewayGetQuotas represents the response of GET /organizations/{orga_id}/quotas -type ScalewayGetQuotas struct { - Quotas ScalewayQuota `json:"quotas"` -} - -// ScalewayUserdata represents []byte -type ScalewayUserdata []byte - -// FuncMap used for json inspection -var FuncMap = template.FuncMap{ - "json": func(v interface{}) string { - a, _ := json.Marshal(v) - return string(a) - }, -} - -// MarketLocalImageDefinition represents localImage of marketplace version -type MarketLocalImageDefinition struct { - Arch string `json:"arch"` - ID string `json:"id"` - Zone string `json:"zone"` -} - -// MarketLocalImages represents an array of local images -type MarketLocalImages struct { - LocalImages []MarketLocalImageDefinition `json:"local_images"` -} - -// MarketLocalImage represents local image -type MarketLocalImage struct { - LocalImages MarketLocalImageDefinition `json:"local_image"` -} - -// MarketVersionDefinition represents version of marketplace image -type MarketVersionDefinition struct { - CreationDate string `json:"creation_date"` - ID string `json:"id"` - Image struct { - ID string `json:"id"` - Name string `json:"name"` - } `json:"image"` - ModificationDate string `json:"modification_date"` - Name string `json:"name"` - MarketLocalImages -} - -// MarketVersions represents an array of marketplace image versions -type MarketVersions struct { - Versions []MarketVersionDefinition `json:"versions"` -} - -// MarketVersion represents version of marketplace image -type MarketVersion struct { - Version MarketVersionDefinition `json:"version"` -} - -// MarketImage represents MarketPlace image -type MarketImage struct { - Categories []string `json:"categories"` - CreationDate string `json:"creation_date"` - CurrentPublicVersion string `json:"current_public_version"` - Description string `json:"description"` - ID string `json:"id"` - Logo string `json:"logo"` - ModificationDate string `json:"modification_date"` - Name string `json:"name"` - Organization struct { - ID string `json:"id"` - Name string `json:"name"` - } `json:"organization"` - Public bool `json:"-"` - MarketVersions -} - -// MarketImages represents MarketPlace images -type MarketImages struct { - Images []MarketImage `json:"images"` -} - -// NewScalewayAPI creates a ready-to-use ScalewayAPI client -func NewScalewayAPI(organization, token, userAgent, region string, options ...func(*ScalewayAPI)) (*ScalewayAPI, error) { - s := &ScalewayAPI{ - // exposed - Organization: organization, - Token: token, - Logger: NewDefaultLogger(), - - // internal - client: &http.Client{}, - verbose: os.Getenv("SCW_VERBOSE_API") != "", - password: "", - userAgent: userAgent, - } - for _, option := range options { - option(s) - } - cache, err := NewScalewayCache(func() { s.Logger.Debugf("Writing cache file to disk") }) - if err != nil { - return nil, err - } - s.Cache = cache - if os.Getenv("SCW_TLSVERIFY") == "0" { - s.client.Transport = &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - } - } - switch region { - case "par1", "": - s.computeAPI = ComputeAPIPar1 - case "ams1": - s.computeAPI = ComputeAPIAms1 - default: - return nil, fmt.Errorf("%s isn't a valid region", region) - } - s.Region = region - if url := os.Getenv("SCW_COMPUTE_API"); url != "" { - s.computeAPI = url - } - return s, nil -} - -// ClearCache clears the cache -func (s *ScalewayAPI) ClearCache() { - s.Cache.Clear() -} - -// Sync flushes out the cache to the disk -func (s *ScalewayAPI) Sync() { - s.Cache.Save() -} - -func (s *ScalewayAPI) response(method, uri string, content io.Reader) (resp *http.Response, err error) { - var ( - req *http.Request - ) - - req, err = http.NewRequest(method, uri, content) - if err != nil { - err = fmt.Errorf("response %s %s", method, uri) - return - } - req.Header.Set("X-Auth-Token", s.Token) - req.Header.Set("Content-Type", "application/json") - req.Header.Set("User-Agent", s.userAgent) - s.LogHTTP(req) - if s.verbose { - dump, _ := httputil.DumpRequest(req, true) - s.Debugf("%v", string(dump)) - } else { - s.Debugf("[%s]: %v", method, uri) - } - resp, err = s.client.Do(req) - return -} - -// GetResponsePaginate fetchs all resources and returns an http.Response object for the requested resource -func (s *ScalewayAPI) GetResponsePaginate(apiURL, resource string, values url.Values) (*http.Response, error) { - resp, err := s.response("HEAD", fmt.Sprintf("%s/%s?%s", strings.TrimRight(apiURL, "/"), resource, values.Encode()), nil) - if err != nil { - return nil, err - } - - count := resp.Header.Get("X-Total-Count") - var maxElem int - if count == "" { - maxElem = 0 - } else { - maxElem, err = strconv.Atoi(count) - if err != nil { - return nil, err - } - } - - get := maxElem / perPage - if (float32(maxElem) / perPage) > float32(get) { - get++ - } - - if get <= 1 { // If there is 0 or 1 page of result, the response is not paginated - if len(values) == 0 { - return s.response("GET", fmt.Sprintf("%s/%s", strings.TrimRight(apiURL, "/"), resource), nil) - } - return s.response("GET", fmt.Sprintf("%s/%s?%s", strings.TrimRight(apiURL, "/"), resource, values.Encode()), nil) - } - - fetchAll := !(values.Get("per_page") != "" || values.Get("page") != "") - if fetchAll { - var g errgroup.Group - - ch := make(chan *http.Response, get) - for i := 1; i <= get; i++ { - i := i // closure tricks - g.Go(func() (err error) { - var resp *http.Response - - val := url.Values{} - val.Set("per_page", fmt.Sprintf("%v", perPage)) - val.Set("page", fmt.Sprintf("%v", i)) - resp, err = s.response("GET", fmt.Sprintf("%s/%s?%s", strings.TrimRight(apiURL, "/"), resource, val.Encode()), nil) - ch <- resp - return - }) - } - if err = g.Wait(); err != nil { - return nil, err - } - newBody := make(map[string][]json.RawMessage) - body := make(map[string][]json.RawMessage) - key := "" - for i := 0; i < get; i++ { - res := <-ch - if res.StatusCode != http.StatusOK { - return res, nil - } - content, err := ioutil.ReadAll(res.Body) - res.Body.Close() - if err != nil { - return nil, err - } - if err := json.Unmarshal(content, &body); err != nil { - return nil, err - } - - if i == 0 { - resp = res - for k := range body { - key = k - break - } - } - newBody[key] = append(newBody[key], body[key]...) - } - payload := new(bytes.Buffer) - if err := json.NewEncoder(payload).Encode(newBody); err != nil { - return nil, err - } - resp.Body = ioutil.NopCloser(payload) - } else { - resp, err = s.response("GET", fmt.Sprintf("%s/%s?%s", strings.TrimRight(apiURL, "/"), resource, values.Encode()), nil) - } - return resp, err -} - -// PostResponse returns an http.Response object for the updated resource -func (s *ScalewayAPI) PostResponse(apiURL, resource string, data interface{}) (*http.Response, error) { - payload := new(bytes.Buffer) - if err := json.NewEncoder(payload).Encode(data); err != nil { - return nil, err - } - return s.response("POST", fmt.Sprintf("%s/%s", strings.TrimRight(apiURL, "/"), resource), payload) -} - -// PatchResponse returns an http.Response object for the updated resource -func (s *ScalewayAPI) PatchResponse(apiURL, resource string, data interface{}) (*http.Response, error) { - payload := new(bytes.Buffer) - if err := json.NewEncoder(payload).Encode(data); err != nil { - return nil, err - } - return s.response("PATCH", fmt.Sprintf("%s/%s", strings.TrimRight(apiURL, "/"), resource), payload) -} - -// PutResponse returns an http.Response object for the updated resource -func (s *ScalewayAPI) PutResponse(apiURL, resource string, data interface{}) (*http.Response, error) { - payload := new(bytes.Buffer) - if err := json.NewEncoder(payload).Encode(data); err != nil { - return nil, err - } - return s.response("PUT", fmt.Sprintf("%s/%s", strings.TrimRight(apiURL, "/"), resource), payload) -} - -// DeleteResponse returns an http.Response object for the deleted resource -func (s *ScalewayAPI) DeleteResponse(apiURL, resource string) (*http.Response, error) { - return s.response("DELETE", fmt.Sprintf("%s/%s", strings.TrimRight(apiURL, "/"), resource), nil) -} - -// handleHTTPError checks the statusCode and displays the error -func (s *ScalewayAPI) handleHTTPError(goodStatusCode []int, resp *http.Response) ([]byte, error) { - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - if s.verbose { - resp.Body = ioutil.NopCloser(bytes.NewBuffer(body)) - dump, err := httputil.DumpResponse(resp, true) - if err == nil { - var js bytes.Buffer - - err = json.Indent(&js, body, "", " ") - if err != nil { - s.Debugf("[Response]: [%v]\n%v", resp.StatusCode, string(dump)) - } else { - s.Debugf("[Response]: [%v]\n%v", resp.StatusCode, js.String()) - } - } - } else { - s.Debugf("[Response]: [%v]\n%v", resp.StatusCode, string(body)) - } - - if resp.StatusCode >= http.StatusInternalServerError { - return nil, errors.New(string(body)) - } - good := false - for _, code := range goodStatusCode { - if code == resp.StatusCode { - good = true - } - } - if !good { - var scwError ScalewayAPIError - - if err := json.Unmarshal(body, &scwError); err != nil { - return nil, err - } - scwError.StatusCode = resp.StatusCode - s.Debugf("%s", scwError.Error()) - return nil, scwError - } - return body, nil -} - -func (s *ScalewayAPI) fetchServers(api string, query url.Values, out chan<- ScalewayServers) func() error { - return func() error { - resp, err := s.GetResponsePaginate(api, "servers", query) - if err != nil { - return err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return err - } - var servers ScalewayServers - - if err = json.Unmarshal(body, &servers); err != nil { - return err - } - out <- servers - return nil - } -} - -// GetServers gets the list of servers from the ScalewayAPI -func (s *ScalewayAPI) GetServers(all bool, limit int) (*[]ScalewayServer, error) { - query := url.Values{} - if !all { - query.Set("state", "running") - } - if limit > 0 { - // FIXME: wait for the API to be ready - // query.Set("per_page", strconv.Itoa(limit)) - panic("Not implemented yet") - } - if all && limit == 0 { - s.Cache.ClearServers() - } - var ( - g errgroup.Group - apis = []string{ - ComputeAPIPar1, - ComputeAPIAms1, - } - ) - - serverChan := make(chan ScalewayServers, len(apis)) - for _, api := range apis { - g.Go(s.fetchServers(api, query, serverChan)) - } - - if err := g.Wait(); err != nil { - return nil, err - } - close(serverChan) - var servers ScalewayServers - - for server := range serverChan { - servers.Servers = append(servers.Servers, server.Servers...) - } - - for i, server := range servers.Servers { - servers.Servers[i].DNSPublic = server.Identifier + URLPublicDNS - servers.Servers[i].DNSPrivate = server.Identifier + URLPrivateDNS - s.Cache.InsertServer(server.Identifier, server.Location.ZoneID, server.Arch, server.Organization, server.Name) - } - return &servers.Servers, nil -} - -// ScalewaySortServers represents a wrapper to sort by CreationDate the servers -type ScalewaySortServers []ScalewayServer - -func (s ScalewaySortServers) Len() int { - return len(s) -} - -func (s ScalewaySortServers) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} - -func (s ScalewaySortServers) Less(i, j int) bool { - date1, _ := time.Parse("2006-01-02T15:04:05.000000+00:00", s[i].CreationDate) - date2, _ := time.Parse("2006-01-02T15:04:05.000000+00:00", s[j].CreationDate) - return date2.Before(date1) -} - -// GetServer gets a server from the ScalewayAPI -func (s *ScalewayAPI) GetServer(serverID string) (*ScalewayServer, error) { - if serverID == "" { - return nil, fmt.Errorf("cannot get server without serverID") - } - resp, err := s.GetResponsePaginate(s.computeAPI, "servers/"+serverID, url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - - var oneServer ScalewayOneServer - - if err = json.Unmarshal(body, &oneServer); err != nil { - return nil, err - } - // FIXME arch, owner, title - oneServer.Server.DNSPublic = oneServer.Server.Identifier + URLPublicDNS - oneServer.Server.DNSPrivate = oneServer.Server.Identifier + URLPrivateDNS - s.Cache.InsertServer(oneServer.Server.Identifier, oneServer.Server.Location.ZoneID, oneServer.Server.Arch, oneServer.Server.Organization, oneServer.Server.Name) - return &oneServer.Server, nil -} - -// PostServerAction posts an action on a server -func (s *ScalewayAPI) PostServerAction(serverID, action string) error { - data := ScalewayServerAction{ - Action: action, - } - resp, err := s.PostResponse(s.computeAPI, fmt.Sprintf("servers/%s/action", serverID), data) - if err != nil { - return err - } - defer resp.Body.Close() - - _, err = s.handleHTTPError([]int{http.StatusAccepted}, resp) - return err -} - -// DeleteServer deletes a server -func (s *ScalewayAPI) DeleteServer(serverID string) error { - defer s.Cache.RemoveServer(serverID) - resp, err := s.DeleteResponse(s.computeAPI, fmt.Sprintf("servers/%s", serverID)) - if err != nil { - return err - } - defer resp.Body.Close() - - if _, err = s.handleHTTPError([]int{http.StatusNoContent}, resp); err != nil { - return err - } - return nil -} - -// PostServer creates a new server -func (s *ScalewayAPI) PostServer(definition ScalewayServerDefinition) (string, error) { - definition.Organization = s.Organization - - resp, err := s.PostResponse(s.computeAPI, "servers", definition) - if err != nil { - return "", err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusCreated}, resp) - if err != nil { - return "", err - } - var server ScalewayOneServer - - if err = json.Unmarshal(body, &server); err != nil { - return "", err - } - // FIXME arch, owner, title - s.Cache.InsertServer(server.Server.Identifier, server.Server.Location.ZoneID, server.Server.Arch, server.Server.Organization, server.Server.Name) - return server.Server.Identifier, nil -} - -// PatchUserSSHKey updates a user -func (s *ScalewayAPI) PatchUserSSHKey(UserID string, definition ScalewayUserPatchSSHKeyDefinition) error { - resp, err := s.PatchResponse(AccountAPI, fmt.Sprintf("users/%s", UserID), definition) - if err != nil { - return err - } - - defer resp.Body.Close() - - if _, err := s.handleHTTPError([]int{http.StatusOK}, resp); err != nil { - return err - } - return nil -} - -// PatchServer updates a server -func (s *ScalewayAPI) PatchServer(serverID string, definition ScalewayServerPatchDefinition) error { - resp, err := s.PatchResponse(s.computeAPI, fmt.Sprintf("servers/%s", serverID), definition) - if err != nil { - return err - } - defer resp.Body.Close() - - if _, err := s.handleHTTPError([]int{http.StatusOK}, resp); err != nil { - return err - } - return nil -} - -// PostSnapshot creates a new snapshot -func (s *ScalewayAPI) PostSnapshot(volumeID string, name string) (string, error) { - definition := ScalewaySnapshotDefinition{ - VolumeIDentifier: volumeID, - Name: name, - Organization: s.Organization, - } - resp, err := s.PostResponse(s.computeAPI, "snapshots", definition) - if err != nil { - return "", err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusCreated}, resp) - if err != nil { - return "", err - } - var snapshot ScalewayOneSnapshot - - if err = json.Unmarshal(body, &snapshot); err != nil { - return "", err - } - // FIXME arch, owner, title - s.Cache.InsertSnapshot(snapshot.Snapshot.Identifier, s.Region, "", snapshot.Snapshot.Organization, snapshot.Snapshot.Name) - return snapshot.Snapshot.Identifier, nil -} - -// PostImage creates a new image -func (s *ScalewayAPI) PostImage(volumeID string, name string, bootscript string, arch string) (string, error) { - definition := ScalewayImageDefinition{ - SnapshotIDentifier: volumeID, - Name: name, - Organization: s.Organization, - Arch: arch, - } - if bootscript != "" { - definition.DefaultBootscript = &bootscript - } - - resp, err := s.PostResponse(s.computeAPI, "images", definition) - if err != nil { - return "", err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusCreated}, resp) - if err != nil { - return "", err - } - var image ScalewayOneImage - - if err = json.Unmarshal(body, &image); err != nil { - return "", err - } - // FIXME region, arch, owner, title - s.Cache.InsertImage(image.Image.Identifier, s.Region, image.Image.Arch, image.Image.Organization, image.Image.Name, "") - return image.Image.Identifier, nil -} - -// PostVolume creates a new volume -func (s *ScalewayAPI) PostVolume(definition ScalewayVolumeDefinition) (string, error) { - definition.Organization = s.Organization - if definition.Type == "" { - definition.Type = "l_ssd" - } - - resp, err := s.PostResponse(s.computeAPI, "volumes", definition) - if err != nil { - return "", err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusCreated}, resp) - if err != nil { - return "", err - } - var volume ScalewayOneVolume - - if err = json.Unmarshal(body, &volume); err != nil { - return "", err - } - // FIXME: s.Cache.InsertVolume(volume.Volume.Identifier, volume.Volume.Name) - return volume.Volume.Identifier, nil -} - -// PutVolume updates a volume -func (s *ScalewayAPI) PutVolume(volumeID string, definition ScalewayVolumePutDefinition) error { - resp, err := s.PutResponse(s.computeAPI, fmt.Sprintf("volumes/%s", volumeID), definition) - if err != nil { - return err - } - defer resp.Body.Close() - - _, err = s.handleHTTPError([]int{http.StatusOK}, resp) - return err -} - -// ResolveServer attempts to find a matching Identifier for the input string -func (s *ScalewayAPI) ResolveServer(needle string) (ScalewayResolverResults, error) { - servers, err := s.Cache.LookUpServers(needle, true) - if err != nil { - return servers, err - } - if len(servers) == 0 { - if _, err = s.GetServers(true, 0); err != nil { - return nil, err - } - servers, err = s.Cache.LookUpServers(needle, true) - } - return servers, err -} - -// ResolveVolume attempts to find a matching Identifier for the input string -func (s *ScalewayAPI) ResolveVolume(needle string) (ScalewayResolverResults, error) { - volumes, err := s.Cache.LookUpVolumes(needle, true) - if err != nil { - return volumes, err - } - if len(volumes) == 0 { - if _, err = s.GetVolumes(); err != nil { - return nil, err - } - volumes, err = s.Cache.LookUpVolumes(needle, true) - } - return volumes, err -} - -// ResolveSnapshot attempts to find a matching Identifier for the input string -func (s *ScalewayAPI) ResolveSnapshot(needle string) (ScalewayResolverResults, error) { - snapshots, err := s.Cache.LookUpSnapshots(needle, true) - if err != nil { - return snapshots, err - } - if len(snapshots) == 0 { - if _, err = s.GetSnapshots(); err != nil { - return nil, err - } - snapshots, err = s.Cache.LookUpSnapshots(needle, true) - } - return snapshots, err -} - -// ResolveImage attempts to find a matching Identifier for the input string -func (s *ScalewayAPI) ResolveImage(needle string) (ScalewayResolverResults, error) { - images, err := s.Cache.LookUpImages(needle, true) - if err != nil { - return images, err - } - if len(images) == 0 { - if _, err = s.GetImages(); err != nil { - return nil, err - } - images, err = s.Cache.LookUpImages(needle, true) - } - return images, err -} - -// ResolveBootscript attempts to find a matching Identifier for the input string -func (s *ScalewayAPI) ResolveBootscript(needle string) (ScalewayResolverResults, error) { - bootscripts, err := s.Cache.LookUpBootscripts(needle, true) - if err != nil { - return bootscripts, err - } - if len(bootscripts) == 0 { - if _, err = s.GetBootscripts(); err != nil { - return nil, err - } - bootscripts, err = s.Cache.LookUpBootscripts(needle, true) - } - return bootscripts, err -} - -// GetImages gets the list of images from the ScalewayAPI -func (s *ScalewayAPI) GetImages() (*[]MarketImage, error) { - images, err := s.GetMarketPlaceImages("") - if err != nil { - return nil, err - } - s.Cache.ClearImages() - for i, image := range images.Images { - if image.CurrentPublicVersion != "" { - for _, version := range image.Versions { - if version.ID == image.CurrentPublicVersion { - for _, localImage := range version.LocalImages { - images.Images[i].Public = true - s.Cache.InsertImage(localImage.ID, localImage.Zone, localImage.Arch, image.Organization.ID, image.Name, image.CurrentPublicVersion) - } - } - } - } - } - values := url.Values{} - values.Set("organization", s.Organization) - resp, err := s.GetResponsePaginate(s.computeAPI, "images", values) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var OrgaImages ScalewayImages - - if err = json.Unmarshal(body, &OrgaImages); err != nil { - return nil, err - } - - for _, orgaImage := range OrgaImages.Images { - images.Images = append(images.Images, MarketImage{ - Categories: []string{"MyImages"}, - CreationDate: orgaImage.CreationDate, - CurrentPublicVersion: orgaImage.Identifier, - ModificationDate: orgaImage.ModificationDate, - Name: orgaImage.Name, - Public: false, - MarketVersions: MarketVersions{ - Versions: []MarketVersionDefinition{ - { - CreationDate: orgaImage.CreationDate, - ID: orgaImage.Identifier, - ModificationDate: orgaImage.ModificationDate, - MarketLocalImages: MarketLocalImages{ - LocalImages: []MarketLocalImageDefinition{ - { - Arch: orgaImage.Arch, - ID: orgaImage.Identifier, - // TODO: fecth images from ams1 and par1 - Zone: s.Region, - }, - }, - }, - }, - }, - }, - }) - s.Cache.InsertImage(orgaImage.Identifier, s.Region, orgaImage.Arch, orgaImage.Organization, orgaImage.Name, "") - } - return &images.Images, nil -} - -// GetImage gets an image from the ScalewayAPI -func (s *ScalewayAPI) GetImage(imageID string) (*ScalewayImage, error) { - resp, err := s.GetResponsePaginate(s.computeAPI, "images/"+imageID, url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var oneImage ScalewayOneImage - - if err = json.Unmarshal(body, &oneImage); err != nil { - return nil, err - } - // FIXME owner, title - s.Cache.InsertImage(oneImage.Image.Identifier, s.Region, oneImage.Image.Arch, oneImage.Image.Organization, oneImage.Image.Name, "") - return &oneImage.Image, nil -} - -// DeleteImage deletes a image -func (s *ScalewayAPI) DeleteImage(imageID string) error { - defer s.Cache.RemoveImage(imageID) - resp, err := s.DeleteResponse(s.computeAPI, fmt.Sprintf("images/%s", imageID)) - if err != nil { - return err - } - defer resp.Body.Close() - - if _, err := s.handleHTTPError([]int{http.StatusNoContent}, resp); err != nil { - return err - } - return nil -} - -// DeleteSnapshot deletes a snapshot -func (s *ScalewayAPI) DeleteSnapshot(snapshotID string) error { - defer s.Cache.RemoveSnapshot(snapshotID) - resp, err := s.DeleteResponse(s.computeAPI, fmt.Sprintf("snapshots/%s", snapshotID)) - if err != nil { - return err - } - defer resp.Body.Close() - - if _, err := s.handleHTTPError([]int{http.StatusNoContent}, resp); err != nil { - return err - } - return nil -} - -// DeleteVolume deletes a volume -func (s *ScalewayAPI) DeleteVolume(volumeID string) error { - defer s.Cache.RemoveVolume(volumeID) - resp, err := s.DeleteResponse(s.computeAPI, fmt.Sprintf("volumes/%s", volumeID)) - if err != nil { - return err - } - defer resp.Body.Close() - - if _, err := s.handleHTTPError([]int{http.StatusNoContent}, resp); err != nil { - return err - } - return nil -} - -// GetSnapshots gets the list of snapshots from the ScalewayAPI -func (s *ScalewayAPI) GetSnapshots() (*[]ScalewaySnapshot, error) { - query := url.Values{} - s.Cache.ClearSnapshots() - - resp, err := s.GetResponsePaginate(s.computeAPI, "snapshots", query) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var snapshots ScalewaySnapshots - - if err = json.Unmarshal(body, &snapshots); err != nil { - return nil, err - } - for _, snapshot := range snapshots.Snapshots { - // FIXME region, arch, owner, title - s.Cache.InsertSnapshot(snapshot.Identifier, s.Region, "", snapshot.Organization, snapshot.Name) - } - return &snapshots.Snapshots, nil -} - -// GetSnapshot gets a snapshot from the ScalewayAPI -func (s *ScalewayAPI) GetSnapshot(snapshotID string) (*ScalewaySnapshot, error) { - resp, err := s.GetResponsePaginate(s.computeAPI, "snapshots/"+snapshotID, url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var oneSnapshot ScalewayOneSnapshot - - if err = json.Unmarshal(body, &oneSnapshot); err != nil { - return nil, err - } - // FIXME region, arch, owner, title - s.Cache.InsertSnapshot(oneSnapshot.Snapshot.Identifier, s.Region, "", oneSnapshot.Snapshot.Organization, oneSnapshot.Snapshot.Name) - return &oneSnapshot.Snapshot, nil -} - -// GetVolumes gets the list of volumes from the ScalewayAPI -func (s *ScalewayAPI) GetVolumes() (*[]ScalewayVolume, error) { - query := url.Values{} - s.Cache.ClearVolumes() - - resp, err := s.GetResponsePaginate(s.computeAPI, "volumes", query) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - - var volumes ScalewayVolumes - - if err = json.Unmarshal(body, &volumes); err != nil { - return nil, err - } - for _, volume := range volumes.Volumes { - // FIXME region, arch, owner, title - s.Cache.InsertVolume(volume.Identifier, s.Region, "", volume.Organization, volume.Name) - } - return &volumes.Volumes, nil -} - -// GetVolume gets a volume from the ScalewayAPI -func (s *ScalewayAPI) GetVolume(volumeID string) (*ScalewayVolume, error) { - resp, err := s.GetResponsePaginate(s.computeAPI, "volumes/"+volumeID, url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var oneVolume ScalewayOneVolume - - if err = json.Unmarshal(body, &oneVolume); err != nil { - return nil, err - } - // FIXME region, arch, owner, title - s.Cache.InsertVolume(oneVolume.Volume.Identifier, s.Region, "", oneVolume.Volume.Organization, oneVolume.Volume.Name) - return &oneVolume.Volume, nil -} - -// GetBootscripts gets the list of bootscripts from the ScalewayAPI -func (s *ScalewayAPI) GetBootscripts() (*[]ScalewayBootscript, error) { - query := url.Values{} - - s.Cache.ClearBootscripts() - resp, err := s.GetResponsePaginate(s.computeAPI, "bootscripts", query) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var bootscripts ScalewayBootscripts - - if err = json.Unmarshal(body, &bootscripts); err != nil { - return nil, err - } - for _, bootscript := range bootscripts.Bootscripts { - // FIXME region, arch, owner, title - s.Cache.InsertBootscript(bootscript.Identifier, s.Region, bootscript.Arch, bootscript.Organization, bootscript.Title) - } - return &bootscripts.Bootscripts, nil -} - -// GetBootscript gets a bootscript from the ScalewayAPI -func (s *ScalewayAPI) GetBootscript(bootscriptID string) (*ScalewayBootscript, error) { - resp, err := s.GetResponsePaginate(s.computeAPI, "bootscripts/"+bootscriptID, url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var oneBootscript ScalewayOneBootscript - - if err = json.Unmarshal(body, &oneBootscript); err != nil { - return nil, err - } - // FIXME region, arch, owner, title - s.Cache.InsertBootscript(oneBootscript.Bootscript.Identifier, s.Region, oneBootscript.Bootscript.Arch, oneBootscript.Bootscript.Organization, oneBootscript.Bootscript.Title) - return &oneBootscript.Bootscript, nil -} - -// GetUserdatas gets list of userdata for a server -func (s *ScalewayAPI) GetUserdatas(serverID string, metadata bool) (*ScalewayUserdatas, error) { - var uri, endpoint string - - endpoint = s.computeAPI - if metadata { - uri = "/user_data" - endpoint = MetadataAPI - } else { - uri = fmt.Sprintf("servers/%s/user_data", serverID) - } - - resp, err := s.GetResponsePaginate(endpoint, uri, url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var userdatas ScalewayUserdatas - - if err = json.Unmarshal(body, &userdatas); err != nil { - return nil, err - } - return &userdatas, nil -} - -func (s *ScalewayUserdata) String() string { - return string(*s) -} - -// GetUserdata gets a specific userdata for a server -func (s *ScalewayAPI) GetUserdata(serverID, key string, metadata bool) (*ScalewayUserdata, error) { - var uri, endpoint string - - endpoint = s.computeAPI - if metadata { - uri = fmt.Sprintf("/user_data/%s", key) - endpoint = MetadataAPI - } else { - uri = fmt.Sprintf("servers/%s/user_data/%s", serverID, key) - } - - var err error - resp, err := s.GetResponsePaginate(endpoint, uri, url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("no such user_data %q (%d)", key, resp.StatusCode) - } - var data ScalewayUserdata - data, err = ioutil.ReadAll(resp.Body) - return &data, err -} - -// PatchUserdata sets a user data -func (s *ScalewayAPI) PatchUserdata(serverID, key string, value []byte, metadata bool) error { - var resource, endpoint string - - endpoint = s.computeAPI - if metadata { - resource = fmt.Sprintf("/user_data/%s", key) - endpoint = MetadataAPI - } else { - resource = fmt.Sprintf("servers/%s/user_data/%s", serverID, key) - } - - uri := fmt.Sprintf("%s/%s", strings.TrimRight(endpoint, "/"), resource) - payload := new(bytes.Buffer) - payload.Write(value) - - req, err := http.NewRequest("PATCH", uri, payload) - if err != nil { - return err - } - - req.Header.Set("X-Auth-Token", s.Token) - req.Header.Set("Content-Type", "text/plain") - req.Header.Set("User-Agent", s.userAgent) - - s.LogHTTP(req) - - resp, err := s.client.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode == http.StatusNoContent { - return nil - } - - return fmt.Errorf("cannot set user_data (%d)", resp.StatusCode) -} - -// DeleteUserdata deletes a server user_data -func (s *ScalewayAPI) DeleteUserdata(serverID, key string, metadata bool) error { - var url, endpoint string - - endpoint = s.computeAPI - if metadata { - url = fmt.Sprintf("/user_data/%s", key) - endpoint = MetadataAPI - } else { - url = fmt.Sprintf("servers/%s/user_data/%s", serverID, key) - } - - resp, err := s.DeleteResponse(endpoint, url) - if err != nil { - return err - } - defer resp.Body.Close() - - _, err = s.handleHTTPError([]int{http.StatusNoContent}, resp) - return err -} - -// GetTasks get the list of tasks from the ScalewayAPI -func (s *ScalewayAPI) GetTasks() (*[]ScalewayTask, error) { - query := url.Values{} - resp, err := s.GetResponsePaginate(s.computeAPI, "tasks", query) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var tasks ScalewayTasks - - if err = json.Unmarshal(body, &tasks); err != nil { - return nil, err - } - return &tasks.Tasks, nil -} - -// CheckCredentials performs a dummy check to ensure we can contact the API -func (s *ScalewayAPI) CheckCredentials() error { - query := url.Values{} - - resp, err := s.GetResponsePaginate(AccountAPI, "tokens", query) - if err != nil { - return err - } - defer resp.Body.Close() - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return err - } - var tokens ScalewayGetTokens - if err = json.Unmarshal(body, &tokens); err != nil { - return err - } - return nil -} - -// GetUserID returns the userID -func (s *ScalewayAPI) GetUserID() (string, error) { - resp, err := s.GetResponsePaginate(AccountAPI, fmt.Sprintf("tokens/%s", s.Token), url.Values{}) - if err != nil { - return "", err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return "", err - } - var token ScalewayTokensDefinition - - if err = json.Unmarshal(body, &token); err != nil { - return "", err - } - return token.Token.UserID, nil -} - -// GetOrganization returns Organization -func (s *ScalewayAPI) GetOrganization() (*ScalewayOrganizationsDefinition, error) { - resp, err := s.GetResponsePaginate(AccountAPI, "organizations", url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var data ScalewayOrganizationsDefinition - - if err = json.Unmarshal(body, &data); err != nil { - return nil, err - } - return &data, nil -} - -// GetUser returns the user -func (s *ScalewayAPI) GetUser() (*ScalewayUserDefinition, error) { - userID, err := s.GetUserID() - if err != nil { - return nil, err - } - resp, err := s.GetResponsePaginate(AccountAPI, fmt.Sprintf("users/%s", userID), url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var user ScalewayUsersDefinition - - if err = json.Unmarshal(body, &user); err != nil { - return nil, err - } - return &user.User, nil -} - -// GetPermissions returns the permissions -func (s *ScalewayAPI) GetPermissions() (*ScalewayPermissionDefinition, error) { - resp, err := s.GetResponsePaginate(AccountAPI, fmt.Sprintf("tokens/%s/permissions", s.Token), url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var permissions ScalewayPermissionDefinition - - if err = json.Unmarshal(body, &permissions); err != nil { - return nil, err - } - return &permissions, nil -} - -// GetDashboard returns the dashboard -func (s *ScalewayAPI) GetDashboard() (*ScalewayDashboard, error) { - resp, err := s.GetResponsePaginate(s.computeAPI, "dashboard", url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var dashboard ScalewayDashboardResp - - if err = json.Unmarshal(body, &dashboard); err != nil { - return nil, err - } - return &dashboard.Dashboard, nil -} - -// GetServerID returns exactly one server matching -func (s *ScalewayAPI) GetServerID(needle string) (string, error) { - // Parses optional type prefix, i.e: "server:name" -> "name" - _, needle = parseNeedle(needle) - - servers, err := s.ResolveServer(needle) - if err != nil { - return "", fmt.Errorf("Unable to resolve server %s: %s", needle, err) - } - if len(servers) == 1 { - return servers[0].Identifier, nil - } - if len(servers) == 0 { - return "", fmt.Errorf("No such server: %s", needle) - } - return "", showResolverResults(needle, servers) -} - -func showResolverResults(needle string, results ScalewayResolverResults) error { - w := tabwriter.NewWriter(os.Stderr, 20, 1, 3, ' ', 0) - defer w.Flush() - sort.Sort(results) - fmt.Fprintf(w, " IMAGEID\tFROM\tNAME\tZONE\tARCH\n") - for _, result := range results { - if result.Arch == "" { - result.Arch = "n/a" - } - fmt.Fprintf(w, "- %s\t%s\t%s\t%s\t%s\n", result.TruncIdentifier(), result.CodeName(), result.Name, result.Region, result.Arch) - } - return fmt.Errorf("Too many candidates for %s (%d)", needle, len(results)) -} - -// GetVolumeID returns exactly one volume matching -func (s *ScalewayAPI) GetVolumeID(needle string) (string, error) { - // Parses optional type prefix, i.e: "volume:name" -> "name" - _, needle = parseNeedle(needle) - - volumes, err := s.ResolveVolume(needle) - if err != nil { - return "", fmt.Errorf("Unable to resolve volume %s: %s", needle, err) - } - if len(volumes) == 1 { - return volumes[0].Identifier, nil - } - if len(volumes) == 0 { - return "", fmt.Errorf("No such volume: %s", needle) - } - return "", showResolverResults(needle, volumes) -} - -// GetSnapshotID returns exactly one snapshot matching -func (s *ScalewayAPI) GetSnapshotID(needle string) (string, error) { - // Parses optional type prefix, i.e: "snapshot:name" -> "name" - _, needle = parseNeedle(needle) - - snapshots, err := s.ResolveSnapshot(needle) - if err != nil { - return "", fmt.Errorf("Unable to resolve snapshot %s: %s", needle, err) - } - if len(snapshots) == 1 { - return snapshots[0].Identifier, nil - } - if len(snapshots) == 0 { - return "", fmt.Errorf("No such snapshot: %s", needle) - } - return "", showResolverResults(needle, snapshots) -} - -// FilterImagesByArch removes entry that doesn't match with architecture -func FilterImagesByArch(res ScalewayResolverResults, arch string) (ret ScalewayResolverResults) { - if arch == "*" { - return res - } - for _, result := range res { - if result.Arch == arch { - ret = append(ret, result) - } - } - return -} - -// FilterImagesByRegion removes entry that doesn't match with region -func FilterImagesByRegion(res ScalewayResolverResults, region string) (ret ScalewayResolverResults) { - if region == "*" { - return res - } - for _, result := range res { - if result.Region == region { - ret = append(ret, result) - } - } - return -} - -// GetImageID returns exactly one image matching -func (s *ScalewayAPI) GetImageID(needle, arch string) (*ScalewayImageIdentifier, error) { - // Parses optional type prefix, i.e: "image:name" -> "name" - _, needle = parseNeedle(needle) - - images, err := s.ResolveImage(needle) - if err != nil { - return nil, fmt.Errorf("Unable to resolve image %s: %s", needle, err) - } - images = FilterImagesByArch(images, arch) - images = FilterImagesByRegion(images, s.Region) - if len(images) == 1 { - return &ScalewayImageIdentifier{ - Identifier: images[0].Identifier, - Arch: images[0].Arch, - // FIXME region, owner hardcoded - Region: images[0].Region, - Owner: "", - }, nil - } - if len(images) == 0 { - return nil, fmt.Errorf("No such image (zone %s, arch %s) : %s", s.Region, arch, needle) - } - return nil, showResolverResults(needle, images) -} - -// GetSecurityGroups returns a ScalewaySecurityGroups -func (s *ScalewayAPI) GetSecurityGroups() (*ScalewayGetSecurityGroups, error) { - resp, err := s.GetResponsePaginate(s.computeAPI, "security_groups", url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var securityGroups ScalewayGetSecurityGroups - - if err = json.Unmarshal(body, &securityGroups); err != nil { - return nil, err - } - return &securityGroups, nil -} - -// GetSecurityGroupRules returns a ScalewaySecurityGroupRules -func (s *ScalewayAPI) GetSecurityGroupRules(groupID string) (*ScalewayGetSecurityGroupRules, error) { - resp, err := s.GetResponsePaginate(s.computeAPI, fmt.Sprintf("security_groups/%s/rules", groupID), url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var securityGroupRules ScalewayGetSecurityGroupRules - - if err = json.Unmarshal(body, &securityGroupRules); err != nil { - return nil, err - } - return &securityGroupRules, nil -} - -// GetASecurityGroupRule returns a ScalewaySecurityGroupRule -func (s *ScalewayAPI) GetASecurityGroupRule(groupID string, rulesID string) (*ScalewayGetSecurityGroupRule, error) { - resp, err := s.GetResponsePaginate(s.computeAPI, fmt.Sprintf("security_groups/%s/rules/%s", groupID, rulesID), url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var securityGroupRules ScalewayGetSecurityGroupRule - - if err = json.Unmarshal(body, &securityGroupRules); err != nil { - return nil, err - } - return &securityGroupRules, nil -} - -// GetASecurityGroup returns a ScalewaySecurityGroup -func (s *ScalewayAPI) GetASecurityGroup(groupsID string) (*ScalewayGetSecurityGroup, error) { - resp, err := s.GetResponsePaginate(s.computeAPI, fmt.Sprintf("security_groups/%s", groupsID), url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var securityGroups ScalewayGetSecurityGroup - - if err = json.Unmarshal(body, &securityGroups); err != nil { - return nil, err - } - return &securityGroups, nil -} - -// PostSecurityGroup posts a group on a server -func (s *ScalewayAPI) PostSecurityGroup(group ScalewayNewSecurityGroup) error { - resp, err := s.PostResponse(s.computeAPI, "security_groups", group) - if err != nil { - return err - } - defer resp.Body.Close() - - _, err = s.handleHTTPError([]int{http.StatusCreated}, resp) - return err -} - -// PostSecurityGroupRule posts a rule on a server -func (s *ScalewayAPI) PostSecurityGroupRule(SecurityGroupID string, rules ScalewayNewSecurityGroupRule) error { - resp, err := s.PostResponse(s.computeAPI, fmt.Sprintf("security_groups/%s/rules", SecurityGroupID), rules) - if err != nil { - return err - } - defer resp.Body.Close() - - _, err = s.handleHTTPError([]int{http.StatusCreated}, resp) - return err -} - -// DeleteSecurityGroup deletes a SecurityGroup -func (s *ScalewayAPI) DeleteSecurityGroup(securityGroupID string) error { - resp, err := s.DeleteResponse(s.computeAPI, fmt.Sprintf("security_groups/%s", securityGroupID)) - if err != nil { - return err - } - defer resp.Body.Close() - - _, err = s.handleHTTPError([]int{http.StatusNoContent}, resp) - return err -} - -// PutSecurityGroup updates a SecurityGroup -func (s *ScalewayAPI) PutSecurityGroup(group ScalewayUpdateSecurityGroup, securityGroupID string) error { - resp, err := s.PutResponse(s.computeAPI, fmt.Sprintf("security_groups/%s", securityGroupID), group) - if err != nil { - return err - } - defer resp.Body.Close() - - _, err = s.handleHTTPError([]int{http.StatusOK}, resp) - return err -} - -// PutSecurityGroupRule updates a SecurityGroupRule -func (s *ScalewayAPI) PutSecurityGroupRule(rules ScalewayNewSecurityGroupRule, securityGroupID, RuleID string) error { - resp, err := s.PutResponse(s.computeAPI, fmt.Sprintf("security_groups/%s/rules/%s", securityGroupID, RuleID), rules) - if err != nil { - return err - } - defer resp.Body.Close() - - _, err = s.handleHTTPError([]int{http.StatusOK}, resp) - return err -} - -// DeleteSecurityGroupRule deletes a SecurityGroupRule -func (s *ScalewayAPI) DeleteSecurityGroupRule(SecurityGroupID, RuleID string) error { - resp, err := s.DeleteResponse(s.computeAPI, fmt.Sprintf("security_groups/%s/rules/%s", SecurityGroupID, RuleID)) - if err != nil { - return err - } - defer resp.Body.Close() - - _, err = s.handleHTTPError([]int{http.StatusNoContent}, resp) - return err -} - -// GetContainers returns a ScalewayGetContainers -func (s *ScalewayAPI) GetContainers() (*ScalewayGetContainers, error) { - resp, err := s.GetResponsePaginate(s.computeAPI, "containers", url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var containers ScalewayGetContainers - - if err = json.Unmarshal(body, &containers); err != nil { - return nil, err - } - return &containers, nil -} - -// GetContainerDatas returns a ScalewayGetContainerDatas -func (s *ScalewayAPI) GetContainerDatas(container string) (*ScalewayGetContainerDatas, error) { - resp, err := s.GetResponsePaginate(s.computeAPI, fmt.Sprintf("containers/%s", container), url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var datas ScalewayGetContainerDatas - - if err = json.Unmarshal(body, &datas); err != nil { - return nil, err - } - return &datas, nil -} - -// GetIPS returns a ScalewayGetIPS -func (s *ScalewayAPI) GetIPS() (*ScalewayGetIPS, error) { - resp, err := s.GetResponsePaginate(s.computeAPI, "ips", url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var ips ScalewayGetIPS - - if err = json.Unmarshal(body, &ips); err != nil { - return nil, err - } - return &ips, nil -} - -// NewIP returns a new IP -func (s *ScalewayAPI) NewIP() (*ScalewayGetIP, error) { - var orga struct { - Organization string `json:"organization"` - } - orga.Organization = s.Organization - resp, err := s.PostResponse(s.computeAPI, "ips", orga) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusCreated}, resp) - if err != nil { - return nil, err - } - var ip ScalewayGetIP - - if err = json.Unmarshal(body, &ip); err != nil { - return nil, err - } - return &ip, nil -} - -// AttachIP attachs an IP to a server -func (s *ScalewayAPI) AttachIP(ipID, serverID string) error { - var update struct { - Address string `json:"address"` - ID string `json:"id"` - Reverse *string `json:"reverse"` - Organization string `json:"organization"` - Server string `json:"server"` - } - - ip, err := s.GetIP(ipID) - if err != nil { - return err - } - update.Address = ip.IP.Address - update.ID = ip.IP.ID - update.Organization = ip.IP.Organization - update.Server = serverID - resp, err := s.PutResponse(s.computeAPI, fmt.Sprintf("ips/%s", ipID), update) - if err != nil { - return err - } - _, err = s.handleHTTPError([]int{http.StatusOK}, resp) - return err -} - -// DetachIP detaches an IP from a server -func (s *ScalewayAPI) DetachIP(ipID string) error { - ip, err := s.GetIP(ipID) - if err != nil { - return err - } - ip.IP.Server = nil - resp, err := s.PutResponse(s.computeAPI, fmt.Sprintf("ips/%s", ipID), ip.IP) - if err != nil { - return err - } - defer resp.Body.Close() - _, err = s.handleHTTPError([]int{http.StatusOK}, resp) - return err -} - -// DeleteIP deletes an IP -func (s *ScalewayAPI) DeleteIP(ipID string) error { - resp, err := s.DeleteResponse(s.computeAPI, fmt.Sprintf("ips/%s", ipID)) - if err != nil { - return err - } - defer resp.Body.Close() - _, err = s.handleHTTPError([]int{http.StatusNoContent}, resp) - return err -} - -// GetIP returns a ScalewayGetIP -func (s *ScalewayAPI) GetIP(ipID string) (*ScalewayGetIP, error) { - resp, err := s.GetResponsePaginate(s.computeAPI, fmt.Sprintf("ips/%s", ipID), url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var ip ScalewayGetIP - - if err = json.Unmarshal(body, &ip); err != nil { - return nil, err - } - return &ip, nil -} - -// GetQuotas returns a ScalewayGetQuotas -func (s *ScalewayAPI) GetQuotas() (*ScalewayGetQuotas, error) { - resp, err := s.GetResponsePaginate(AccountAPI, fmt.Sprintf("organizations/%s/quotas", s.Organization), url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var quotas ScalewayGetQuotas - - if err = json.Unmarshal(body, "as); err != nil { - return nil, err - } - return "as, nil -} - -// GetBootscriptID returns exactly one bootscript matching -func (s *ScalewayAPI) GetBootscriptID(needle, arch string) (string, error) { - // Parses optional type prefix, i.e: "bootscript:name" -> "name" - _, needle = parseNeedle(needle) - - bootscripts, err := s.ResolveBootscript(needle) - if err != nil { - return "", fmt.Errorf("Unable to resolve bootscript %s: %s", needle, err) - } - bootscripts.FilterByArch(arch) - if len(bootscripts) == 1 { - return bootscripts[0].Identifier, nil - } - if len(bootscripts) == 0 { - return "", fmt.Errorf("No such bootscript: %s", needle) - } - return "", showResolverResults(needle, bootscripts) -} - -func rootNetDial(network, addr string) (net.Conn, error) { - dialer := net.Dialer{ - Timeout: 10 * time.Second, - KeepAlive: 10 * time.Second, - } - - // bruteforce privileged ports - var localAddr net.Addr - var err error - for port := 1; port <= 1024; port++ { - localAddr, err = net.ResolveTCPAddr("tcp", fmt.Sprintf(":%d", port)) - - // this should never happen - if err != nil { - return nil, err - } - - dialer.LocalAddr = localAddr - - conn, err := dialer.Dial(network, addr) - - // if err is nil, dialer.Dial succeed, so let's go - // else, err != nil, but we don't care - if err == nil { - return conn, nil - } - } - // if here, all privileged ports were tried without success - return nil, fmt.Errorf("bind: permission denied, are you root ?") -} - -// SetPassword register the password -func (s *ScalewayAPI) SetPassword(password string) { - s.password = password -} - -// GetMarketPlaceImages returns images from marketplace -func (s *ScalewayAPI) GetMarketPlaceImages(uuidImage string) (*MarketImages, error) { - resp, err := s.GetResponsePaginate(MarketplaceAPI, fmt.Sprintf("images/%s", uuidImage), url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var ret MarketImages - - if uuidImage != "" { - ret.Images = make([]MarketImage, 1) - - var img MarketImage - - if err = json.Unmarshal(body, &img); err != nil { - return nil, err - } - ret.Images[0] = img - } else { - if err = json.Unmarshal(body, &ret); err != nil { - return nil, err - } - } - return &ret, nil -} - -// GetMarketPlaceImageVersions returns image version -func (s *ScalewayAPI) GetMarketPlaceImageVersions(uuidImage, uuidVersion string) (*MarketVersions, error) { - resp, err := s.GetResponsePaginate(MarketplaceAPI, fmt.Sprintf("images/%v/versions/%s", uuidImage, uuidVersion), url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var ret MarketVersions - - if uuidImage != "" { - var version MarketVersion - ret.Versions = make([]MarketVersionDefinition, 1) - - if err = json.Unmarshal(body, &version); err != nil { - return nil, err - } - ret.Versions[0] = version.Version - } else { - if err = json.Unmarshal(body, &ret); err != nil { - return nil, err - } - } - return &ret, nil -} - -// GetMarketPlaceImageCurrentVersion return the image current version -func (s *ScalewayAPI) GetMarketPlaceImageCurrentVersion(uuidImage string) (*MarketVersion, error) { - resp, err := s.GetResponsePaginate(MarketplaceAPI, fmt.Sprintf("images/%v/versions/current", uuidImage), url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var ret MarketVersion - - if err = json.Unmarshal(body, &ret); err != nil { - return nil, err - } - return &ret, nil -} - -// GetMarketPlaceLocalImages returns images from local region -func (s *ScalewayAPI) GetMarketPlaceLocalImages(uuidImage, uuidVersion, uuidLocalImage string) (*MarketLocalImages, error) { - resp, err := s.GetResponsePaginate(MarketplaceAPI, fmt.Sprintf("images/%v/versions/%s/local_images/%s", uuidImage, uuidVersion, uuidLocalImage), url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - var ret MarketLocalImages - if uuidLocalImage != "" { - var localImage MarketLocalImage - ret.LocalImages = make([]MarketLocalImageDefinition, 1) - - if err = json.Unmarshal(body, &localImage); err != nil { - return nil, err - } - ret.LocalImages[0] = localImage.LocalImages - } else { - if err = json.Unmarshal(body, &ret); err != nil { - return nil, err - } - } - return &ret, nil -} - -// PostMarketPlaceImage adds new image -func (s *ScalewayAPI) PostMarketPlaceImage(images MarketImage) error { - resp, err := s.PostResponse(MarketplaceAPI, "images/", images) - if err != nil { - return err - } - defer resp.Body.Close() - _, err = s.handleHTTPError([]int{http.StatusAccepted}, resp) - return err -} - -// PostMarketPlaceImageVersion adds new image version -func (s *ScalewayAPI) PostMarketPlaceImageVersion(uuidImage string, version MarketVersion) error { - resp, err := s.PostResponse(MarketplaceAPI, fmt.Sprintf("images/%v/versions", uuidImage), version) - if err != nil { - return err - } - defer resp.Body.Close() - _, err = s.handleHTTPError([]int{http.StatusAccepted}, resp) - return err -} - -// PostMarketPlaceLocalImage adds new local image -func (s *ScalewayAPI) PostMarketPlaceLocalImage(uuidImage, uuidVersion, uuidLocalImage string, local MarketLocalImage) error { - resp, err := s.PostResponse(MarketplaceAPI, fmt.Sprintf("images/%v/versions/%s/local_images/%v", uuidImage, uuidVersion, uuidLocalImage), local) - if err != nil { - return err - } - defer resp.Body.Close() - _, err = s.handleHTTPError([]int{http.StatusAccepted}, resp) - return err -} - -// PutMarketPlaceImage updates image -func (s *ScalewayAPI) PutMarketPlaceImage(uudiImage string, images MarketImage) error { - resp, err := s.PutResponse(MarketplaceAPI, fmt.Sprintf("images/%v", uudiImage), images) - if err != nil { - return err - } - defer resp.Body.Close() - _, err = s.handleHTTPError([]int{http.StatusOK}, resp) - return err -} - -// PutMarketPlaceImageVersion updates image version -func (s *ScalewayAPI) PutMarketPlaceImageVersion(uuidImage, uuidVersion string, version MarketVersion) error { - resp, err := s.PutResponse(MarketplaceAPI, fmt.Sprintf("images/%v/versions/%v", uuidImage, uuidVersion), version) - if err != nil { - return err - } - defer resp.Body.Close() - _, err = s.handleHTTPError([]int{http.StatusOK}, resp) - return err -} - -// PutMarketPlaceLocalImage updates local image -func (s *ScalewayAPI) PutMarketPlaceLocalImage(uuidImage, uuidVersion, uuidLocalImage string, local MarketLocalImage) error { - resp, err := s.PostResponse(MarketplaceAPI, fmt.Sprintf("images/%v/versions/%s/local_images/%v", uuidImage, uuidVersion, uuidLocalImage), local) - if err != nil { - return err - } - defer resp.Body.Close() - _, err = s.handleHTTPError([]int{http.StatusOK}, resp) - return err -} - -// DeleteMarketPlaceImage deletes image -func (s *ScalewayAPI) DeleteMarketPlaceImage(uudImage string) error { - resp, err := s.DeleteResponse(MarketplaceAPI, fmt.Sprintf("images/%v", uudImage)) - if err != nil { - return err - } - defer resp.Body.Close() - _, err = s.handleHTTPError([]int{http.StatusNoContent}, resp) - return err -} - -// DeleteMarketPlaceImageVersion delete image version -func (s *ScalewayAPI) DeleteMarketPlaceImageVersion(uuidImage, uuidVersion string) error { - resp, err := s.DeleteResponse(MarketplaceAPI, fmt.Sprintf("images/%v/versions/%v", uuidImage, uuidVersion)) - if err != nil { - return err - } - defer resp.Body.Close() - _, err = s.handleHTTPError([]int{http.StatusNoContent}, resp) - return err -} - -// DeleteMarketPlaceLocalImage deletes local image -func (s *ScalewayAPI) DeleteMarketPlaceLocalImage(uuidImage, uuidVersion, uuidLocalImage string) error { - resp, err := s.DeleteResponse(MarketplaceAPI, fmt.Sprintf("images/%v/versions/%s/local_images/%v", uuidImage, uuidVersion, uuidLocalImage)) - if err != nil { - return err - } - defer resp.Body.Close() - _, err = s.handleHTTPError([]int{http.StatusNoContent}, resp) - return err -} - -// ResolveTTYUrl return an URL to get a tty -func (s *ScalewayAPI) ResolveTTYUrl() string { - switch s.Region { - case "par1", "": - return "https://tty-par1.scaleway.com/v2/" - case "ams1": - return "https://tty-ams1.scaleway.com" - } - return "" -} - -// GetProductServers Fetches all the server type and their constraints from the Products API -func (s *ScalewayAPI) GetProductsServers() (*ScalewayProductsServers, error) { - resp, err := s.GetResponsePaginate(s.computeAPI, "products/servers", url.Values{}) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := s.handleHTTPError([]int{http.StatusOK}, resp) - if err != nil { - return nil, err - } - - var productServers ScalewayProductsServers - if err = json.Unmarshal(body, &productServers); err != nil { - return nil, err - } - - return &productServers, nil -} diff --git a/vendor/github.com/scaleway/scaleway-cli/pkg/api/cache.go b/vendor/github.com/scaleway/scaleway-cli/pkg/api/cache.go deleted file mode 100644 index 0a57796e9..000000000 --- a/vendor/github.com/scaleway/scaleway-cli/pkg/api/cache.go +++ /dev/null @@ -1,816 +0,0 @@ -// Copyright (C) 2015 Scaleway. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE.md file. - -package api - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "regexp" - "strings" - "sync" - - "github.com/moul/anonuuid" - "github.com/renstrom/fuzzysearch/fuzzy" -) - -const ( - // CacheRegion permits to access at the region field - CacheRegion = iota - // CacheArch permits to access at the arch field - CacheArch - // CacheOwner permits to access at the owner field - CacheOwner - // CacheTitle permits to access at the title field - CacheTitle - // CacheMarketPlaceUUID is used to determine the UUID of local images - CacheMarketPlaceUUID - // CacheMaxfield is used to determine the size of array - CacheMaxfield -) - -// ScalewayCache is used not to query the API to resolve full identifiers -type ScalewayCache struct { - // Images contains names of Scaleway images indexed by identifier - Images map[string][CacheMaxfield]string `json:"images"` - - // Snapshots contains names of Scaleway snapshots indexed by identifier - Snapshots map[string][CacheMaxfield]string `json:"snapshots"` - - // Volumes contains names of Scaleway volumes indexed by identifier - Volumes map[string][CacheMaxfield]string `json:"volumes"` - - // Bootscripts contains names of Scaleway bootscripts indexed by identifier - Bootscripts map[string][CacheMaxfield]string `json:"bootscripts"` - - // Servers contains names of Scaleway servers indexed by identifier - Servers map[string][CacheMaxfield]string `json:"servers"` - - // Path is the path to the cache file - Path string `json:"-"` - - // Modified tells if the cache needs to be overwritten or not - Modified bool `json:"-"` - - // Lock allows ScalewayCache to be used concurrently - Lock sync.Mutex `json:"-"` - - hookSave func() -} - -const ( - // IdentifierUnknown is used when we don't know explicitly the type key of the object (used for nil comparison) - IdentifierUnknown = 1 << iota - // IdentifierServer is the type key of cached server objects - IdentifierServer - // IdentifierImage is the type key of cached image objects - IdentifierImage - // IdentifierSnapshot is the type key of cached snapshot objects - IdentifierSnapshot - // IdentifierBootscript is the type key of cached bootscript objects - IdentifierBootscript - // IdentifierVolume is the type key of cached volume objects - IdentifierVolume -) - -// ScalewayResolverResult is a structure containing human-readable information -// about resolver results. This structure is used to display the user choices. -type ScalewayResolverResult struct { - Identifier string - Type int - Name string - Arch string - Needle string - RankMatch int - Region string -} - -// ScalewayResolverResults is a list of `ScalewayResolverResult` -type ScalewayResolverResults []ScalewayResolverResult - -// NewScalewayResolverResult returns a new ScalewayResolverResult -func NewScalewayResolverResult(Identifier, Name, Arch, Region string, Type int) (ScalewayResolverResult, error) { - if err := anonuuid.IsUUID(Identifier); err != nil { - return ScalewayResolverResult{}, err - } - return ScalewayResolverResult{ - Identifier: Identifier, - Type: Type, - Name: Name, - Arch: Arch, - Region: Region, - }, nil -} - -func (s ScalewayResolverResults) Len() int { - return len(s) -} - -func (s ScalewayResolverResults) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} - -func (s ScalewayResolverResults) Less(i, j int) bool { - return s[i].RankMatch < s[j].RankMatch -} - -// TruncIdentifier returns first 8 characters of an Identifier (UUID) -func (s *ScalewayResolverResult) TruncIdentifier() string { - return s.Identifier[:8] -} - -func identifierTypeName(kind int) string { - switch kind { - case IdentifierServer: - return "Server" - case IdentifierImage: - return "Image" - case IdentifierSnapshot: - return "Snapshot" - case IdentifierVolume: - return "Volume" - case IdentifierBootscript: - return "Bootscript" - } - return "" -} - -// CodeName returns a full resource name with typed prefix -func (s *ScalewayResolverResult) CodeName() string { - name := strings.ToLower(s.Name) - name = regexp.MustCompile(`[^a-z0-9-]`).ReplaceAllString(name, "-") - name = regexp.MustCompile(`--+`).ReplaceAllString(name, "-") - name = strings.Trim(name, "-") - - return fmt.Sprintf("%s:%s", strings.ToLower(identifierTypeName(s.Type)), name) -} - -// FilterByArch deletes the elements which not match with arch -func (s *ScalewayResolverResults) FilterByArch(arch string) { -REDO: - for i := range *s { - if (*s)[i].Arch != arch { - (*s)[i] = (*s)[len(*s)-1] - *s = (*s)[:len(*s)-1] - goto REDO - } - } -} - -// NewScalewayCache loads a per-user cache -func NewScalewayCache(hookSave func()) (*ScalewayCache, error) { - var cache ScalewayCache - - cache.hookSave = hookSave - homeDir := os.Getenv("HOME") // *nix - if homeDir == "" { // Windows - homeDir = os.Getenv("USERPROFILE") - } - if homeDir == "" { - homeDir = "/tmp" - } - cachePath := filepath.Join(homeDir, ".scw-cache.db") - cache.Path = cachePath - _, err := os.Stat(cachePath) - if os.IsNotExist(err) { - cache.Clear() - return &cache, nil - } else if err != nil { - return nil, err - } - file, err := ioutil.ReadFile(cachePath) - if err != nil { - return nil, err - } - err = json.Unmarshal(file, &cache) - if err != nil { - // fix compatibility with older version - if err = os.Remove(cachePath); err != nil { - return nil, err - } - cache.Clear() - return &cache, nil - } - if cache.Images == nil { - cache.Images = make(map[string][CacheMaxfield]string) - } - if cache.Snapshots == nil { - cache.Snapshots = make(map[string][CacheMaxfield]string) - } - if cache.Volumes == nil { - cache.Volumes = make(map[string][CacheMaxfield]string) - } - if cache.Servers == nil { - cache.Servers = make(map[string][CacheMaxfield]string) - } - if cache.Bootscripts == nil { - cache.Bootscripts = make(map[string][CacheMaxfield]string) - } - return &cache, nil -} - -// Clear removes all information from the cache -func (c *ScalewayCache) Clear() { - c.Images = make(map[string][CacheMaxfield]string) - c.Snapshots = make(map[string][CacheMaxfield]string) - c.Volumes = make(map[string][CacheMaxfield]string) - c.Bootscripts = make(map[string][CacheMaxfield]string) - c.Servers = make(map[string][CacheMaxfield]string) - c.Modified = true -} - -// Flush flushes the cache database -func (c *ScalewayCache) Flush() error { - return os.Remove(c.Path) -} - -// Save atomically overwrites the current cache database -func (c *ScalewayCache) Save() error { - c.Lock.Lock() - defer c.Lock.Unlock() - - c.hookSave() - if c.Modified { - file, err := ioutil.TempFile(filepath.Dir(c.Path), filepath.Base(c.Path)) - if err != nil { - return err - } - - if err := json.NewEncoder(file).Encode(c); err != nil { - file.Close() - os.Remove(file.Name()) - return err - } - - file.Close() - if err := os.Rename(file.Name(), c.Path); err != nil { - os.Remove(file.Name()) - return err - } - } - return nil -} - -// ComputeRankMatch fills `ScalewayResolverResult.RankMatch` with its `fuzzy` score -func (s *ScalewayResolverResult) ComputeRankMatch(needle string) { - s.Needle = needle - s.RankMatch = fuzzy.RankMatch(needle, s.Name) -} - -// LookUpImages attempts to return identifiers matching a pattern -func (c *ScalewayCache) LookUpImages(needle string, acceptUUID bool) (ScalewayResolverResults, error) { - c.Lock.Lock() - defer c.Lock.Unlock() - - var res ScalewayResolverResults - var exactMatches ScalewayResolverResults - - if acceptUUID && anonuuid.IsUUID(needle) == nil { - if fields, ok := c.Images[needle]; ok { - entry, err := NewScalewayResolverResult(needle, fields[CacheTitle], fields[CacheArch], fields[CacheRegion], IdentifierImage) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - res = append(res, entry) - } - } - - needle = regexp.MustCompile(`^user/`).ReplaceAllString(needle, "") - // FIXME: if 'user/' is in needle, only watch for a user image - nameRegex := regexp.MustCompile(`(?i)` + regexp.MustCompile(`[_-]`).ReplaceAllString(needle, ".*")) - for identifier, fields := range c.Images { - if fields[CacheTitle] == needle { - entry, err := NewScalewayResolverResult(identifier, fields[CacheTitle], fields[CacheArch], fields[CacheRegion], IdentifierImage) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - exactMatches = append(exactMatches, entry) - } - if strings.HasPrefix(identifier, needle) || nameRegex.MatchString(fields[CacheTitle]) { - entry, err := NewScalewayResolverResult(identifier, fields[CacheTitle], fields[CacheArch], fields[CacheRegion], IdentifierImage) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - res = append(res, entry) - } else if strings.HasPrefix(fields[CacheMarketPlaceUUID], needle) || nameRegex.MatchString(fields[CacheMarketPlaceUUID]) { - entry, err := NewScalewayResolverResult(identifier, fields[CacheTitle], fields[CacheArch], fields[CacheRegion], IdentifierImage) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - res = append(res, entry) - } - } - - if len(exactMatches) == 1 { - return exactMatches, nil - } - - return removeDuplicatesResults(res), nil -} - -// LookUpSnapshots attempts to return identifiers matching a pattern -func (c *ScalewayCache) LookUpSnapshots(needle string, acceptUUID bool) (ScalewayResolverResults, error) { - c.Lock.Lock() - defer c.Lock.Unlock() - - var res ScalewayResolverResults - var exactMatches ScalewayResolverResults - - if acceptUUID && anonuuid.IsUUID(needle) == nil { - if fields, ok := c.Snapshots[needle]; ok { - entry, err := NewScalewayResolverResult(needle, fields[CacheTitle], fields[CacheArch], fields[CacheRegion], IdentifierSnapshot) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - res = append(res, entry) - } - } - - needle = regexp.MustCompile(`^user/`).ReplaceAllString(needle, "") - nameRegex := regexp.MustCompile(`(?i)` + regexp.MustCompile(`[_-]`).ReplaceAllString(needle, ".*")) - for identifier, fields := range c.Snapshots { - if fields[CacheTitle] == needle { - entry, err := NewScalewayResolverResult(identifier, fields[CacheTitle], fields[CacheArch], fields[CacheRegion], IdentifierSnapshot) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - exactMatches = append(exactMatches, entry) - } - if strings.HasPrefix(identifier, needle) || nameRegex.MatchString(fields[CacheTitle]) { - entry, err := NewScalewayResolverResult(identifier, fields[CacheTitle], fields[CacheArch], fields[CacheRegion], IdentifierSnapshot) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - res = append(res, entry) - } - } - - if len(exactMatches) == 1 { - return exactMatches, nil - } - - return removeDuplicatesResults(res), nil -} - -// LookUpVolumes attempts to return identifiers matching a pattern -func (c *ScalewayCache) LookUpVolumes(needle string, acceptUUID bool) (ScalewayResolverResults, error) { - c.Lock.Lock() - defer c.Lock.Unlock() - - var res ScalewayResolverResults - var exactMatches ScalewayResolverResults - - if acceptUUID && anonuuid.IsUUID(needle) == nil { - if fields, ok := c.Volumes[needle]; ok { - entry, err := NewScalewayResolverResult(needle, fields[CacheTitle], fields[CacheArch], fields[CacheRegion], IdentifierVolume) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - res = append(res, entry) - } - } - - nameRegex := regexp.MustCompile(`(?i)` + regexp.MustCompile(`[_-]`).ReplaceAllString(needle, ".*")) - for identifier, fields := range c.Volumes { - if fields[CacheTitle] == needle { - entry, err := NewScalewayResolverResult(identifier, fields[CacheTitle], fields[CacheArch], fields[CacheRegion], IdentifierVolume) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - exactMatches = append(exactMatches, entry) - } - if strings.HasPrefix(identifier, needle) || nameRegex.MatchString(fields[CacheTitle]) { - entry, err := NewScalewayResolverResult(identifier, fields[CacheTitle], fields[CacheArch], fields[CacheRegion], IdentifierVolume) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - res = append(res, entry) - } - } - - if len(exactMatches) == 1 { - return exactMatches, nil - } - - return removeDuplicatesResults(res), nil -} - -// LookUpBootscripts attempts to return identifiers matching a pattern -func (c *ScalewayCache) LookUpBootscripts(needle string, acceptUUID bool) (ScalewayResolverResults, error) { - c.Lock.Lock() - defer c.Lock.Unlock() - - var res ScalewayResolverResults - var exactMatches ScalewayResolverResults - - if acceptUUID && anonuuid.IsUUID(needle) == nil { - if fields, ok := c.Bootscripts[needle]; ok { - entry, err := NewScalewayResolverResult(needle, fields[CacheTitle], fields[CacheArch], fields[CacheRegion], IdentifierBootscript) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - res = append(res, entry) - } - } - - nameRegex := regexp.MustCompile(`(?i)` + regexp.MustCompile(`[_-]`).ReplaceAllString(needle, ".*")) - for identifier, fields := range c.Bootscripts { - if fields[CacheTitle] == needle { - entry, err := NewScalewayResolverResult(identifier, fields[CacheTitle], fields[CacheArch], fields[CacheRegion], IdentifierBootscript) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - exactMatches = append(exactMatches, entry) - } - if strings.HasPrefix(identifier, needle) || nameRegex.MatchString(fields[CacheTitle]) { - entry, err := NewScalewayResolverResult(identifier, fields[CacheTitle], fields[CacheArch], fields[CacheRegion], IdentifierBootscript) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - res = append(res, entry) - } - } - - if len(exactMatches) == 1 { - return exactMatches, nil - } - - return removeDuplicatesResults(res), nil -} - -// LookUpServers attempts to return identifiers matching a pattern -func (c *ScalewayCache) LookUpServers(needle string, acceptUUID bool) (ScalewayResolverResults, error) { - c.Lock.Lock() - defer c.Lock.Unlock() - - var res ScalewayResolverResults - var exactMatches ScalewayResolverResults - - if acceptUUID && anonuuid.IsUUID(needle) == nil { - if fields, ok := c.Servers[needle]; ok { - entry, err := NewScalewayResolverResult(needle, fields[CacheTitle], fields[CacheArch], fields[CacheRegion], IdentifierServer) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - res = append(res, entry) - } - } - - nameRegex := regexp.MustCompile(`(?i)` + regexp.MustCompile(`[_-]`).ReplaceAllString(needle, ".*")) - for identifier, fields := range c.Servers { - if fields[CacheTitle] == needle { - entry, err := NewScalewayResolverResult(identifier, fields[CacheTitle], fields[CacheArch], fields[CacheRegion], IdentifierServer) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - exactMatches = append(exactMatches, entry) - } - if strings.HasPrefix(identifier, needle) || nameRegex.MatchString(fields[CacheTitle]) { - entry, err := NewScalewayResolverResult(identifier, fields[CacheTitle], fields[CacheArch], fields[CacheRegion], IdentifierServer) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - res = append(res, entry) - } - } - - if len(exactMatches) == 1 { - return exactMatches, nil - } - - return removeDuplicatesResults(res), nil -} - -// removeDuplicatesResults transforms an array into a unique array -func removeDuplicatesResults(elements ScalewayResolverResults) ScalewayResolverResults { - encountered := map[string]ScalewayResolverResult{} - - // Create a map of all unique elements. - for v := range elements { - encountered[elements[v].Identifier] = elements[v] - } - - // Place all keys from the map into a slice. - results := ScalewayResolverResults{} - for _, result := range encountered { - results = append(results, result) - } - return results -} - -// parseNeedle parses a user needle and try to extract a forced object type -// i.e: -// - server:blah-blah -> kind=server, needle=blah-blah -// - blah-blah -> kind="", needle=blah-blah -// - not-existing-type:blah-blah -func parseNeedle(input string) (identifierType int, needle string) { - parts := strings.Split(input, ":") - if len(parts) == 2 { - switch parts[0] { - case "server": - return IdentifierServer, parts[1] - case "image": - return IdentifierImage, parts[1] - case "snapshot": - return IdentifierSnapshot, parts[1] - case "bootscript": - return IdentifierBootscript, parts[1] - case "volume": - return IdentifierVolume, parts[1] - } - } - return IdentifierUnknown, input -} - -// LookUpIdentifiers attempts to return identifiers matching a pattern -func (c *ScalewayCache) LookUpIdentifiers(needle string) (ScalewayResolverResults, error) { - results := ScalewayResolverResults{} - - identifierType, needle := parseNeedle(needle) - - if identifierType&(IdentifierUnknown|IdentifierServer) > 0 { - servers, err := c.LookUpServers(needle, false) - if err != nil { - return ScalewayResolverResults{}, err - } - for _, result := range servers { - entry, err := NewScalewayResolverResult(result.Identifier, result.Name, result.Arch, result.Region, IdentifierServer) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - results = append(results, entry) - } - } - - if identifierType&(IdentifierUnknown|IdentifierImage) > 0 { - images, err := c.LookUpImages(needle, false) - if err != nil { - return ScalewayResolverResults{}, err - } - for _, result := range images { - entry, err := NewScalewayResolverResult(result.Identifier, result.Name, result.Arch, result.Region, IdentifierImage) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - results = append(results, entry) - } - } - - if identifierType&(IdentifierUnknown|IdentifierSnapshot) > 0 { - snapshots, err := c.LookUpSnapshots(needle, false) - if err != nil { - return ScalewayResolverResults{}, err - } - for _, result := range snapshots { - entry, err := NewScalewayResolverResult(result.Identifier, result.Name, result.Arch, result.Region, IdentifierSnapshot) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - results = append(results, entry) - } - } - - if identifierType&(IdentifierUnknown|IdentifierVolume) > 0 { - volumes, err := c.LookUpVolumes(needle, false) - if err != nil { - return ScalewayResolverResults{}, err - } - for _, result := range volumes { - entry, err := NewScalewayResolverResult(result.Identifier, result.Name, result.Arch, result.Region, IdentifierVolume) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - results = append(results, entry) - } - } - - if identifierType&(IdentifierUnknown|IdentifierBootscript) > 0 { - bootscripts, err := c.LookUpBootscripts(needle, false) - if err != nil { - return ScalewayResolverResults{}, err - } - for _, result := range bootscripts { - entry, err := NewScalewayResolverResult(result.Identifier, result.Name, result.Arch, result.Region, IdentifierBootscript) - if err != nil { - return ScalewayResolverResults{}, err - } - entry.ComputeRankMatch(needle) - results = append(results, entry) - } - } - return results, nil -} - -// InsertServer registers a server in the cache -func (c *ScalewayCache) InsertServer(identifier, region, arch, owner, name string) { - c.Lock.Lock() - defer c.Lock.Unlock() - - fields, exists := c.Servers[identifier] - if !exists || fields[CacheTitle] != name { - c.Servers[identifier] = [CacheMaxfield]string{region, arch, owner, name} - c.Modified = true - } -} - -// RemoveServer removes a server from the cache -func (c *ScalewayCache) RemoveServer(identifier string) { - c.Lock.Lock() - defer c.Lock.Unlock() - - delete(c.Servers, identifier) - c.Modified = true -} - -// ClearServers removes all servers from the cache -func (c *ScalewayCache) ClearServers() { - c.Lock.Lock() - defer c.Lock.Unlock() - - c.Servers = make(map[string][CacheMaxfield]string) - c.Modified = true -} - -// InsertImage registers an image in the cache -func (c *ScalewayCache) InsertImage(identifier, region, arch, owner, name, marketPlaceUUID string) { - c.Lock.Lock() - defer c.Lock.Unlock() - - fields, exists := c.Images[identifier] - if !exists || fields[CacheTitle] != name { - c.Images[identifier] = [CacheMaxfield]string{region, arch, owner, name, marketPlaceUUID} - c.Modified = true - } -} - -// RemoveImage removes a server from the cache -func (c *ScalewayCache) RemoveImage(identifier string) { - c.Lock.Lock() - defer c.Lock.Unlock() - - delete(c.Images, identifier) - c.Modified = true -} - -// ClearImages removes all images from the cache -func (c *ScalewayCache) ClearImages() { - c.Lock.Lock() - defer c.Lock.Unlock() - - c.Images = make(map[string][CacheMaxfield]string) - c.Modified = true -} - -// InsertSnapshot registers an snapshot in the cache -func (c *ScalewayCache) InsertSnapshot(identifier, region, arch, owner, name string) { - c.Lock.Lock() - defer c.Lock.Unlock() - - fields, exists := c.Snapshots[identifier] - if !exists || fields[CacheTitle] != name { - c.Snapshots[identifier] = [CacheMaxfield]string{region, arch, owner, name} - c.Modified = true - } -} - -// RemoveSnapshot removes a server from the cache -func (c *ScalewayCache) RemoveSnapshot(identifier string) { - c.Lock.Lock() - defer c.Lock.Unlock() - - delete(c.Snapshots, identifier) - c.Modified = true -} - -// ClearSnapshots removes all snapshots from the cache -func (c *ScalewayCache) ClearSnapshots() { - c.Lock.Lock() - defer c.Lock.Unlock() - - c.Snapshots = make(map[string][CacheMaxfield]string) - c.Modified = true -} - -// InsertVolume registers an volume in the cache -func (c *ScalewayCache) InsertVolume(identifier, region, arch, owner, name string) { - c.Lock.Lock() - defer c.Lock.Unlock() - - fields, exists := c.Volumes[identifier] - if !exists || fields[CacheTitle] != name { - c.Volumes[identifier] = [CacheMaxfield]string{region, arch, owner, name} - c.Modified = true - } -} - -// RemoveVolume removes a server from the cache -func (c *ScalewayCache) RemoveVolume(identifier string) { - c.Lock.Lock() - defer c.Lock.Unlock() - - delete(c.Volumes, identifier) - c.Modified = true -} - -// ClearVolumes removes all volumes from the cache -func (c *ScalewayCache) ClearVolumes() { - c.Lock.Lock() - defer c.Lock.Unlock() - - c.Volumes = make(map[string][CacheMaxfield]string) - c.Modified = true -} - -// InsertBootscript registers an bootscript in the cache -func (c *ScalewayCache) InsertBootscript(identifier, region, arch, owner, name string) { - c.Lock.Lock() - defer c.Lock.Unlock() - - fields, exists := c.Bootscripts[identifier] - if !exists || fields[CacheTitle] != name { - c.Bootscripts[identifier] = [CacheMaxfield]string{region, arch, owner, name} - c.Modified = true - } -} - -// RemoveBootscript removes a bootscript from the cache -func (c *ScalewayCache) RemoveBootscript(identifier string) { - c.Lock.Lock() - defer c.Lock.Unlock() - - delete(c.Bootscripts, identifier) - c.Modified = true -} - -// ClearBootscripts removes all bootscripts from the cache -func (c *ScalewayCache) ClearBootscripts() { - c.Lock.Lock() - defer c.Lock.Unlock() - - c.Bootscripts = make(map[string][CacheMaxfield]string) - c.Modified = true -} - -// GetNbServers returns the number of servers in the cache -func (c *ScalewayCache) GetNbServers() int { - c.Lock.Lock() - defer c.Lock.Unlock() - - return len(c.Servers) -} - -// GetNbImages returns the number of images in the cache -func (c *ScalewayCache) GetNbImages() int { - c.Lock.Lock() - defer c.Lock.Unlock() - - return len(c.Images) -} - -// GetNbSnapshots returns the number of snapshots in the cache -func (c *ScalewayCache) GetNbSnapshots() int { - c.Lock.Lock() - defer c.Lock.Unlock() - - return len(c.Snapshots) -} - -// GetNbVolumes returns the number of volumes in the cache -func (c *ScalewayCache) GetNbVolumes() int { - c.Lock.Lock() - defer c.Lock.Unlock() - - return len(c.Volumes) -} - -// GetNbBootscripts returns the number of bootscripts in the cache -func (c *ScalewayCache) GetNbBootscripts() int { - c.Lock.Lock() - defer c.Lock.Unlock() - - return len(c.Bootscripts) -} diff --git a/vendor/github.com/scaleway/scaleway-cli/pkg/api/helpers.go b/vendor/github.com/scaleway/scaleway-cli/pkg/api/helpers.go deleted file mode 100644 index d0e33f932..000000000 --- a/vendor/github.com/scaleway/scaleway-cli/pkg/api/helpers.go +++ /dev/null @@ -1,725 +0,0 @@ -// Copyright (C) 2015 Scaleway. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE.md file. - -package api - -import ( - "errors" - "fmt" - "math" - "os" - "sort" - "strings" - "sync" - "time" - - "github.com/docker/docker/pkg/namesgenerator" - "github.com/dustin/go-humanize" - "github.com/moul/anonuuid" - "github.com/scaleway/scaleway-cli/pkg/utils" - "github.com/sirupsen/logrus" - log "github.com/sirupsen/logrus" -) - -// ScalewayResolvedIdentifier represents a list of matching identifier for a specifier pattern -type ScalewayResolvedIdentifier struct { - // Identifiers holds matching identifiers - Identifiers ScalewayResolverResults - - // Needle is the criteria used to lookup identifiers - Needle string -} - -// ScalewayImageInterface is an interface to multiple Scaleway items -type ScalewayImageInterface struct { - CreationDate time.Time - Identifier string - Name string - Tag string - VirtualSize uint64 - Public bool - Type string - Organization string - Archs []string - Region []string -} - -// ResolveGateway tries to resolve a server public ip address, else returns the input string, i.e. IPv4, hostname -func ResolveGateway(api *ScalewayAPI, gateway string) (string, error) { - if gateway == "" { - return "", nil - } - - // Parses optional type prefix, i.e: "server:name" -> "name" - _, gateway = parseNeedle(gateway) - - servers, err := api.ResolveServer(gateway) - if err != nil { - return "", err - } - - if len(servers) == 0 { - return gateway, nil - } - - if len(servers) > 1 { - return "", showResolverResults(gateway, servers) - } - - // if len(servers) == 1 { - server, err := api.GetServer(servers[0].Identifier) - if err != nil { - return "", err - } - return server.PublicAddress.IP, nil -} - -// CreateVolumeFromHumanSize creates a volume on the API with a human readable size -func CreateVolumeFromHumanSize(api *ScalewayAPI, size string) (*string, error) { - bytes, err := humanize.ParseBytes(size) - if err != nil { - return nil, err - } - - var newVolume ScalewayVolumeDefinition - newVolume.Name = size - newVolume.Size = bytes - newVolume.Type = "l_ssd" - - volumeID, err := api.PostVolume(newVolume) - if err != nil { - return nil, err - } - - return &volumeID, nil -} - -// VolumesFromSize returns a string of standard sized volumes from a given size -func VolumesFromSize(size uint64) string { - const DefaultVolumeSize float64 = 50000000000 - StdVolumeSizes := []struct { - kind string - capacity float64 - }{ - {"150G", 150000000000}, - {"100G", 100000000000}, - {"50G", 50000000000}, - } - - RequiredSize := float64(size) - DefaultVolumeSize - Volumes := "" - for _, v := range StdVolumeSizes { - q := RequiredSize / v.capacity - r := math.Mod(RequiredSize, v.capacity) - RequiredSize = r - - if q > 0 { - Volumes += strings.Repeat(v.kind+" ", int(q)) - } - if r == 0 { - break - } - } - - return strings.TrimSpace(Volumes) -} - -// fillIdentifierCache fills the cache by fetching from the API -func fillIdentifierCache(api *ScalewayAPI, identifierType int) { - log.Debugf("Filling the cache") - var wg sync.WaitGroup - wg.Add(5) - go func() { - if identifierType&(IdentifierUnknown|IdentifierServer) > 0 { - api.GetServers(true, 0) - } - wg.Done() - }() - go func() { - if identifierType&(IdentifierUnknown|IdentifierImage) > 0 { - api.GetImages() - } - wg.Done() - }() - go func() { - if identifierType&(IdentifierUnknown|IdentifierSnapshot) > 0 { - api.GetSnapshots() - } - wg.Done() - }() - go func() { - if identifierType&(IdentifierUnknown|IdentifierVolume) > 0 { - api.GetVolumes() - } - wg.Done() - }() - go func() { - if identifierType&(IdentifierUnknown|IdentifierBootscript) > 0 { - api.GetBootscripts() - } - wg.Done() - }() - wg.Wait() -} - -// GetIdentifier returns a an identifier if the resolved needles only match one element, else, it exists the program -func GetIdentifier(api *ScalewayAPI, needle string) (*ScalewayResolverResult, error) { - idents, err := ResolveIdentifier(api, needle) - if err != nil { - return nil, err - } - - if len(idents) == 1 { - return &idents[0], nil - } - if len(idents) == 0 { - return nil, fmt.Errorf("No such identifier: %s", needle) - } - - sort.Sort(idents) - for _, identifier := range idents { - // FIXME: also print the name - fmt.Fprintf(os.Stderr, "- %s\n", identifier.Identifier) - } - return nil, fmt.Errorf("Too many candidates for %s (%d)", needle, len(idents)) -} - -// ResolveIdentifier resolves needle provided by the user -func ResolveIdentifier(api *ScalewayAPI, needle string) (ScalewayResolverResults, error) { - idents, err := api.Cache.LookUpIdentifiers(needle) - if err != nil { - return idents, err - } - if len(idents) > 0 { - return idents, nil - } - - identifierType, _ := parseNeedle(needle) - fillIdentifierCache(api, identifierType) - - return api.Cache.LookUpIdentifiers(needle) -} - -// ResolveIdentifiers resolves needles provided by the user -func ResolveIdentifiers(api *ScalewayAPI, needles []string, out chan ScalewayResolvedIdentifier) { - // first attempt, only lookup from the cache - var unresolved []string - for _, needle := range needles { - idents, err := api.Cache.LookUpIdentifiers(needle) - if err != nil { - api.Logger.Fatalf("%s", err) - } - if len(idents) == 0 { - unresolved = append(unresolved, needle) - } else { - out <- ScalewayResolvedIdentifier{ - Identifiers: idents, - Needle: needle, - } - } - } - // fill the cache by fetching from the API and resolve missing identifiers - if len(unresolved) > 0 { - // compute identifierType: - // if identifierType is the same for every unresolved needle, - // we use it directly, else, we choose IdentifierUnknown to - // fulfill every types of cache - identifierType, _ := parseNeedle(unresolved[0]) - for _, needle := range unresolved { - newIdentifierType, _ := parseNeedle(needle) - if identifierType != newIdentifierType { - identifierType = IdentifierUnknown - break - } - } - - // fill all the cache - fillIdentifierCache(api, identifierType) - - // lookup again in the cache - for _, needle := range unresolved { - idents, err := api.Cache.LookUpIdentifiers(needle) - if err != nil { - api.Logger.Fatalf("%s", err) - } - out <- ScalewayResolvedIdentifier{ - Identifiers: idents, - Needle: needle, - } - } - } - - close(out) -} - -// InspectIdentifierResult is returned by `InspectIdentifiers` and contains the inspected `Object` with its `Type` -type InspectIdentifierResult struct { - Type int - Object interface{} -} - -// InspectIdentifiers inspects identifiers concurrently -func InspectIdentifiers(api *ScalewayAPI, ci chan ScalewayResolvedIdentifier, cj chan InspectIdentifierResult, arch string) { - var wg sync.WaitGroup - for { - idents, ok := <-ci - if !ok { - break - } - idents.Identifiers = FilterImagesByArch(idents.Identifiers, arch) - idents.Identifiers = FilterImagesByRegion(idents.Identifiers, api.Region) - if len(idents.Identifiers) != 1 { - if len(idents.Identifiers) == 0 { - log.Errorf("Unable to resolve identifier %s", idents.Needle) - } else { - logrus.Fatal(showResolverResults(idents.Needle, idents.Identifiers)) - } - } else { - ident := idents.Identifiers[0] - wg.Add(1) - go func() { - var obj interface{} - var err error - - switch ident.Type { - case IdentifierServer: - obj, err = api.GetServer(ident.Identifier) - case IdentifierImage: - obj, err = api.GetImage(ident.Identifier) - case IdentifierSnapshot: - obj, err = api.GetSnapshot(ident.Identifier) - case IdentifierVolume: - obj, err = api.GetVolume(ident.Identifier) - case IdentifierBootscript: - obj, err = api.GetBootscript(ident.Identifier) - } - if err == nil && obj != nil { - cj <- InspectIdentifierResult{ - Type: ident.Type, - Object: obj, - } - } - wg.Done() - }() - } - } - wg.Wait() - close(cj) -} - -// ConfigCreateServer represents the options sent to CreateServer and defining a server -type ConfigCreateServer struct { - ImageName string - Name string - Bootscript string - Env string - AdditionalVolumes string - IP string - CommercialType string - DynamicIPRequired bool - EnableIPV6 bool - BootType string -} - -// Return offer from any of the product name or alternate names -func OfferNameFromName(name string, products *ScalewayProductsServers) (*ProductServer, error) { - offer, ok := products.Servers[name] - if ok { - return &offer, nil - } - - for _, v := range products.Servers { - for _, alt := range v.AltNames { - alt := strings.ToUpper(alt) - if alt == name { - return &v, nil - } - } - } - - return nil, fmt.Errorf("Unknow commercial type: %v", name) -} - -// CreateServer creates a server using API based on typical server fields -func CreateServer(api *ScalewayAPI, c *ConfigCreateServer) (string, error) { - commercialType := os.Getenv("SCW_COMMERCIAL_TYPE") - if commercialType == "" { - commercialType = c.CommercialType - } - if len(commercialType) < 2 { - return "", errors.New("Invalid commercial type") - } - - if c.BootType != "local" && c.BootType != "bootscript" { - return "", errors.New("Invalid boot type") - } - - if c.Name == "" { - c.Name = strings.Replace(namesgenerator.GetRandomName(0), "_", "-", -1) - } - - var server ScalewayServerDefinition - - server.CommercialType = strings.ToUpper(commercialType) - server.Volumes = make(map[string]string) - server.DynamicIPRequired = &c.DynamicIPRequired - server.EnableIPV6 = c.EnableIPV6 - server.BootType = c.BootType - if commercialType == "" { - return "", errors.New("You need to specify a commercial-type") - } - if c.IP != "" { - if anonuuid.IsUUID(c.IP) == nil { - server.PublicIP = c.IP - } else { - ips, err := api.GetIPS() - if err != nil { - return "", err - } - for _, ip := range ips.IPS { - if ip.Address == c.IP { - server.PublicIP = ip.ID - break - } - } - if server.PublicIP == "" { - return "", fmt.Errorf("IP address %v not found", c.IP) - } - } - } - server.Tags = []string{} - if c.Env != "" { - server.Tags = strings.Split(c.Env, " ") - } - - products, err := api.GetProductsServers() - if err != nil { - return "", fmt.Errorf("Unable to fetch products list from the Scaleway API: %v", err) - } - offer, err := OfferNameFromName(server.CommercialType, products) - if err != nil { - return "", fmt.Errorf("Unknow commercial type %v: %v", server.CommercialType, err) - } - if offer.VolumesConstraint.MinSize > 0 && c.AdditionalVolumes == "" { - c.AdditionalVolumes = VolumesFromSize(offer.VolumesConstraint.MinSize) - log.Debugf("%s needs at least %s. Automatically creates the following volumes: %s", - server.CommercialType, humanize.Bytes(offer.VolumesConstraint.MinSize), c.AdditionalVolumes) - } - if c.AdditionalVolumes != "" { - volumes := strings.Split(c.AdditionalVolumes, " ") - for i := range volumes { - volumeID, err := CreateVolumeFromHumanSize(api, volumes[i]) - if err != nil { - return "", err - } - - volumeIDx := fmt.Sprintf("%d", i+1) - server.Volumes[volumeIDx] = *volumeID - } - } - - arch := os.Getenv("SCW_TARGET_ARCH") - if arch == "" { - arch = offer.Arch - } - imageIdentifier := &ScalewayImageIdentifier{ - Arch: arch, - } - server.Name = c.Name - inheritingVolume := false - _, err = humanize.ParseBytes(c.ImageName) - if err == nil { - // Create a new root volume - volumeID, errCreateVol := CreateVolumeFromHumanSize(api, c.ImageName) - if errCreateVol != nil { - return "", errCreateVol - } - server.Volumes["0"] = *volumeID - } else { - // Use an existing image - inheritingVolume = true - if anonuuid.IsUUID(c.ImageName) == nil { - server.Image = &c.ImageName - } else { - imageIdentifier, err = api.GetImageID(c.ImageName, arch) - if err != nil { - return "", err - } - if imageIdentifier.Identifier != "" { - server.Image = &imageIdentifier.Identifier - } else { - snapshotID, errGetSnapID := api.GetSnapshotID(c.ImageName) - if errGetSnapID != nil { - return "", errGetSnapID - } - snapshot, errGetSnap := api.GetSnapshot(snapshotID) - if errGetSnap != nil { - return "", errGetSnap - } - if snapshot.BaseVolume.Identifier == "" { - return "", fmt.Errorf("snapshot %v does not have base volume", snapshot.Name) - } - server.Volumes["0"] = snapshot.BaseVolume.Identifier - } - } - } - - if c.Bootscript != "" { - bootscript := "" - - if anonuuid.IsUUID(c.Bootscript) == nil { - bootscript = c.Bootscript - } else { - var errGetBootScript error - - bootscript, errGetBootScript = api.GetBootscriptID(c.Bootscript, imageIdentifier.Arch) - if errGetBootScript != nil { - return "", errGetBootScript - } - } - server.Bootscript = &bootscript - } - serverID, err := api.PostServer(server) - if err != nil { - return "", err - } - - // For inherited volumes, we prefix the name with server hostname - if inheritingVolume { - createdServer, err := api.GetServer(serverID) - if err != nil { - return "", err - } - currentVolume := createdServer.Volumes["0"] - - var volumePayload ScalewayVolumePutDefinition - newName := fmt.Sprintf("%s-%s", createdServer.Hostname, currentVolume.Name) - volumePayload.Name = &newName - volumePayload.CreationDate = ¤tVolume.CreationDate - volumePayload.Organization = ¤tVolume.Organization - volumePayload.Server.Identifier = ¤tVolume.Server.Identifier - volumePayload.Server.Name = ¤tVolume.Server.Name - volumePayload.Identifier = ¤tVolume.Identifier - volumePayload.Size = ¤tVolume.Size - volumePayload.ModificationDate = ¤tVolume.ModificationDate - volumePayload.ExportURI = ¤tVolume.ExportURI - volumePayload.VolumeType = ¤tVolume.VolumeType - - err = api.PutVolume(currentVolume.Identifier, volumePayload) - if err != nil { - return "", err - } - } - - return serverID, nil -} - -// WaitForServerState asks API in a loop until a server matches a wanted state -func WaitForServerState(api *ScalewayAPI, serverID string, targetState string) (*ScalewayServer, error) { - var server *ScalewayServer - var err error - - var currentState string - - for { - server, err = api.GetServer(serverID) - if err != nil { - return nil, err - } - if currentState != server.State { - log.Infof("Server changed state to '%s'", server.State) - currentState = server.State - } - if server.State == targetState { - break - } - time.Sleep(1 * time.Second) - } - - return server, nil -} - -// WaitForServerReady wait for a server state to be running, then wait for the SSH port to be available -func WaitForServerReady(api *ScalewayAPI, serverID, gateway string) (*ScalewayServer, error) { - promise := make(chan bool) - var server *ScalewayServer - var err error - var currentState string - - go func() { - defer close(promise) - - for { - server, err = api.GetServer(serverID) - if err != nil { - promise <- false - return - } - if currentState != server.State { - log.Infof("Server changed state to '%s'", server.State) - currentState = server.State - } - if server.State == "running" { - break - } - if server.State == "stopped" { - err = fmt.Errorf("The server has been stopped") - promise <- false - return - } - time.Sleep(1 * time.Second) - } - - if gateway == "" { - ip := server.PublicAddress.IP - if ip == "" && server.EnableIPV6 { - ip = fmt.Sprintf("[%s]", server.IPV6.Address) - } - dest := fmt.Sprintf("%s:22", ip) - log.Debugf("Waiting for server SSH port %s", dest) - err = utils.WaitForTCPPortOpen(dest) - if err != nil { - promise <- false - return - } - } else { - dest := fmt.Sprintf("%s:22", gateway) - log.Debugf("Waiting for server SSH port %s", dest) - err = utils.WaitForTCPPortOpen(dest) - if err != nil { - promise <- false - return - } - log.Debugf("Check for SSH port through the gateway: %s", server.PrivateIP) - timeout := time.Tick(120 * time.Second) - for { - select { - case <-timeout: - err = fmt.Errorf("Timeout: unable to ping %s", server.PrivateIP) - goto OUT - default: - if utils.SSHExec("", server.PrivateIP, "root", 22, []string{ - "nc", - "-z", - "-w", - "1", - server.PrivateIP, - "22", - }, false, gateway, false) == nil { - goto OUT - } - time.Sleep(2 * time.Second) - } - } - OUT: - if err != nil { - logrus.Info(err) - err = nil - } - } - promise <- true - }() - - loop := 0 - for { - select { - case done := <-promise: - utils.LogQuiet("\r \r") - if !done { - return nil, err - } - return server, nil - case <-time.After(time.Millisecond * 100): - utils.LogQuiet(fmt.Sprintf("\r%c\r", "-\\|/"[loop%4])) - loop = loop + 1 - if loop == 5 { - loop = 0 - } - } - } -} - -// WaitForServerStopped wait for a server state to be stopped -func WaitForServerStopped(api *ScalewayAPI, serverID string) (*ScalewayServer, error) { - server, err := WaitForServerState(api, serverID, "stopped") - if err != nil { - return nil, err - } - return server, nil -} - -// ByCreationDate sorts images by CreationDate field -type ByCreationDate []ScalewayImageInterface - -func (a ByCreationDate) Len() int { return len(a) } -func (a ByCreationDate) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a ByCreationDate) Less(i, j int) bool { return a[j].CreationDate.Before(a[i].CreationDate) } - -// StartServer start a server based on its needle, can optionaly block while server is booting -func StartServer(api *ScalewayAPI, needle string, wait bool) error { - server, err := api.GetServerID(needle) - if err != nil { - return err - } - - if err = api.PostServerAction(server, "poweron"); err != nil { - return err - } - - if wait { - _, err = WaitForServerReady(api, server, "") - if err != nil { - return fmt.Errorf("failed to wait for server %s to be ready, %v", needle, err) - } - } - return nil -} - -// StartServerOnce wraps StartServer for golang channel -func StartServerOnce(api *ScalewayAPI, needle string, wait bool, successChan chan string, errChan chan error) { - err := StartServer(api, needle, wait) - - if err != nil { - errChan <- err - return - } - successChan <- needle -} - -// DeleteServerForce tries to delete a server using multiple ways -func (a *ScalewayAPI) DeleteServerForce(serverID string) error { - // FIXME: also delete attached volumes and ip address - // FIXME: call delete and stop -t in parallel to speed up process - err := a.DeleteServer(serverID) - if err == nil { - logrus.Infof("Server '%s' successfully deleted", serverID) - return nil - } - - err = a.PostServerAction(serverID, "terminate") - if err == nil { - logrus.Infof("Server '%s' successfully terminated", serverID) - return nil - } - - // FIXME: retry in a loop until timeout or Control+C - logrus.Errorf("Failed to delete server %s", serverID) - logrus.Errorf("Try to run 'scw rm -f %s' later", serverID) - return err -} - -// GetSSHFingerprintFromServer returns an array which containts ssh-host-fingerprints -func (a *ScalewayAPI) GetSSHFingerprintFromServer(serverID string) []string { - ret := []string{} - - if value, err := a.GetUserdata(serverID, "ssh-host-fingerprints", false); err == nil { - PublicKeys := strings.Split(string(*value), "\n") - for i := range PublicKeys { - if fingerprint, err := utils.SSHGetFingerprint([]byte(PublicKeys[i])); err == nil { - ret = append(ret, fingerprint) - } - } - } - return ret -} diff --git a/vendor/github.com/scaleway/scaleway-cli/pkg/api/logger.go b/vendor/github.com/scaleway/scaleway-cli/pkg/api/logger.go deleted file mode 100644 index 58ad93716..000000000 --- a/vendor/github.com/scaleway/scaleway-cli/pkg/api/logger.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (C) 2015 Scaleway. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE.md file. - -package api - -import ( - "fmt" - "log" - "net/http" - "os" -) - -// Logger handles logging concerns for the Scaleway API SDK -type Logger interface { - LogHTTP(*http.Request) - Fatalf(format string, v ...interface{}) - Debugf(format string, v ...interface{}) - Infof(format string, v ...interface{}) - Warnf(format string, v ...interface{}) -} - -// NewDefaultLogger returns a logger which is configured for stdout -func NewDefaultLogger() Logger { - return &defaultLogger{ - Logger: log.New(os.Stdout, "", log.LstdFlags), - } -} - -type defaultLogger struct { - *log.Logger -} - -func (l *defaultLogger) LogHTTP(r *http.Request) { - l.Printf("%s %s\n", r.Method, r.URL.RawPath) -} - -func (l *defaultLogger) Fatalf(format string, v ...interface{}) { - l.Printf("[FATAL] %s\n", fmt.Sprintf(format, v)) - os.Exit(1) -} - -func (l *defaultLogger) Debugf(format string, v ...interface{}) { - l.Printf("[DEBUG] %s\n", fmt.Sprintf(format, v)) -} - -func (l *defaultLogger) Infof(format string, v ...interface{}) { - l.Printf("[INFO ] %s\n", fmt.Sprintf(format, v)) -} - -func (l *defaultLogger) Warnf(format string, v ...interface{}) { - l.Printf("[WARN ] %s\n", fmt.Sprintf(format, v)) -} - -type disableLogger struct { -} - -// NewDisableLogger returns a logger which is configured to do nothing -func NewDisableLogger() Logger { - return &disableLogger{} -} - -func (d *disableLogger) LogHTTP(r *http.Request) { -} - -func (d *disableLogger) Fatalf(format string, v ...interface{}) { - panic(fmt.Sprintf(format, v)) -} - -func (d *disableLogger) Debugf(format string, v ...interface{}) { -} - -func (d *disableLogger) Infof(format string, v ...interface{}) { -} - -func (d *disableLogger) Warnf(format string, v ...interface{}) { -} diff --git a/vendor/github.com/scaleway/scaleway-cli/pkg/sshcommand/sshcommand.go b/vendor/github.com/scaleway/scaleway-cli/pkg/sshcommand/sshcommand.go deleted file mode 100644 index 7852ca0be..000000000 --- a/vendor/github.com/scaleway/scaleway-cli/pkg/sshcommand/sshcommand.go +++ /dev/null @@ -1,122 +0,0 @@ -package sshcommand - -import ( - "fmt" - "runtime" - "strings" -) - -// Command contains settings to build a ssh command -type Command struct { - Host string - User string - Port int - SSHOptions []string - Gateway *Command - Command []string - Debug bool - NoEscapeCommand bool - SkipHostKeyChecking bool - Quiet bool - AllocateTTY bool - EnableSSHKeyForwarding bool - - isGateway bool -} - -// New returns a minimal Command -func New(host string) *Command { - return &Command{ - Host: host, - } -} - -func (c *Command) applyDefaults() { - if strings.Contains(c.Host, "@") { - parts := strings.Split(c.Host, "@") - c.User = parts[0] - c.Host = parts[1] - } - - if c.Port == 0 { - c.Port = 22 - } - - if c.isGateway { - c.SSHOptions = []string{"-W", "%h:%p"} - } -} - -// Slice returns an execve compatible slice of arguments -func (c *Command) Slice() []string { - c.applyDefaults() - - slice := []string{"ssh"} - - if c.EnableSSHKeyForwarding { - slice = append(slice, "-A") - } - - if c.Quiet { - slice = append(slice, "-q") - } - - if c.SkipHostKeyChecking { - slice = append(slice, "-o", "UserKnownHostsFile=/dev/null", "-o", "StrictHostKeyChecking=no") - } - - if len(c.SSHOptions) > 0 { - slice = append(slice, c.SSHOptions...) - } - - if c.Gateway != nil { - c.Gateway.isGateway = true - slice = append(slice, "-o", "ProxyCommand="+c.Gateway.String()) - } - - if c.User != "" { - slice = append(slice, "-l", c.User) - } - - slice = append(slice, c.Host) - - if c.AllocateTTY { - slice = append(slice, "-t", "-t") - } - - slice = append(slice, "-p", fmt.Sprintf("%d", c.Port)) - if len(c.Command) > 0 { - slice = append(slice, "--", "/bin/sh", "-e") - if c.Debug { - slice = append(slice, "-x") - } - slice = append(slice, "-c") - - var escapedCommand []string - if c.NoEscapeCommand { - escapedCommand = c.Command - } else { - escapedCommand = []string{} - for _, part := range c.Command { - escapedCommand = append(escapedCommand, fmt.Sprintf("%q", part)) - } - } - slice = append(slice, fmt.Sprintf("%q", strings.Join(escapedCommand, " "))) - } - if runtime.GOOS == "windows" { - slice[len(slice)-1] = slice[len(slice)-1] + " " // Why ? - } - return slice -} - -// String returns a copy-pasteable command, useful for debugging -func (c *Command) String() string { - slice := c.Slice() - for i := range slice { - quoted := fmt.Sprintf("%q", slice[i]) - if strings.Contains(slice[i], " ") || len(quoted) != len(slice[i])+2 { - slice[i] = quoted - } - } - return strings.Join(slice, " ") -} diff --git a/vendor/github.com/scaleway/scaleway-cli/pkg/utils/quiet.go b/vendor/github.com/scaleway/scaleway-cli/pkg/utils/quiet.go deleted file mode 100644 index 775918d8d..000000000 --- a/vendor/github.com/scaleway/scaleway-cli/pkg/utils/quiet.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (C) 2015 Scaleway. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE.md file. - -// Package utils contains logquiet -package utils - -import ( - "fmt" - "os" -) - -// LogQuietStruct is a struct to store information about quiet state -type LogQuietStruct struct { - quiet bool -} - -var instanceQuiet LogQuietStruct - -// Quiet enable or disable quiet -func Quiet(option bool) { - instanceQuiet.quiet = option -} - -// LogQuiet Displays info if quiet is activated -func LogQuiet(str string) { - if !instanceQuiet.quiet { - fmt.Fprintf(os.Stderr, "%s", str) - } -} diff --git a/vendor/github.com/scaleway/scaleway-cli/pkg/utils/utils.go b/vendor/github.com/scaleway/scaleway-cli/pkg/utils/utils.go deleted file mode 100644 index 126d9c834..000000000 --- a/vendor/github.com/scaleway/scaleway-cli/pkg/utils/utils.go +++ /dev/null @@ -1,253 +0,0 @@ -// Copyright (C) 2015 Scaleway. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE.md file. - -// scw helpers - -// Package utils contains helpers -package utils - -import ( - "crypto/md5" - "errors" - "fmt" - "io" - "net" - "os" - "os/exec" - "path" - "path/filepath" - "reflect" - "regexp" - "strings" - "time" - - "golang.org/x/crypto/ssh" - - "github.com/mattn/go-isatty" - "github.com/moul/gotty-client" - "github.com/scaleway/scaleway-cli/pkg/sshcommand" - "github.com/sirupsen/logrus" - log "github.com/sirupsen/logrus" -) - -// SpawnRedirection is used to redirects the fluxes -type SpawnRedirection struct { - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer -} - -// SSHExec executes a command over SSH and redirects file-descriptors -func SSHExec(publicIPAddress, privateIPAddress, user string, port int, command []string, checkConnection bool, gateway string, enableSSHKeyForwarding bool) error { - gatewayUser := "root" - gatewayIPAddress := gateway - if strings.Contains(gateway, "@") { - parts := strings.Split(gatewayIPAddress, "@") - if len(parts) != 2 { - return fmt.Errorf("gateway: must be like root@IP") - } - gatewayUser = parts[0] - gatewayIPAddress = parts[1] - gateway = gatewayUser + "@" + gatewayIPAddress - } - - if publicIPAddress == "" && gatewayIPAddress == "" { - return errors.New("server does not have public IP") - } - if privateIPAddress == "" && gatewayIPAddress != "" { - return errors.New("server does not have private IP") - } - - if checkConnection { - useGateway := gatewayIPAddress != "" - if useGateway && !IsTCPPortOpen(fmt.Sprintf("%s:22", gatewayIPAddress)) { - return errors.New("gateway is not available, try again later") - } - if !useGateway && !IsTCPPortOpen(fmt.Sprintf("%s:%d", publicIPAddress, port)) { - return errors.New("server is not ready, try again later") - } - } - - sshCommand := NewSSHExecCmd(publicIPAddress, privateIPAddress, user, port, isatty.IsTerminal(os.Stdin.Fd()), command, gateway, enableSSHKeyForwarding) - - log.Debugf("Executing: %s", sshCommand) - - spawn := exec.Command("ssh", sshCommand.Slice()[1:]...) - spawn.Stdout = os.Stdout - spawn.Stdin = os.Stdin - spawn.Stderr = os.Stderr - return spawn.Run() -} - -// NewSSHExecCmd computes execve compatible arguments to run a command via ssh -func NewSSHExecCmd(publicIPAddress, privateIPAddress, user string, port int, allocateTTY bool, command []string, gatewayIPAddress string, enableSSHKeyForwarding bool) *sshcommand.Command { - quiet := os.Getenv("DEBUG") != "1" - secureExec := os.Getenv("SCW_SECURE_EXEC") == "1" - sshCommand := &sshcommand.Command{ - AllocateTTY: allocateTTY, - Command: command, - Host: publicIPAddress, - Quiet: quiet, - SkipHostKeyChecking: !secureExec, - User: user, - NoEscapeCommand: true, - Port: port, - EnableSSHKeyForwarding: enableSSHKeyForwarding, - } - if gatewayIPAddress != "" { - sshCommand.Host = privateIPAddress - sshCommand.Gateway = &sshcommand.Command{ - Host: gatewayIPAddress, - SkipHostKeyChecking: !secureExec, - AllocateTTY: allocateTTY, - Quiet: quiet, - User: user, - Port: port, - } - } - - return sshCommand -} - -// GeneratingAnSSHKey generates an SSH key -func GeneratingAnSSHKey(cfg SpawnRedirection, path string, name string) (string, error) { - args := []string{ - "-t", - "rsa", - "-b", - "4096", - "-f", - filepath.Join(path, name), - "-N", - "", - "-C", - "", - } - log.Infof("Executing commands %v", args) - spawn := exec.Command("ssh-keygen", args...) - spawn.Stdout = cfg.Stdout - spawn.Stdin = cfg.Stdin - spawn.Stderr = cfg.Stderr - return args[5], spawn.Run() -} - -// WaitForTCPPortOpen calls IsTCPPortOpen in a loop -func WaitForTCPPortOpen(dest string) error { - for { - if IsTCPPortOpen(dest) { - break - } - time.Sleep(1 * time.Second) - } - return nil -} - -// IsTCPPortOpen returns true if a TCP communication with "host:port" can be initialized -func IsTCPPortOpen(dest string) bool { - conn, err := net.DialTimeout("tcp", dest, time.Duration(2000)*time.Millisecond) - if err == nil { - defer conn.Close() - } - return err == nil -} - -// TruncIf ensures the input string does not exceed max size if cond is met -func TruncIf(str string, max int, cond bool) string { - if cond && len(str) > max { - return str[:max] - } - return str -} - -// Wordify convert complex name to a single word without special shell characters -func Wordify(str string) string { - str = regexp.MustCompile(`[^a-zA-Z0-9-]`).ReplaceAllString(str, "_") - str = regexp.MustCompile(`__+`).ReplaceAllString(str, "_") - str = strings.Trim(str, "_") - return str -} - -// PathToTARPathparts returns the two parts of a unix path -func PathToTARPathparts(fullPath string) (string, string) { - fullPath = strings.TrimRight(fullPath, "/") - return path.Dir(fullPath), path.Base(fullPath) -} - -// RemoveDuplicates transforms an array into a unique array -func RemoveDuplicates(elements []string) []string { - encountered := map[string]bool{} - - // Create a map of all unique elements. - for v := range elements { - encountered[elements[v]] = true - } - - // Place all keys from the map into a slice. - result := []string{} - for key := range encountered { - result = append(result, key) - } - return result -} - -// AttachToSerial tries to connect to server serial using 'gotty-client' and fallback with a help message -func AttachToSerial(serverID, apiToken, url string) (*gottyclient.Client, chan bool, error) { - gottyURL := os.Getenv("SCW_GOTTY_URL") - if gottyURL == "" { - gottyURL = url - } - URL := fmt.Sprintf("%s?arg=%s&arg=%s", gottyURL, apiToken, serverID) - - logrus.Debug("Connection to ", URL) - gottycli, err := gottyclient.NewClient(URL) - if err != nil { - return nil, nil, err - } - - if os.Getenv("SCW_TLSVERIFY") == "0" { - gottycli.SkipTLSVerify = true - } - - gottycli.UseProxyFromEnv = true - - if err = gottycli.Connect(); err != nil { - return nil, nil, err - } - done := make(chan bool) - - fmt.Println("You are connected, type 'Ctrl+q' to quit.") - go func() { - gottycli.Loop() - gottycli.Close() - done <- true - }() - return gottycli, done, nil -} - -func rfc4716hex(data []byte) string { - fingerprint := "" - - for i := 0; i < len(data); i++ { - fingerprint = fmt.Sprintf("%s%0.2x", fingerprint, data[i]) - if i != len(data)-1 { - fingerprint = fingerprint + ":" - } - } - return fingerprint -} - -// SSHGetFingerprint returns the fingerprint of an SSH key -func SSHGetFingerprint(key []byte) (string, error) { - publicKey, comment, _, _, err := ssh.ParseAuthorizedKey(key) - if err != nil { - return "", err - } - switch reflect.TypeOf(publicKey).String() { - case "*ssh.rsaPublicKey", "*ssh.dsaPublicKey", "*ssh.ecdsaPublicKey": - md5sum := md5.Sum(publicKey.Marshal()) - return publicKey.Type() + " " + rfc4716hex(md5sum[:]) + " " + comment, nil - default: - return "", errors.New("Can't handle this key") - } -} diff --git a/vendor/github.com/docker/docker/LICENSE b/vendor/github.com/scaleway/scaleway-sdk-go/LICENSE similarity index 99% rename from vendor/github.com/docker/docker/LICENSE rename to vendor/github.com/scaleway/scaleway-sdk-go/LICENSE index 9c8e20ab8..2712cc51a 100644 --- a/vendor/github.com/docker/docker/LICENSE +++ b/vendor/github.com/scaleway/scaleway-sdk-go/LICENSE @@ -176,7 +176,7 @@ END OF TERMS AND CONDITIONS - Copyright 2013-2017 Docker, Inc. + Copyright 2019 Scaleway. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/image_utils.go b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/image_utils.go new file mode 100644 index 000000000..e9d4a90f7 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/image_utils.go @@ -0,0 +1,56 @@ +package instance + +import ( + "time" + + "github.com/scaleway/scaleway-sdk-go/internal/async" + "github.com/scaleway/scaleway-sdk-go/internal/errors" + "github.com/scaleway/scaleway-sdk-go/scw" +) + +// WaitForImageRequest is used by WaitForImage method. +type WaitForImageRequest struct { + ImageID string + Zone scw.Zone + Timeout *time.Duration + RetryInterval *time.Duration +} + +// WaitForImage wait for the image to be in a "terminal state" before returning. +func (s *API) WaitForImage(req *WaitForImageRequest) (*Image, error) { + timeout := defaultTimeout + if req.Timeout != nil { + timeout = *req.Timeout + } + retryInterval := defaultRetryInterval + if req.RetryInterval != nil { + retryInterval = *req.RetryInterval + } + + terminalStatus := map[ImageState]struct{}{ + ImageStateAvailable: {}, + ImageStateError: {}, + } + + image, err := async.WaitSync(&async.WaitSyncConfig{ + Get: func() (interface{}, bool, error) { + res, err := s.GetImage(&GetImageRequest{ + ImageID: req.ImageID, + Zone: req.Zone, + }) + + if err != nil { + return nil, false, err + } + _, isTerminal := terminalStatus[res.Image.State] + + return res.Image, isTerminal, err + }, + Timeout: timeout, + IntervalStrategy: async.LinearIntervalStrategy(retryInterval), + }) + if err != nil { + return nil, errors.Wrap(err, "waiting for image failed") + } + return image.(*Image), nil +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/instance_metadata_sdk.go b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/instance_metadata_sdk.go new file mode 100644 index 000000000..1f5919880 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/instance_metadata_sdk.go @@ -0,0 +1,273 @@ +package instance + +import ( + "bytes" + "encoding/json" + "io/ioutil" + "math/rand" + "net" + "net/http" + "strconv" + "time" + + "github.com/scaleway/scaleway-sdk-go/internal/errors" +) + +var ( + metadataURL = "http://169.254.42.42" + metadataRetryBindPort = 200 +) + +// MetadataAPI metadata API +type MetadataAPI struct { +} + +// NewMetadataAPI returns a MetadataAPI object from a Scaleway client. +func NewMetadataAPI() *MetadataAPI { + return &MetadataAPI{} +} + +// GetMetadata returns the metadata available from the server +func (*MetadataAPI) GetMetadata() (m *Metadata, err error) { + resp, err := http.Get(metadataURL + "/conf?format=json") + if err != nil { + return nil, errors.Wrap(err, "error getting metadataURL") + } + defer resp.Body.Close() + + metadata := &Metadata{} + err = json.NewDecoder(resp.Body).Decode(metadata) + if err != nil { + return nil, errors.Wrap(err, "error decoding metadata") + } + return metadata, nil +} + +// Metadata represents the struct return by the metadata API +type Metadata struct { + ID string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Hostname string `json:"hostname,omitempty"` + Organization string `json:"organization,omitempty"` + Project string `json:"project,omitempty"` + CommercialType string `json:"commercial_type,omitempty"` + PublicIP struct { + Dynamic bool `json:"dynamic,omitempty"` + ID string `json:"id,omitempty"` + Address string `json:"address,omitempty"` + } `json:"public_ip,omitempty"` + PrivateIP string `json:"private_ip,omitempty"` + IPv6 struct { + Netmask string `json:"netmask,omitempty"` + Gateway string `json:"gateway,omitempty"` + Address string `json:"address,omitempty"` + } `json:"ipv6,omitempty"` + Location struct { + PlatformID string `json:"platform_id,omitempty"` + HypervisorID string `json:"hypervisor_id,omitempty"` + NodeID string `json:"node_id,omitempty"` + ClusterID string `json:"cluster_id,omitempty"` + ZoneID string `json:"zone_id,omitempty"` + } `json:"location,omitempty"` + Tags []string `json:"tags,omitempty"` + StateDetail string `json:"state_detail,omitempty"` + SSHPublicKeys []struct { + Description string `json:"description,omitempty"` + ModificationDate string `json:"modification_date,omitempty"` + IP string `json:"ip,omitempty"` + Key string `json:"key,omitempty"` + Fingerprint string `json:"fingerprint,omitempty"` + ID string `json:"id,omitempty"` + CreationDate string `json:"creation_date,omitempty"` + } `json:"ssh_public_keys,omitempty"` + Timezone string `json:"timezone,omitempty"` + Bootscript struct { + Kernel string `json:"kernel,omitempty"` + Title string `json:"title,omitempty"` + Default bool `json:"default,omitempty"` + Dtb string `json:"dtb,omitempty"` + Public bool `json:"publc,omitempty"` + Initrd string `json:"initrd,omitempty"` + Bootcmdargs string `json:"bootcmdargs,omitempty"` + Architecture string `json:"architecture,omitempty"` + Organization string `json:"organization,omitempty"` + Project string `json:"project,omitempty"` + ID string `json:"id,omitempty"` + } `json:"bootscript,omitempty"` + Volumes map[string]struct { + Name string `json:"name,omitempty"` + ModificationDate string `json:"modification_date,omitempty"` + ExportURI string `json:"export_uri,omitempty"` + VolumeType string `json:"volume_type,omitempty"` + CreationDate string `json:"creation_date,omitempty"` + State string `json:"state,omitempty"` + Organization string `json:"organization,omitempty"` + Project string `json:"project,omitempty"` + Server struct { + ID string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + } `json:"server,omitempty"` + ID string `json:"id,omitempty"` + Size int `json:"size,omitempty"` + } +} + +// ListUserData returns the metadata available from the server +func (*MetadataAPI) ListUserData() (res *UserData, err error) { + retries := 0 + for retries <= metadataRetryBindPort { + port := rand.Intn(1024) + localTCPAddr, err := net.ResolveTCPAddr("tcp", ":"+strconv.Itoa(port)) + if err != nil { + return nil, errors.Wrap(err, "error resolving tcp address") + } + + userdataClient := &http.Client{ + Transport: &http.Transport{ + DialContext: (&net.Dialer{ + LocalAddr: localTCPAddr, + DualStack: false, + FallbackDelay: time.Second * -1, + }).DialContext, + }, + } + + resp, err := userdataClient.Get(metadataURL + "/user_data?format=json") + if err != nil { + retries++ // retry with a different source port + continue + } + defer resp.Body.Close() + + userdata := &UserData{} + err = json.NewDecoder(resp.Body).Decode(userdata) + if err != nil { + return nil, errors.Wrap(err, "error decoding userdata") + } + return userdata, nil + } + return nil, errors.New("too many bind port retries for ListUserData") +} + +// GetUserData returns the value for the given metadata key +func (*MetadataAPI) GetUserData(key string) ([]byte, error) { + if key == "" { + return make([]byte, 0), errors.New("key must not be empty in GetUserData") + } + + retries := 0 + for retries <= metadataRetryBindPort { + port := rand.Intn(1024) + localTCPAddr, err := net.ResolveTCPAddr("tcp", ":"+strconv.Itoa(port)) + if err != nil { + return make([]byte, 0), errors.Wrap(err, "error resolving tcp address") + } + + userdataClient := &http.Client{ + Transport: &http.Transport{ + DialContext: (&net.Dialer{ + LocalAddr: localTCPAddr, + DualStack: false, + FallbackDelay: time.Second * -1, + }).DialContext, + }, + } + + resp, err := userdataClient.Get(metadataURL + "/user_data/" + key) + if err != nil { + retries++ // retry with a different source port + continue + } + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return make([]byte, 0), errors.Wrap(err, "error reading userdata body") + } + + return body, nil + } + return make([]byte, 0), errors.New("too may bind port retries for GetUserData") +} + +// SetUserData sets the userdata key with the given value +func (*MetadataAPI) SetUserData(key string, value []byte) error { + if key == "" { + return errors.New("key must not be empty in SetUserData") + } + + retries := 0 + for retries <= metadataRetryBindPort { + port := rand.Intn(1024) + localTCPAddr, err := net.ResolveTCPAddr("tcp", ":"+strconv.Itoa(port)) + if err != nil { + return errors.Wrap(err, "error resolving tcp address") + } + + userdataClient := &http.Client{ + Transport: &http.Transport{ + DialContext: (&net.Dialer{ + LocalAddr: localTCPAddr, + DualStack: false, + FallbackDelay: time.Second * -1, + }).DialContext, + }, + } + request, err := http.NewRequest("PATCH", metadataURL+"/user_data/"+key, bytes.NewBuffer(value)) + if err != nil { + return errors.Wrap(err, "error creating patch userdata request") + } + request.Header.Set("Content-Type", "text/plain") + _, err = userdataClient.Do(request) + if err != nil { + retries++ // retry with a different source port + continue + } + + return nil + } + return errors.New("too may bind port retries for SetUserData") +} + +// DeleteUserData deletes the userdata key and the associated value +func (*MetadataAPI) DeleteUserData(key string) error { + if key == "" { + return errors.New("key must not be empty in DeleteUserData") + } + + retries := 0 + for retries <= metadataRetryBindPort { + port := rand.Intn(1024) + localTCPAddr, err := net.ResolveTCPAddr("tcp", ":"+strconv.Itoa(port)) + if err != nil { + return errors.Wrap(err, "error resolving tcp address") + } + + userdataClient := &http.Client{ + Transport: &http.Transport{ + DialContext: (&net.Dialer{ + LocalAddr: localTCPAddr, + DualStack: false, + FallbackDelay: time.Second * -1, + }).DialContext, + }, + } + request, err := http.NewRequest("DELETE", metadataURL+"/user_data/"+key, bytes.NewBuffer([]byte(""))) + if err != nil { + return errors.Wrap(err, "error creating delete userdata request") + } + _, err = userdataClient.Do(request) + if err != nil { + retries++ // retry with a different source port + continue + } + + return nil + } + return errors.New("too may bind port retries for DeleteUserData") +} + +// UserData represents the user data +type UserData struct { + UserData []string `json:"user_data,omitempty"` +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/instance_sdk.go b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/instance_sdk.go new file mode 100644 index 000000000..b97dd6850 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/instance_sdk.go @@ -0,0 +1,4707 @@ +// This file was automatically generated. DO NOT EDIT. +// If you have any remark or suggestion do not hesitate to open an issue. + +// Package instance provides methods and message types of the instance v1 API. +package instance + +import ( + "bytes" + "encoding/json" + "fmt" + "net" + "net/http" + "net/url" + "strings" + "time" + + "github.com/scaleway/scaleway-sdk-go/internal/errors" + "github.com/scaleway/scaleway-sdk-go/internal/marshaler" + "github.com/scaleway/scaleway-sdk-go/internal/parameter" + "github.com/scaleway/scaleway-sdk-go/namegenerator" + "github.com/scaleway/scaleway-sdk-go/scw" +) + +// always import dependencies +var ( + _ fmt.Stringer + _ json.Unmarshaler + _ url.URL + _ net.IP + _ http.Header + _ bytes.Reader + _ time.Time + _ = strings.Join + + _ scw.ScalewayRequest + _ marshaler.Duration + _ scw.File + _ = parameter.AddToQuery + _ = namegenerator.GetRandomName +) + +// API: instance API +type API struct { + client *scw.Client +} + +// NewAPI returns a API object from a Scaleway client. +func NewAPI(client *scw.Client) *API { + return &API{ + client: client, + } +} + +type Arch string + +const ( + // ArchX86_64 is [insert doc]. + ArchX86_64 = Arch("x86_64") + // ArchArm is [insert doc]. + ArchArm = Arch("arm") +) + +func (enum Arch) String() string { + if enum == "" { + // return default value if empty + return "x86_64" + } + return string(enum) +} + +func (enum Arch) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, enum)), nil +} + +func (enum *Arch) UnmarshalJSON(data []byte) error { + tmp := "" + + if err := json.Unmarshal(data, &tmp); err != nil { + return err + } + + *enum = Arch(Arch(tmp).String()) + return nil +} + +type BootType string + +const ( + // BootTypeLocal is [insert doc]. + BootTypeLocal = BootType("local") + // BootTypeBootscript is [insert doc]. + BootTypeBootscript = BootType("bootscript") + // BootTypeRescue is [insert doc]. + BootTypeRescue = BootType("rescue") +) + +func (enum BootType) String() string { + if enum == "" { + // return default value if empty + return "local" + } + return string(enum) +} + +func (enum BootType) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, enum)), nil +} + +func (enum *BootType) UnmarshalJSON(data []byte) error { + tmp := "" + + if err := json.Unmarshal(data, &tmp); err != nil { + return err + } + + *enum = BootType(BootType(tmp).String()) + return nil +} + +type ImageState string + +const ( + // ImageStateAvailable is [insert doc]. + ImageStateAvailable = ImageState("available") + // ImageStateCreating is [insert doc]. + ImageStateCreating = ImageState("creating") + // ImageStateError is [insert doc]. + ImageStateError = ImageState("error") +) + +func (enum ImageState) String() string { + if enum == "" { + // return default value if empty + return "available" + } + return string(enum) +} + +func (enum ImageState) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, enum)), nil +} + +func (enum *ImageState) UnmarshalJSON(data []byte) error { + tmp := "" + + if err := json.Unmarshal(data, &tmp); err != nil { + return err + } + + *enum = ImageState(ImageState(tmp).String()) + return nil +} + +type PlacementGroupPolicyMode string + +const ( + // PlacementGroupPolicyModeOptional is [insert doc]. + PlacementGroupPolicyModeOptional = PlacementGroupPolicyMode("optional") + // PlacementGroupPolicyModeEnforced is [insert doc]. + PlacementGroupPolicyModeEnforced = PlacementGroupPolicyMode("enforced") +) + +func (enum PlacementGroupPolicyMode) String() string { + if enum == "" { + // return default value if empty + return "optional" + } + return string(enum) +} + +func (enum PlacementGroupPolicyMode) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, enum)), nil +} + +func (enum *PlacementGroupPolicyMode) UnmarshalJSON(data []byte) error { + tmp := "" + + if err := json.Unmarshal(data, &tmp); err != nil { + return err + } + + *enum = PlacementGroupPolicyMode(PlacementGroupPolicyMode(tmp).String()) + return nil +} + +type PlacementGroupPolicyType string + +const ( + // PlacementGroupPolicyTypeMaxAvailability is [insert doc]. + PlacementGroupPolicyTypeMaxAvailability = PlacementGroupPolicyType("max_availability") + // PlacementGroupPolicyTypeLowLatency is [insert doc]. + PlacementGroupPolicyTypeLowLatency = PlacementGroupPolicyType("low_latency") +) + +func (enum PlacementGroupPolicyType) String() string { + if enum == "" { + // return default value if empty + return "max_availability" + } + return string(enum) +} + +func (enum PlacementGroupPolicyType) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, enum)), nil +} + +func (enum *PlacementGroupPolicyType) UnmarshalJSON(data []byte) error { + tmp := "" + + if err := json.Unmarshal(data, &tmp); err != nil { + return err + } + + *enum = PlacementGroupPolicyType(PlacementGroupPolicyType(tmp).String()) + return nil +} + +type SecurityGroupPolicy string + +const ( + // SecurityGroupPolicyAccept is [insert doc]. + SecurityGroupPolicyAccept = SecurityGroupPolicy("accept") + // SecurityGroupPolicyDrop is [insert doc]. + SecurityGroupPolicyDrop = SecurityGroupPolicy("drop") +) + +func (enum SecurityGroupPolicy) String() string { + if enum == "" { + // return default value if empty + return "accept" + } + return string(enum) +} + +func (enum SecurityGroupPolicy) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, enum)), nil +} + +func (enum *SecurityGroupPolicy) UnmarshalJSON(data []byte) error { + tmp := "" + + if err := json.Unmarshal(data, &tmp); err != nil { + return err + } + + *enum = SecurityGroupPolicy(SecurityGroupPolicy(tmp).String()) + return nil +} + +type SecurityGroupRuleAction string + +const ( + // SecurityGroupRuleActionAccept is [insert doc]. + SecurityGroupRuleActionAccept = SecurityGroupRuleAction("accept") + // SecurityGroupRuleActionDrop is [insert doc]. + SecurityGroupRuleActionDrop = SecurityGroupRuleAction("drop") +) + +func (enum SecurityGroupRuleAction) String() string { + if enum == "" { + // return default value if empty + return "accept" + } + return string(enum) +} + +func (enum SecurityGroupRuleAction) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, enum)), nil +} + +func (enum *SecurityGroupRuleAction) UnmarshalJSON(data []byte) error { + tmp := "" + + if err := json.Unmarshal(data, &tmp); err != nil { + return err + } + + *enum = SecurityGroupRuleAction(SecurityGroupRuleAction(tmp).String()) + return nil +} + +type SecurityGroupRuleDirection string + +const ( + // SecurityGroupRuleDirectionInbound is [insert doc]. + SecurityGroupRuleDirectionInbound = SecurityGroupRuleDirection("inbound") + // SecurityGroupRuleDirectionOutbound is [insert doc]. + SecurityGroupRuleDirectionOutbound = SecurityGroupRuleDirection("outbound") +) + +func (enum SecurityGroupRuleDirection) String() string { + if enum == "" { + // return default value if empty + return "inbound" + } + return string(enum) +} + +func (enum SecurityGroupRuleDirection) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, enum)), nil +} + +func (enum *SecurityGroupRuleDirection) UnmarshalJSON(data []byte) error { + tmp := "" + + if err := json.Unmarshal(data, &tmp); err != nil { + return err + } + + *enum = SecurityGroupRuleDirection(SecurityGroupRuleDirection(tmp).String()) + return nil +} + +type SecurityGroupRuleProtocol string + +const ( + // SecurityGroupRuleProtocolTCP is [insert doc]. + SecurityGroupRuleProtocolTCP = SecurityGroupRuleProtocol("TCP") + // SecurityGroupRuleProtocolUDP is [insert doc]. + SecurityGroupRuleProtocolUDP = SecurityGroupRuleProtocol("UDP") + // SecurityGroupRuleProtocolICMP is [insert doc]. + SecurityGroupRuleProtocolICMP = SecurityGroupRuleProtocol("ICMP") + // SecurityGroupRuleProtocolANY is [insert doc]. + SecurityGroupRuleProtocolANY = SecurityGroupRuleProtocol("ANY") +) + +func (enum SecurityGroupRuleProtocol) String() string { + if enum == "" { + // return default value if empty + return "TCP" + } + return string(enum) +} + +func (enum SecurityGroupRuleProtocol) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, enum)), nil +} + +func (enum *SecurityGroupRuleProtocol) UnmarshalJSON(data []byte) error { + tmp := "" + + if err := json.Unmarshal(data, &tmp); err != nil { + return err + } + + *enum = SecurityGroupRuleProtocol(SecurityGroupRuleProtocol(tmp).String()) + return nil +} + +type ServerAction string + +const ( + // ServerActionPoweron is [insert doc]. + ServerActionPoweron = ServerAction("poweron") + // ServerActionBackup is [insert doc]. + ServerActionBackup = ServerAction("backup") + // ServerActionStopInPlace is [insert doc]. + ServerActionStopInPlace = ServerAction("stop_in_place") + // ServerActionPoweroff is [insert doc]. + ServerActionPoweroff = ServerAction("poweroff") + // ServerActionTerminate is [insert doc]. + ServerActionTerminate = ServerAction("terminate") + // ServerActionReboot is [insert doc]. + ServerActionReboot = ServerAction("reboot") +) + +func (enum ServerAction) String() string { + if enum == "" { + // return default value if empty + return "poweron" + } + return string(enum) +} + +func (enum ServerAction) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, enum)), nil +} + +func (enum *ServerAction) UnmarshalJSON(data []byte) error { + tmp := "" + + if err := json.Unmarshal(data, &tmp); err != nil { + return err + } + + *enum = ServerAction(ServerAction(tmp).String()) + return nil +} + +type ServerState string + +const ( + // ServerStateRunning is [insert doc]. + ServerStateRunning = ServerState("running") + // ServerStateStopped is [insert doc]. + ServerStateStopped = ServerState("stopped") + // ServerStateStoppedInPlace is [insert doc]. + ServerStateStoppedInPlace = ServerState("stopped in place") + // ServerStateStarting is [insert doc]. + ServerStateStarting = ServerState("starting") + // ServerStateStopping is [insert doc]. + ServerStateStopping = ServerState("stopping") + // ServerStateLocked is [insert doc]. + ServerStateLocked = ServerState("locked") +) + +func (enum ServerState) String() string { + if enum == "" { + // return default value if empty + return "running" + } + return string(enum) +} + +func (enum ServerState) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, enum)), nil +} + +func (enum *ServerState) UnmarshalJSON(data []byte) error { + tmp := "" + + if err := json.Unmarshal(data, &tmp); err != nil { + return err + } + + *enum = ServerState(ServerState(tmp).String()) + return nil +} + +type ServerTypesAvailability string + +const ( + // ServerTypesAvailabilityAvailable is [insert doc]. + ServerTypesAvailabilityAvailable = ServerTypesAvailability("available") + // ServerTypesAvailabilityScarce is [insert doc]. + ServerTypesAvailabilityScarce = ServerTypesAvailability("scarce") + // ServerTypesAvailabilityShortage is [insert doc]. + ServerTypesAvailabilityShortage = ServerTypesAvailability("shortage") +) + +func (enum ServerTypesAvailability) String() string { + if enum == "" { + // return default value if empty + return "available" + } + return string(enum) +} + +func (enum ServerTypesAvailability) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, enum)), nil +} + +func (enum *ServerTypesAvailability) UnmarshalJSON(data []byte) error { + tmp := "" + + if err := json.Unmarshal(data, &tmp); err != nil { + return err + } + + *enum = ServerTypesAvailability(ServerTypesAvailability(tmp).String()) + return nil +} + +type SnapshotState string + +const ( + // SnapshotStateAvailable is [insert doc]. + SnapshotStateAvailable = SnapshotState("available") + // SnapshotStateSnapshotting is [insert doc]. + SnapshotStateSnapshotting = SnapshotState("snapshotting") + // SnapshotStateError is [insert doc]. + SnapshotStateError = SnapshotState("error") +) + +func (enum SnapshotState) String() string { + if enum == "" { + // return default value if empty + return "available" + } + return string(enum) +} + +func (enum SnapshotState) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, enum)), nil +} + +func (enum *SnapshotState) UnmarshalJSON(data []byte) error { + tmp := "" + + if err := json.Unmarshal(data, &tmp); err != nil { + return err + } + + *enum = SnapshotState(SnapshotState(tmp).String()) + return nil +} + +type TaskStatus string + +const ( + // TaskStatusPending is [insert doc]. + TaskStatusPending = TaskStatus("pending") + // TaskStatusStarted is [insert doc]. + TaskStatusStarted = TaskStatus("started") + // TaskStatusSuccess is [insert doc]. + TaskStatusSuccess = TaskStatus("success") + // TaskStatusFailure is [insert doc]. + TaskStatusFailure = TaskStatus("failure") + // TaskStatusRetry is [insert doc]. + TaskStatusRetry = TaskStatus("retry") +) + +func (enum TaskStatus) String() string { + if enum == "" { + // return default value if empty + return "pending" + } + return string(enum) +} + +func (enum TaskStatus) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, enum)), nil +} + +func (enum *TaskStatus) UnmarshalJSON(data []byte) error { + tmp := "" + + if err := json.Unmarshal(data, &tmp); err != nil { + return err + } + + *enum = TaskStatus(TaskStatus(tmp).String()) + return nil +} + +type VolumeState string + +const ( + // VolumeStateAvailable is [insert doc]. + VolumeStateAvailable = VolumeState("available") + // VolumeStateSnapshotting is [insert doc]. + VolumeStateSnapshotting = VolumeState("snapshotting") + // VolumeStateError is [insert doc]. + VolumeStateError = VolumeState("error") +) + +func (enum VolumeState) String() string { + if enum == "" { + // return default value if empty + return "available" + } + return string(enum) +} + +func (enum VolumeState) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, enum)), nil +} + +func (enum *VolumeState) UnmarshalJSON(data []byte) error { + tmp := "" + + if err := json.Unmarshal(data, &tmp); err != nil { + return err + } + + *enum = VolumeState(VolumeState(tmp).String()) + return nil +} + +type VolumeVolumeType string + +const ( + // VolumeVolumeTypeLSSD is [insert doc]. + VolumeVolumeTypeLSSD = VolumeVolumeType("l_ssd") + // VolumeVolumeTypeBSSD is [insert doc]. + VolumeVolumeTypeBSSD = VolumeVolumeType("b_ssd") +) + +func (enum VolumeVolumeType) String() string { + if enum == "" { + // return default value if empty + return "l_ssd" + } + return string(enum) +} + +func (enum VolumeVolumeType) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%s"`, enum)), nil +} + +func (enum *VolumeVolumeType) UnmarshalJSON(data []byte) error { + tmp := "" + + if err := json.Unmarshal(data, &tmp); err != nil { + return err + } + + *enum = VolumeVolumeType(VolumeVolumeType(tmp).String()) + return nil +} + +// Bootscript: bootscript +type Bootscript struct { + // Bootcmdargs: the bootscript arguments + Bootcmdargs string `json:"bootcmdargs"` + // Default: dispmay if the bootscript is the default bootscript if no other boot option is configured + Default bool `json:"default"` + // Dtb: provide information regarding a Device Tree Binary (dtb) for use with C1 servers + Dtb string `json:"dtb"` + // ID: the bootscript ID + ID string `json:"id"` + // Initrd: the initrd (initial ramdisk) configuration + Initrd string `json:"initrd"` + // Kernel: the server kernel version + Kernel string `json:"kernel"` + // Organization: the bootscript organization + Organization string `json:"organization"` + // Project: the bootscript project ID + Project string `json:"project"` + // Public: provide information if the bootscript is public + Public bool `json:"public"` + // Title: the bootscript title + Title string `json:"title"` + // Arch: the bootscript arch + // + // Default value: x86_64 + Arch Arch `json:"arch"` + // Zone: the zone in which is the bootscript + Zone scw.Zone `json:"zone"` +} + +type CreateIPResponse struct { + IP *IP `json:"ip"` + + Location string `json:"Location"` +} + +type CreateImageResponse struct { + Image *Image `json:"image"` + + Location string `json:"Location"` +} + +type CreatePlacementGroupResponse struct { + PlacementGroup *PlacementGroup `json:"placement_group"` +} + +type CreatePrivateNICResponse struct { + PrivateNic *PrivateNIC `json:"private_nic"` +} + +type CreateSecurityGroupResponse struct { + SecurityGroup *SecurityGroup `json:"security_group"` +} + +type CreateSecurityGroupRuleResponse struct { + Rule *SecurityGroupRule `json:"rule"` +} + +type CreateServerResponse struct { + Server *Server `json:"server"` +} + +type CreateSnapshotResponse struct { + Snapshot *Snapshot `json:"snapshot"` +} + +type CreateVolumeResponse struct { + Volume *Volume `json:"volume"` + + Location string `json:"Location"` +} + +type Dashboard struct { + VolumesCount uint32 `json:"volumes_count"` + + RunningServersCount uint32 `json:"running_servers_count"` + + ServersByTypes map[string]uint32 `json:"servers_by_types"` + + ImagesCount uint32 `json:"images_count"` + + SnapshotsCount uint32 `json:"snapshots_count"` + + ServersCount uint32 `json:"servers_count"` + + IPsCount uint32 `json:"ips_count"` + + SecurityGroupsCount uint32 `json:"security_groups_count"` + + IPsUnused uint32 `json:"ips_unused"` +} + +type GetBootscriptResponse struct { + Bootscript *Bootscript `json:"bootscript"` +} + +type GetDashboardResponse struct { + Dashboard *Dashboard `json:"dashboard"` +} + +type GetIPResponse struct { + IP *IP `json:"ip"` +} + +type GetImageResponse struct { + Image *Image `json:"image"` +} + +type GetPlacementGroupResponse struct { + PlacementGroup *PlacementGroup `json:"placement_group"` +} + +type GetPlacementGroupServersResponse struct { + Servers []*PlacementGroupServer `json:"servers"` +} + +type GetPrivateNICResponse struct { + PrivateNic *PrivateNIC `json:"private_nic"` +} + +type GetSecurityGroupResponse struct { + SecurityGroup *SecurityGroup `json:"security_group"` +} + +type GetSecurityGroupRuleResponse struct { + Rule *SecurityGroupRule `json:"rule"` +} + +type GetServerResponse struct { + Server *Server `json:"server"` +} + +type GetServerTypesAvailabilityResponse struct { + Servers map[string]*GetServerTypesAvailabilityResponseAvailability `json:"servers"` +} + +type GetServerTypesAvailabilityResponseAvailability struct { + // Availability: + // + // Default value: available + Availability ServerTypesAvailability `json:"availability"` +} + +type GetSnapshotResponse struct { + Snapshot *Snapshot `json:"snapshot"` +} + +type GetVolumeResponse struct { + Volume *Volume `json:"volume"` +} + +type IP struct { + ID string `json:"id"` + + Address net.IP `json:"address"` + + Reverse *string `json:"reverse"` + + Server *ServerSummary `json:"server"` + + Organization string `json:"organization"` + + Tags []string `json:"tags"` + + Project string `json:"project"` + + Zone scw.Zone `json:"zone"` +} + +type Image struct { + ID string `json:"id"` + + Name string `json:"name"` + // Arch: + // + // Default value: x86_64 + Arch Arch `json:"arch"` + + CreationDate *time.Time `json:"creation_date"` + + ModificationDate *time.Time `json:"modification_date"` + + DefaultBootscript *Bootscript `json:"default_bootscript"` + + ExtraVolumes map[string]*Volume `json:"extra_volumes"` + + FromServer string `json:"from_server"` + + Organization string `json:"organization"` + + Public bool `json:"public"` + + RootVolume *VolumeSummary `json:"root_volume"` + // State: + // + // Default value: available + State ImageState `json:"state"` + + Project string `json:"project"` + + Zone scw.Zone `json:"zone"` +} + +type ListBootscriptsResponse struct { + Bootscripts []*Bootscript `json:"bootscripts"` + + TotalCount uint32 `json:"total_count"` +} + +type ListIPsResponse struct { + IPs []*IP `json:"ips"` + + TotalCount uint32 `json:"total_count"` +} + +type ListImagesResponse struct { + Images []*Image `json:"images"` + + TotalCount uint32 `json:"total_count"` +} + +type ListPlacementGroupsResponse struct { + PlacementGroups []*PlacementGroup `json:"placement_groups"` + + TotalCount uint32 `json:"total_count"` +} + +type ListPrivateNICsResponse struct { + PrivateNics []*PrivateNIC `json:"private_nics"` +} + +type ListSecurityGroupRulesResponse struct { + Rules []*SecurityGroupRule `json:"rules"` + + TotalCount uint32 `json:"total_count"` +} + +type ListSecurityGroupsResponse struct { + SecurityGroups []*SecurityGroup `json:"security_groups"` + + TotalCount uint32 `json:"total_count"` +} + +type ListServerActionsResponse struct { + Actions []ServerAction `json:"actions"` +} + +type ListServerUserDataResponse struct { + UserData []string `json:"user_data"` +} + +type ListServersResponse struct { + Servers []*Server `json:"servers"` + + TotalCount uint32 `json:"total_count"` +} + +type ListServersTypesResponse struct { + Servers map[string]*ServerType `json:"servers"` + + TotalCount uint32 `json:"total_count"` +} + +type ListSnapshotsResponse struct { + Snapshots []*Snapshot `json:"snapshots"` + + TotalCount uint32 `json:"total_count"` +} + +type ListVolumesResponse struct { + Volumes []*Volume `json:"volumes"` + + TotalCount uint32 `json:"total_count"` +} + +type ListVolumesTypesResponse struct { + Volumes map[string]*VolumeType `json:"volumes"` + + TotalCount uint32 `json:"total_count"` +} + +type NullableStringValue struct { + Null bool `json:"null,omitempty"` + + Value string `json:"value,omitempty"` +} + +// PlacementGroup: placement group +type PlacementGroup struct { + // ID: the placement group unique ID + ID string `json:"id"` + // Name: the placement group name + Name string `json:"name"` + // Organization: the placement group organization + Organization string `json:"organization"` + // Project: the placement group project ID + Project string `json:"project"` + // PolicyMode: select the failling mode when the placement cannot be respected, either optional or enforced + // + // Default value: optional + PolicyMode PlacementGroupPolicyMode `json:"policy_mode"` + // PolicyType: select the behavior of the placement group, either low_latency (group) or max_availability (spread) + // + // Default value: max_availability + PolicyType PlacementGroupPolicyType `json:"policy_type"` + // PolicyRespected: returns true if the policy is respected, false otherwise + PolicyRespected bool `json:"policy_respected"` + // Zone: the zone in which is the placement group + Zone scw.Zone `json:"zone"` +} + +type PlacementGroupServer struct { + ID string `json:"id"` + + Name string `json:"name"` + + PolicyRespected bool `json:"policy_respected"` +} + +// PrivateNIC: private nic +type PrivateNIC struct { + // ID: the private NIC unique ID + ID string `json:"id,omitempty"` + // ServerID: the server the private NIC is attached to + ServerID string `json:"server_id,omitempty"` + // PrivateNetworkID: the private network where the private NIC is attached + PrivateNetworkID string `json:"private_network_id,omitempty"` + // MacAddress: the private NIC MAC address + MacAddress string `json:"mac_address,omitempty"` +} + +// SecurityGroup: security group +type SecurityGroup struct { + // ID: the security groups' unique ID + ID string `json:"id"` + // Name: the security groups name + Name string `json:"name"` + // Description: the security groups description + Description string `json:"description"` + // EnableDefaultSecurity: true if SMTP is blocked on IPv4 and IPv6 + EnableDefaultSecurity bool `json:"enable_default_security"` + // InboundDefaultPolicy: the default inbound policy + // + // Default value: accept + InboundDefaultPolicy SecurityGroupPolicy `json:"inbound_default_policy"` + // OutboundDefaultPolicy: the default outbound policy + // + // Default value: accept + OutboundDefaultPolicy SecurityGroupPolicy `json:"outbound_default_policy"` + // Organization: the security groups organization ID + Organization string `json:"organization"` + // Project: the project ID of the security group + Project string `json:"project"` + // OrganizationDefault: true if it is your default security group for this organization + OrganizationDefault bool `json:"organization_default"` + // ProjectDefault: true if it is your default security group for this project id + ProjectDefault bool `json:"project_default"` + // CreationDate: the security group creation date + CreationDate *time.Time `json:"creation_date"` + // ModificationDate: the security group modification date + ModificationDate *time.Time `json:"modification_date"` + // Servers: list of servers attached to this security group + Servers []*ServerSummary `json:"servers"` + // Stateful: true if the security group is stateful + Stateful bool `json:"stateful"` + // Zone: the zone in which is the security group + Zone scw.Zone `json:"zone"` +} + +type SecurityGroupRule struct { + ID string `json:"id"` + // Protocol: + // + // Default value: TCP + Protocol SecurityGroupRuleProtocol `json:"protocol"` + // Direction: + // + // Default value: inbound + Direction SecurityGroupRuleDirection `json:"direction"` + // Action: + // + // Default value: accept + Action SecurityGroupRuleAction `json:"action"` + + IPRange scw.IPNet `json:"ip_range"` + + DestPortFrom *uint32 `json:"dest_port_from"` + + DestPortTo *uint32 `json:"dest_port_to"` + + Position uint32 `json:"position"` + + Editable bool `json:"editable"` + + Zone scw.Zone `json:"zone"` +} + +type SecurityGroupSummary struct { + ID string `json:"id"` + + Name string `json:"name"` +} + +type SecurityGroupTemplate struct { + ID string `json:"id,omitempty"` + + Name string `json:"name,omitempty"` +} + +// Server: server +type Server struct { + // ID: the server unique ID + ID string `json:"id"` + // Name: the server name + Name string `json:"name"` + // Organization: the server organization + Organization string `json:"organization"` + // Project: the server project ID + Project string `json:"project"` + // AllowedActions: provide as list of allowed actions on the server + AllowedActions []ServerAction `json:"allowed_actions"` + // Tags: the server associated tags + Tags []string `json:"tags"` + // CommercialType: the server commercial type (eg. GP1-M) + CommercialType string `json:"commercial_type"` + // CreationDate: the server creation date + CreationDate *time.Time `json:"creation_date"` + // DynamicIPRequired: true if a dynamic IP is required + DynamicIPRequired bool `json:"dynamic_ip_required"` + // EnableIPv6: true if IPv6 is enabled + EnableIPv6 bool `json:"enable_ipv6"` + // Hostname: the server host name + Hostname string `json:"hostname"` + // Image: provide information on the server image + Image *Image `json:"image"` + // Protected: the server protection option is activated + Protected bool `json:"protected"` + // PrivateIP: the server private IP address + PrivateIP *string `json:"private_ip"` + // PublicIP: information about the public IP + PublicIP *ServerIP `json:"public_ip"` + // ModificationDate: the server modification date + ModificationDate *time.Time `json:"modification_date"` + // State: the server state + // + // Default value: running + State ServerState `json:"state"` + // Location: the server location + Location *ServerLocation `json:"location"` + // IPv6: the server IPv6 address + IPv6 *ServerIPv6 `json:"ipv6"` + // Bootscript: the server bootscript + Bootscript *Bootscript `json:"bootscript"` + // BootType: the server boot type + // + // Default value: local + BootType BootType `json:"boot_type"` + // Volumes: the server volumes + Volumes map[string]*Volume `json:"volumes"` + // SecurityGroup: the server security group + SecurityGroup *SecurityGroupSummary `json:"security_group"` + // Maintenances: the server planned maintenances + Maintenances []*ServerMaintenance `json:"maintenances"` + // StateDetail: the server state_detail + StateDetail string `json:"state_detail"` + // Arch: the server arch + // + // Default value: x86_64 + Arch Arch `json:"arch"` + // PlacementGroup: the server placement group + PlacementGroup *PlacementGroup `json:"placement_group"` + // PrivateNics: the server private NICs + PrivateNics []*PrivateNIC `json:"private_nics"` + // Zone: the zone in which is the server + Zone scw.Zone `json:"zone"` +} + +type ServerActionResponse struct { + Task *Task `json:"task"` +} + +// ServerIP: server. ip +type ServerIP struct { + // ID: the unique ID of the IP address + ID string `json:"id"` + // Address: the server public IPv4 IP-Address + Address net.IP `json:"address"` + // Dynamic: true if the IP address is dynamic + Dynamic bool `json:"dynamic"` +} + +// ServerIPv6: server. ipv6 +type ServerIPv6 struct { + // Address: the server IPv6 IP-Address + Address net.IP `json:"address"` + // Gateway: the IPv6 IP-addresses gateway + Gateway net.IP `json:"gateway"` + // Netmask: the IPv6 IP-addresses CIDR netmask + Netmask string `json:"netmask"` +} + +type ServerLocation struct { + ClusterID string `json:"cluster_id"` + + HypervisorID string `json:"hypervisor_id"` + + NodeID string `json:"node_id"` + + PlatformID string `json:"platform_id"` + + ZoneID string `json:"zone_id"` +} + +type ServerMaintenance struct { +} + +type ServerSummary struct { + ID string `json:"id"` + + Name string `json:"name"` +} + +type ServerType struct { + MonthlyPrice float32 `json:"monthly_price"` + + HourlyPrice float32 `json:"hourly_price"` + + AltNames []string `json:"alt_names"` + + PerVolumeConstraint *ServerTypeVolumeConstraintsByType `json:"per_volume_constraint"` + + VolumesConstraint *ServerTypeVolumeConstraintSizes `json:"volumes_constraint"` + + Ncpus uint32 `json:"ncpus"` + + Gpu *uint64 `json:"gpu"` + + RAM uint64 `json:"ram"` + // Arch: + // + // Default value: x86_64 + Arch Arch `json:"arch"` + + Baremetal bool `json:"baremetal"` + + Network *ServerTypeNetwork `json:"network"` +} + +type ServerTypeNetwork struct { + Interfaces []*ServerTypeNetworkInterface `json:"interfaces"` + + SumInternalBandwidth *uint64 `json:"sum_internal_bandwidth"` + + SumInternetBandwidth *uint64 `json:"sum_internet_bandwidth"` + + IPv6Support bool `json:"ipv6_support"` +} + +type ServerTypeNetworkInterface struct { + InternalBandwidth *uint64 `json:"internal_bandwidth"` + + InternetBandwidth *uint64 `json:"internet_bandwidth"` +} + +type ServerTypeVolumeConstraintSizes struct { + MinSize scw.Size `json:"min_size"` + + MaxSize scw.Size `json:"max_size"` +} + +type ServerTypeVolumeConstraintsByType struct { + LSSD *ServerTypeVolumeConstraintSizes `json:"l_ssd"` +} + +type SetPlacementGroupResponse struct { + PlacementGroup *PlacementGroup `json:"placement_group"` +} + +type SetPlacementGroupServersResponse struct { + Servers []*PlacementGroupServer `json:"servers"` +} + +type Snapshot struct { + ID string `json:"id"` + + Name string `json:"name"` + + Organization string `json:"organization"` + // VolumeType: + // + // Default value: l_ssd + VolumeType VolumeVolumeType `json:"volume_type"` + + Size scw.Size `json:"size"` + // State: + // + // Default value: available + State SnapshotState `json:"state"` + + BaseVolume *SnapshotBaseVolume `json:"base_volume"` + + CreationDate *time.Time `json:"creation_date"` + + ModificationDate *time.Time `json:"modification_date"` + + Project string `json:"project"` + + Zone scw.Zone `json:"zone"` +} + +type SnapshotBaseVolume struct { + ID string `json:"id"` + + Name string `json:"name"` +} + +// Task: task +type Task struct { + // ID: the unique ID of the task + ID string `json:"id"` + // Description: the description of the task + Description string `json:"description"` + // Progress: the progress of the task in percent + Progress int32 `json:"progress"` + // StartedAt: the task start date + StartedAt *time.Time `json:"started_at"` + // TerminatedAt: the task end date + TerminatedAt *time.Time `json:"terminated_at"` + // Status: the task status + // + // Default value: pending + Status TaskStatus `json:"status"` + + HrefFrom string `json:"href_from"` + + HrefResult string `json:"href_result"` + // Zone: the zone in which is the task + Zone scw.Zone `json:"zone"` +} + +type UpdateIPResponse struct { + IP *IP `json:"ip"` +} + +type UpdatePlacementGroupResponse struct { + PlacementGroup *PlacementGroup `json:"placement_group"` +} + +type UpdatePlacementGroupServersResponse struct { + Servers []*PlacementGroupServer `json:"servers"` +} + +type UpdateServerResponse struct { + Server *Server `json:"server"` +} + +type UpdateVolumeResponse struct { + Volume *Volume `json:"volume"` +} + +// Volume: volume +type Volume struct { + // ID: the volumes unique ID + ID string `json:"id"` + // Name: the volumes names + Name string `json:"name"` + // ExportURI: show the volumes NBD export URI + ExportURI string `json:"export_uri"` + // Size: the volumes disk size + Size scw.Size `json:"size"` + // VolumeType: the volumes type + // + // Default value: l_ssd + VolumeType VolumeVolumeType `json:"volume_type"` + // CreationDate: the volumes creation date + CreationDate *time.Time `json:"creation_date"` + // ModificationDate: the volumes modification date + ModificationDate *time.Time `json:"modification_date"` + // Organization: the volumes organization + Organization string `json:"organization"` + // Project: the volumes project ID + Project string `json:"project"` + // Server: the server attached to the volume + Server *ServerSummary `json:"server"` + // State: the volumes state + // + // Default value: available + State VolumeState `json:"state"` + // Zone: the zone in which is the volume + Zone scw.Zone `json:"zone"` +} + +type VolumeSummary struct { + ID string `json:"id"` + + Name string `json:"name"` + + Size scw.Size `json:"size"` + // VolumeType: + // + // Default value: l_ssd + VolumeType VolumeVolumeType `json:"volume_type"` +} + +// VolumeTemplate: volume template +type VolumeTemplate struct { + // ID: UUID of the volume + ID string `json:"id,omitempty"` + // Name: name of the volume + Name string `json:"name,omitempty"` + // Size: disk size of the volume + Size scw.Size `json:"size,omitempty"` + // VolumeType: type of the volume + // + // Default value: l_ssd + VolumeType VolumeVolumeType `json:"volume_type,omitempty"` + // Organization: organization ID of the volume + Organization string `json:"organization,omitempty"` + // Project: project ID of the volume + Project string `json:"project,omitempty"` +} + +type VolumeType struct { + DisplayName string `json:"display_name"` + + Capabilities *VolumeTypeCapabilities `json:"capabilities"` + + Constraints *VolumeTypeConstraints `json:"constraints"` +} + +type VolumeTypeCapabilities struct { + Snapshot bool `json:"snapshot"` +} + +type VolumeTypeConstraints struct { + Min scw.Size `json:"min"` + + Max scw.Size `json:"max"` +} + +// setImageResponse: set image response +type setImageResponse struct { + Image *Image `json:"image"` +} + +// setSecurityGroupResponse: set security group response +type setSecurityGroupResponse struct { + SecurityGroup *SecurityGroup `json:"security_group"` +} + +// setSecurityGroupRuleResponse: set security group rule response +type setSecurityGroupRuleResponse struct { + Rule *SecurityGroupRule `json:"rule"` +} + +// setServerResponse: set server response +type setServerResponse struct { + Server *Server `json:"server"` +} + +// setSnapshotResponse: set snapshot response +type setSnapshotResponse struct { + Snapshot *Snapshot `json:"snapshot"` +} + +// Service API + +type GetServerTypesAvailabilityRequest struct { + Zone scw.Zone `json:"-"` + + PerPage *uint32 `json:"-"` + + Page *int32 `json:"-"` +} + +// GetServerTypesAvailability: get availability +// +// Get availibility for all server types. +func (s *API) GetServerTypesAvailability(req *GetServerTypesAvailabilityRequest, opts ...scw.RequestOption) (*GetServerTypesAvailabilityResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + defaultPerPage, exist := s.client.GetDefaultPageSize() + if (req.PerPage == nil || *req.PerPage == 0) && exist { + req.PerPage = &defaultPerPage + } + + query := url.Values{} + parameter.AddToQuery(query, "per_page", req.PerPage) + parameter.AddToQuery(query, "page", req.Page) + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/products/servers/availability", + Query: query, + Headers: http.Header{}, + } + + var resp GetServerTypesAvailabilityResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type ListServersTypesRequest struct { + Zone scw.Zone `json:"-"` + + PerPage *uint32 `json:"-"` + + Page *int32 `json:"-"` +} + +// ListServersTypes: list server types +// +// Get server types technical details. +func (s *API) ListServersTypes(req *ListServersTypesRequest, opts ...scw.RequestOption) (*ListServersTypesResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + defaultPerPage, exist := s.client.GetDefaultPageSize() + if (req.PerPage == nil || *req.PerPage == 0) && exist { + req.PerPage = &defaultPerPage + } + + query := url.Values{} + parameter.AddToQuery(query, "per_page", req.PerPage) + parameter.AddToQuery(query, "page", req.Page) + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/products/servers", + Query: query, + Headers: http.Header{}, + } + + var resp ListServersTypesResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type ListVolumesTypesRequest struct { + Zone scw.Zone `json:"-"` + + PerPage *uint32 `json:"-"` + + Page *int32 `json:"-"` +} + +// ListVolumesTypes: list volumes types +// +// Get volumes technical details. +func (s *API) ListVolumesTypes(req *ListVolumesTypesRequest, opts ...scw.RequestOption) (*ListVolumesTypesResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + defaultPerPage, exist := s.client.GetDefaultPageSize() + if (req.PerPage == nil || *req.PerPage == 0) && exist { + req.PerPage = &defaultPerPage + } + + query := url.Values{} + parameter.AddToQuery(query, "per_page", req.PerPage) + parameter.AddToQuery(query, "page", req.Page) + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/products/volumes", + Query: query, + Headers: http.Header{}, + } + + var resp ListVolumesTypesResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type ListServersRequest struct { + Zone scw.Zone `json:"-"` + // PerPage: a positive integer lower or equal to 100 to select the number of items to return + // + // Default value: 50 + PerPage *uint32 `json:"-"` + // Page: a positive integer to choose the page to return + Page *int32 `json:"-"` + // Organization: list only servers of this organization + Organization *string `json:"-"` + // Project: list only servers of this project ID + Project *string `json:"-"` + // Name: filter servers by name (for eg. "server1" will return "server100" and "server1" but not "foo") + Name *string `json:"-"` + // PrivateIP: list servers by private_ip + PrivateIP *net.IP `json:"-"` + // WithoutIP: list servers that are not attached to a public IP + WithoutIP *bool `json:"-"` + // CommercialType: list servers of this commercial type + CommercialType *string `json:"-"` + // State: list servers in this state + // + // Default value: running + State *ServerState `json:"-"` + // Tags: list servers with these exact tags + Tags []string `json:"-"` +} + +// ListServers: list all servers +func (s *API) ListServers(req *ListServersRequest, opts ...scw.RequestOption) (*ListServersResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + defaultPerPage, exist := s.client.GetDefaultPageSize() + if (req.PerPage == nil || *req.PerPage == 0) && exist { + req.PerPage = &defaultPerPage + } + + query := url.Values{} + parameter.AddToQuery(query, "per_page", req.PerPage) + parameter.AddToQuery(query, "page", req.Page) + parameter.AddToQuery(query, "organization", req.Organization) + parameter.AddToQuery(query, "project", req.Project) + parameter.AddToQuery(query, "name", req.Name) + parameter.AddToQuery(query, "private_ip", req.PrivateIP) + parameter.AddToQuery(query, "without_ip", req.WithoutIP) + parameter.AddToQuery(query, "commercial_type", req.CommercialType) + parameter.AddToQuery(query, "state", req.State) + if len(req.Tags) != 0 { + parameter.AddToQuery(query, "tags", strings.Join(req.Tags, ",")) + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers", + Query: query, + Headers: http.Header{}, + } + + var resp ListServersResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +// UnsafeGetTotalCount should not be used +// Internal usage only +func (r *ListServersResponse) UnsafeGetTotalCount() uint32 { + return r.TotalCount +} + +// UnsafeAppend should not be used +// Internal usage only +func (r *ListServersResponse) UnsafeAppend(res interface{}) (uint32, error) { + results, ok := res.(*ListServersResponse) + if !ok { + return 0, errors.New("%T type cannot be appended to type %T", res, r) + } + + r.Servers = append(r.Servers, results.Servers...) + r.TotalCount += uint32(len(results.Servers)) + return uint32(len(results.Servers)), nil +} + +type CreateServerRequest struct { + Zone scw.Zone `json:"-"` + // Name: the server name + Name string `json:"name,omitempty"` + // DynamicIPRequired: define if a dynamic IP is required for the instance + DynamicIPRequired *bool `json:"dynamic_ip_required,omitempty"` + // CommercialType: define the server commercial type (i.e. GP1-S) + CommercialType string `json:"commercial_type,omitempty"` + // Image: the server image ID or label + Image string `json:"image,omitempty"` + // Volumes: the volumes attached to the server + Volumes map[string]*VolumeTemplate `json:"volumes,omitempty"` + // EnableIPv6: true if IPv6 is enabled on the server + EnableIPv6 bool `json:"enable_ipv6,omitempty"` + // PublicIP: the ID of the reserved IP to attach to the server + PublicIP *string `json:"public_ip,omitempty"` + // BootType: the boot type to use + // + // Default value: local + BootType *BootType `json:"boot_type,omitempty"` + // Bootscript: the bootscript ID to use when `boot_type` is set to `bootscript` + Bootscript *string `json:"bootscript,omitempty"` + // Organization: the server organization ID + // Precisely one of Organization, Project must be set. + Organization *string `json:"organization,omitempty"` + // Project: the server project ID + // Precisely one of Organization, Project must be set. + Project *string `json:"project,omitempty"` + // Tags: the server tags + Tags []string `json:"tags,omitempty"` + // SecurityGroup: the security group ID + SecurityGroup *string `json:"security_group,omitempty"` + // PlacementGroup: placement group ID if server must be part of a placement group + PlacementGroup *string `json:"placement_group,omitempty"` + // PrivateNetwork: private Network IDs if the server need to be part of one or more Private Networks + PrivateNetwork []string `json:"private_network,omitempty"` +} + +// createServer: create a server +func (s *API) createServer(req *CreateServerRequest, opts ...scw.RequestOption) (*CreateServerResponse, error) { + var err error + + defaultProject, exist := s.client.GetDefaultProjectID() + if exist && req.Organization == nil && req.Project == nil { + req.Project = &defaultProject + } + + defaultOrganization, exist := s.client.GetDefaultOrganizationID() + if exist && req.Organization == nil && req.Project == nil { + req.Organization = &defaultOrganization + } + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if req.Name == "" { + req.Name = namegenerator.GetRandomName("srv") + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "POST", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp CreateServerResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type DeleteServerRequest struct { + Zone scw.Zone `json:"-"` + + ServerID string `json:"-"` +} + +// DeleteServer: delete a server +// +// Delete a server with the given ID. +func (s *API) DeleteServer(req *DeleteServerRequest, opts ...scw.RequestOption) error { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ServerID) == "" { + return errors.New("field ServerID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "DELETE", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "", + Headers: http.Header{}, + } + + err = s.client.Do(scwReq, nil, opts...) + if err != nil { + return err + } + return nil +} + +type GetServerRequest struct { + Zone scw.Zone `json:"-"` + // ServerID: UUID of the server you want to get + ServerID string `json:"-"` +} + +// GetServer: get a server +// +// Get the details of a specified Server. +func (s *API) GetServer(req *GetServerRequest, opts ...scw.RequestOption) (*GetServerResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ServerID) == "" { + return nil, errors.New("field ServerID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "", + Headers: http.Header{}, + } + + var resp GetServerResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type setServerRequest struct { + Zone scw.Zone `json:"-"` + // ID: the server unique ID + ID string `json:"-"` + // Name: the server name + Name string `json:"name"` + // Organization: the server organization + Organization string `json:"organization"` + // Project: the server project ID + Project string `json:"project"` + // AllowedActions: provide as list of allowed actions on the server + AllowedActions []ServerAction `json:"allowed_actions"` + // Tags: the server associated tags + Tags []string `json:"tags"` + // CommercialType: the server commercial type (eg. GP1-M) + CommercialType string `json:"commercial_type"` + // CreationDate: the server creation date + CreationDate *time.Time `json:"creation_date"` + // DynamicIPRequired: true if a dynamic IP is required + DynamicIPRequired bool `json:"dynamic_ip_required"` + // EnableIPv6: true if IPv6 is enabled + EnableIPv6 bool `json:"enable_ipv6"` + // Hostname: the server host name + Hostname string `json:"hostname"` + // Image: provide information on the server image + Image *Image `json:"image"` + // Protected: the server protection option is activated + Protected bool `json:"protected"` + // PrivateIP: the server private IP address + PrivateIP *string `json:"private_ip"` + // PublicIP: information about the public IP + PublicIP *ServerIP `json:"public_ip"` + // ModificationDate: the server modification date + ModificationDate *time.Time `json:"modification_date"` + // State: the server state + // + // Default value: running + State ServerState `json:"state"` + // Location: the server location + Location *ServerLocation `json:"location"` + // IPv6: the server IPv6 address + IPv6 *ServerIPv6 `json:"ipv6"` + // Bootscript: the server bootscript + Bootscript *Bootscript `json:"bootscript"` + // BootType: the server boot type + // + // Default value: local + BootType BootType `json:"boot_type"` + // Volumes: the server volumes + Volumes map[string]*Volume `json:"volumes"` + // SecurityGroup: the server security group + SecurityGroup *SecurityGroupSummary `json:"security_group"` + // Maintenances: the server planned maintenances + Maintenances []*ServerMaintenance `json:"maintenances"` + // StateDetail: the server state_detail + StateDetail string `json:"state_detail"` + // Arch: the server arch + // + // Default value: x86_64 + Arch Arch `json:"arch"` + // PlacementGroup: the server placement group + PlacementGroup *PlacementGroup `json:"placement_group"` + // PrivateNics: the server private NICs + PrivateNics []*PrivateNIC `json:"private_nics"` +} + +func (s *API) setServer(req *setServerRequest, opts ...scw.RequestOption) (*setServerResponse, error) { + var err error + + if req.Project == "" { + defaultProject, _ := s.client.GetDefaultProjectID() + req.Project = defaultProject + } + + if req.Organization == "" { + defaultOrganization, _ := s.client.GetDefaultOrganizationID() + req.Organization = defaultOrganization + } + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ID) == "" { + return nil, errors.New("field ID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "PUT", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ID) + "", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp setServerResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type UpdateServerRequest struct { + Zone scw.Zone `json:"-"` + // ServerID: UUID of the server + ServerID string `json:"-"` + // Name: name of the server + Name *string `json:"name,omitempty"` + // BootType: + // + // Default value: local + BootType *BootType `json:"boot_type,omitempty"` + // Tags: tags of the server + Tags *[]string `json:"tags,omitempty"` + + Volumes *map[string]*VolumeTemplate `json:"volumes,omitempty"` + + Bootscript *string `json:"bootscript,omitempty"` + + DynamicIPRequired *bool `json:"dynamic_ip_required,omitempty"` + + EnableIPv6 *bool `json:"enable_ipv6,omitempty"` + + Protected *bool `json:"protected,omitempty"` + + SecurityGroup *SecurityGroupTemplate `json:"security_group,omitempty"` + // PlacementGroup: placement group ID if server must be part of a placement group + PlacementGroup *NullableStringValue `json:"placement_group,omitempty"` + // PrivateNics: the server private NICs + PrivateNics []*PrivateNIC `json:"private_nics,omitempty"` +} + +// updateServer: update a server +func (s *API) updateServer(req *UpdateServerRequest, opts ...scw.RequestOption) (*UpdateServerResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ServerID) == "" { + return nil, errors.New("field ServerID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "PATCH", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp UpdateServerResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type ListServerActionsRequest struct { + Zone scw.Zone `json:"-"` + + ServerID string `json:"-"` +} + +// ListServerActions: list server actions +// +// Liste all actions that can currently be performed on a server. +func (s *API) ListServerActions(req *ListServerActionsRequest, opts ...scw.RequestOption) (*ListServerActionsResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ServerID) == "" { + return nil, errors.New("field ServerID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/action", + Headers: http.Header{}, + } + + var resp ListServerActionsResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type ServerActionRequest struct { + Zone scw.Zone `json:"-"` + // ServerID: UUID of the server + ServerID string `json:"-"` + // Action: the action to perform on the server + // + // Default value: poweron + Action ServerAction `json:"action"` + // Name: the name of the backup you want to create + // + // The name of the backup you want to create. + // This field should only be specified when performing a backup action. + // + Name *string `json:"name,omitempty"` +} + +// ServerAction: perform action +// +// Perform power related actions on a server. Be wary that when terminating a server, all the attached volumes (local *and* block storage) are deleted. So, if you want to keep your local volumes, you must use the `archive` action instead of `terminate`. And if you want to keep block-storage volumes, **you must** detach it beforehand you issue the `terminate` call. For more information, read the [Volumes](#volumes-7e8a39) documentation. +func (s *API) ServerAction(req *ServerActionRequest, opts ...scw.RequestOption) (*ServerActionResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ServerID) == "" { + return nil, errors.New("field ServerID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "POST", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/action", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp ServerActionResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type ListServerUserDataRequest struct { + Zone scw.Zone `json:"-"` + // ServerID: UUID of the server + ServerID string `json:"-"` +} + +// ListServerUserData: list user data +// +// List all user data keys registered on a given server. +func (s *API) ListServerUserData(req *ListServerUserDataRequest, opts ...scw.RequestOption) (*ListServerUserDataResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ServerID) == "" { + return nil, errors.New("field ServerID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/user_data", + Headers: http.Header{}, + } + + var resp ListServerUserDataResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type DeleteServerUserDataRequest struct { + Zone scw.Zone `json:"-"` + // ServerID: UUID of the server + ServerID string `json:"-"` + // Key: key of the user data to delete + Key string `json:"-"` +} + +// DeleteServerUserData: delete user data +// +// Delete the given key from a server user data. +func (s *API) DeleteServerUserData(req *DeleteServerUserDataRequest, opts ...scw.RequestOption) error { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ServerID) == "" { + return errors.New("field ServerID cannot be empty in request") + } + + if fmt.Sprint(req.Key) == "" { + return errors.New("field Key cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "DELETE", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/user_data/" + fmt.Sprint(req.Key) + "", + Headers: http.Header{}, + } + + err = s.client.Do(scwReq, nil, opts...) + if err != nil { + return err + } + return nil +} + +type ListImagesRequest struct { + Zone scw.Zone `json:"-"` + + Organization *string `json:"-"` + + PerPage *uint32 `json:"-"` + + Page *int32 `json:"-"` + + Name *string `json:"-"` + + Public *bool `json:"-"` + + Arch *string `json:"-"` + + Project *string `json:"-"` +} + +// ListImages: list instance images +// +// List all images available in an account. +func (s *API) ListImages(req *ListImagesRequest, opts ...scw.RequestOption) (*ListImagesResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + defaultPerPage, exist := s.client.GetDefaultPageSize() + if (req.PerPage == nil || *req.PerPage == 0) && exist { + req.PerPage = &defaultPerPage + } + + query := url.Values{} + parameter.AddToQuery(query, "organization", req.Organization) + parameter.AddToQuery(query, "per_page", req.PerPage) + parameter.AddToQuery(query, "page", req.Page) + parameter.AddToQuery(query, "name", req.Name) + parameter.AddToQuery(query, "public", req.Public) + parameter.AddToQuery(query, "arch", req.Arch) + parameter.AddToQuery(query, "project", req.Project) + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/images", + Query: query, + Headers: http.Header{}, + } + + var resp ListImagesResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +// UnsafeGetTotalCount should not be used +// Internal usage only +func (r *ListImagesResponse) UnsafeGetTotalCount() uint32 { + return r.TotalCount +} + +// UnsafeAppend should not be used +// Internal usage only +func (r *ListImagesResponse) UnsafeAppend(res interface{}) (uint32, error) { + results, ok := res.(*ListImagesResponse) + if !ok { + return 0, errors.New("%T type cannot be appended to type %T", res, r) + } + + r.Images = append(r.Images, results.Images...) + r.TotalCount += uint32(len(results.Images)) + return uint32(len(results.Images)), nil +} + +type GetImageRequest struct { + Zone scw.Zone `json:"-"` + // ImageID: UUID of the image you want to get + ImageID string `json:"-"` +} + +// GetImage: get an instance image +// +// Get details of an image with the given ID. +func (s *API) GetImage(req *GetImageRequest, opts ...scw.RequestOption) (*GetImageResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ImageID) == "" { + return nil, errors.New("field ImageID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/images/" + fmt.Sprint(req.ImageID) + "", + Headers: http.Header{}, + } + + var resp GetImageResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type CreateImageRequest struct { + Zone scw.Zone `json:"-"` + // Name: name of the image + Name string `json:"name,omitempty"` + // RootVolume: UUID of the snapshot + RootVolume string `json:"root_volume,omitempty"` + // Arch: architecture of the image + // + // Default value: x86_64 + Arch Arch `json:"arch"` + // DefaultBootscript: default bootscript of the image + DefaultBootscript string `json:"default_bootscript,omitempty"` + // ExtraVolumes: additional volumes of the image + ExtraVolumes map[string]*VolumeTemplate `json:"extra_volumes,omitempty"` + // Organization: organization ID of the image + // Precisely one of Organization, Project must be set. + Organization *string `json:"organization,omitempty"` + // Project: project ID of the image + // Precisely one of Organization, Project must be set. + Project *string `json:"project,omitempty"` + // Public: true to create a public image + Public bool `json:"public,omitempty"` +} + +// CreateImage: create an instance image +func (s *API) CreateImage(req *CreateImageRequest, opts ...scw.RequestOption) (*CreateImageResponse, error) { + var err error + + defaultProject, exist := s.client.GetDefaultProjectID() + if exist && req.Organization == nil && req.Project == nil { + req.Project = &defaultProject + } + + defaultOrganization, exist := s.client.GetDefaultOrganizationID() + if exist && req.Organization == nil && req.Project == nil { + req.Organization = &defaultOrganization + } + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if req.Name == "" { + req.Name = namegenerator.GetRandomName("img") + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "POST", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/images", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp CreateImageResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type SetImageRequest struct { + Zone scw.Zone `json:"-"` + + ID string `json:"-"` + + Name string `json:"name"` + // Arch: + // + // Default value: x86_64 + Arch Arch `json:"arch"` + + CreationDate *time.Time `json:"creation_date"` + + ModificationDate *time.Time `json:"modification_date"` + + DefaultBootscript *Bootscript `json:"default_bootscript"` + + ExtraVolumes map[string]*Volume `json:"extra_volumes"` + + FromServer string `json:"from_server"` + + Organization string `json:"organization"` + + Public bool `json:"public"` + + RootVolume *VolumeSummary `json:"root_volume"` + // State: + // + // Default value: available + State ImageState `json:"state"` + + Project string `json:"project"` +} + +// setImage: update image +// +// Replace all image properties with an image message. +func (s *API) setImage(req *SetImageRequest, opts ...scw.RequestOption) (*setImageResponse, error) { + var err error + + if req.Project == "" { + defaultProject, _ := s.client.GetDefaultProjectID() + req.Project = defaultProject + } + + if req.Organization == "" { + defaultOrganization, _ := s.client.GetDefaultOrganizationID() + req.Organization = defaultOrganization + } + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ID) == "" { + return nil, errors.New("field ID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "PUT", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/images/" + fmt.Sprint(req.ID) + "", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp setImageResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type DeleteImageRequest struct { + Zone scw.Zone `json:"-"` + // ImageID: UUID of the image you want to delete + ImageID string `json:"-"` +} + +// DeleteImage: delete an instance image +// +// Delete the image with the given ID. +func (s *API) DeleteImage(req *DeleteImageRequest, opts ...scw.RequestOption) error { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ImageID) == "" { + return errors.New("field ImageID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "DELETE", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/images/" + fmt.Sprint(req.ImageID) + "", + Headers: http.Header{}, + } + + err = s.client.Do(scwReq, nil, opts...) + if err != nil { + return err + } + return nil +} + +type ListSnapshotsRequest struct { + Zone scw.Zone `json:"-"` + + Organization *string `json:"-"` + + PerPage *uint32 `json:"-"` + + Page *int32 `json:"-"` + + Name *string `json:"-"` + + Project *string `json:"-"` +} + +// ListSnapshots: list snapshots +func (s *API) ListSnapshots(req *ListSnapshotsRequest, opts ...scw.RequestOption) (*ListSnapshotsResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + defaultPerPage, exist := s.client.GetDefaultPageSize() + if (req.PerPage == nil || *req.PerPage == 0) && exist { + req.PerPage = &defaultPerPage + } + + query := url.Values{} + parameter.AddToQuery(query, "organization", req.Organization) + parameter.AddToQuery(query, "per_page", req.PerPage) + parameter.AddToQuery(query, "page", req.Page) + parameter.AddToQuery(query, "name", req.Name) + parameter.AddToQuery(query, "project", req.Project) + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/snapshots", + Query: query, + Headers: http.Header{}, + } + + var resp ListSnapshotsResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +// UnsafeGetTotalCount should not be used +// Internal usage only +func (r *ListSnapshotsResponse) UnsafeGetTotalCount() uint32 { + return r.TotalCount +} + +// UnsafeAppend should not be used +// Internal usage only +func (r *ListSnapshotsResponse) UnsafeAppend(res interface{}) (uint32, error) { + results, ok := res.(*ListSnapshotsResponse) + if !ok { + return 0, errors.New("%T type cannot be appended to type %T", res, r) + } + + r.Snapshots = append(r.Snapshots, results.Snapshots...) + r.TotalCount += uint32(len(results.Snapshots)) + return uint32(len(results.Snapshots)), nil +} + +type CreateSnapshotRequest struct { + Zone scw.Zone `json:"-"` + // Name: name of the snapshot + Name string `json:"name,omitempty"` + // VolumeID: UUID of the volume + VolumeID string `json:"volume_id,omitempty"` + + // Precisely one of Organization, Project must be set. + Organization *string `json:"organization,omitempty"` + + // Precisely one of Organization, Project must be set. + Project *string `json:"project,omitempty"` +} + +// CreateSnapshot: create a snapshot from a given volume +func (s *API) CreateSnapshot(req *CreateSnapshotRequest, opts ...scw.RequestOption) (*CreateSnapshotResponse, error) { + var err error + + defaultProject, exist := s.client.GetDefaultProjectID() + if exist && req.Organization == nil && req.Project == nil { + req.Project = &defaultProject + } + + defaultOrganization, exist := s.client.GetDefaultOrganizationID() + if exist && req.Organization == nil && req.Project == nil { + req.Organization = &defaultOrganization + } + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if req.Name == "" { + req.Name = namegenerator.GetRandomName("snp") + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "POST", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/snapshots", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp CreateSnapshotResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type GetSnapshotRequest struct { + Zone scw.Zone `json:"-"` + // SnapshotID: UUID of the snapshot you want to get + SnapshotID string `json:"-"` +} + +// GetSnapshot: get a snapshot +// +// Get details of a snapshot with the given ID. +func (s *API) GetSnapshot(req *GetSnapshotRequest, opts ...scw.RequestOption) (*GetSnapshotResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.SnapshotID) == "" { + return nil, errors.New("field SnapshotID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "", + Headers: http.Header{}, + } + + var resp GetSnapshotResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type SetSnapshotRequest struct { + Zone scw.Zone `json:"-"` + + ID string `json:"-"` + + Name string `json:"name"` + + Organization string `json:"organization"` + // VolumeType: + // + // Default value: l_ssd + VolumeType VolumeVolumeType `json:"volume_type"` + + Size scw.Size `json:"size"` + // State: + // + // Default value: available + State SnapshotState `json:"state"` + + BaseVolume *SnapshotBaseVolume `json:"base_volume"` + + CreationDate *time.Time `json:"creation_date"` + + ModificationDate *time.Time `json:"modification_date"` + + Project string `json:"project"` +} + +// setSnapshot: update snapshot +// +// Replace all snapshot properties with a snapshot message. +func (s *API) setSnapshot(req *SetSnapshotRequest, opts ...scw.RequestOption) (*setSnapshotResponse, error) { + var err error + + if req.Project == "" { + defaultProject, _ := s.client.GetDefaultProjectID() + req.Project = defaultProject + } + + if req.Organization == "" { + defaultOrganization, _ := s.client.GetDefaultOrganizationID() + req.Organization = defaultOrganization + } + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ID) == "" { + return nil, errors.New("field ID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "PUT", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/snapshots/" + fmt.Sprint(req.ID) + "", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp setSnapshotResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type DeleteSnapshotRequest struct { + Zone scw.Zone `json:"-"` + // SnapshotID: UUID of the snapshot you want to delete + SnapshotID string `json:"-"` +} + +// DeleteSnapshot: delete a snapshot +// +// Delete the snapshot with the given ID. +func (s *API) DeleteSnapshot(req *DeleteSnapshotRequest, opts ...scw.RequestOption) error { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.SnapshotID) == "" { + return errors.New("field SnapshotID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "DELETE", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/snapshots/" + fmt.Sprint(req.SnapshotID) + "", + Headers: http.Header{}, + } + + err = s.client.Do(scwReq, nil, opts...) + if err != nil { + return err + } + return nil +} + +type ListVolumesRequest struct { + Zone scw.Zone `json:"-"` + // VolumeType: filter by volume type + // + // Default value: l_ssd + VolumeType *VolumeVolumeType `json:"-"` + // PerPage: a positive integer lower or equal to 100 to select the number of items to return + // + // Default value: 50 + PerPage *uint32 `json:"-"` + // Page: a positive integer to choose the page to return + Page *int32 `json:"-"` + // Organization: filter volume by organization + Organization *string `json:"-"` + // Project: filter volume by project ID + Project *string `json:"-"` + // Name: filter volume by name (for eg. "vol" will return "myvolume" but not "data") + Name *string `json:"-"` +} + +// ListVolumes: list volumes +func (s *API) ListVolumes(req *ListVolumesRequest, opts ...scw.RequestOption) (*ListVolumesResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + defaultPerPage, exist := s.client.GetDefaultPageSize() + if (req.PerPage == nil || *req.PerPage == 0) && exist { + req.PerPage = &defaultPerPage + } + + query := url.Values{} + parameter.AddToQuery(query, "volume_type", req.VolumeType) + parameter.AddToQuery(query, "per_page", req.PerPage) + parameter.AddToQuery(query, "page", req.Page) + parameter.AddToQuery(query, "organization", req.Organization) + parameter.AddToQuery(query, "project", req.Project) + parameter.AddToQuery(query, "name", req.Name) + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/volumes", + Query: query, + Headers: http.Header{}, + } + + var resp ListVolumesResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +// UnsafeGetTotalCount should not be used +// Internal usage only +func (r *ListVolumesResponse) UnsafeGetTotalCount() uint32 { + return r.TotalCount +} + +// UnsafeAppend should not be used +// Internal usage only +func (r *ListVolumesResponse) UnsafeAppend(res interface{}) (uint32, error) { + results, ok := res.(*ListVolumesResponse) + if !ok { + return 0, errors.New("%T type cannot be appended to type %T", res, r) + } + + r.Volumes = append(r.Volumes, results.Volumes...) + r.TotalCount += uint32(len(results.Volumes)) + return uint32(len(results.Volumes)), nil +} + +type CreateVolumeRequest struct { + Zone scw.Zone `json:"-"` + + Name string `json:"name,omitempty"` + + // Precisely one of Organization, Project must be set. + Organization *string `json:"organization,omitempty"` + // VolumeType: + // + // Default value: l_ssd + VolumeType VolumeVolumeType `json:"volume_type"` + + // Precisely one of BaseSnapshot, BaseVolume, Size must be set. + Size *scw.Size `json:"size,omitempty"` + + // Precisely one of BaseSnapshot, BaseVolume, Size must be set. + BaseVolume *string `json:"base_volume,omitempty"` + + // Precisely one of BaseSnapshot, BaseVolume, Size must be set. + BaseSnapshot *string `json:"base_snapshot,omitempty"` + + // Precisely one of Organization, Project must be set. + Project *string `json:"project,omitempty"` +} + +// CreateVolume: create a volume +func (s *API) CreateVolume(req *CreateVolumeRequest, opts ...scw.RequestOption) (*CreateVolumeResponse, error) { + var err error + + defaultProject, exist := s.client.GetDefaultProjectID() + if exist && req.Organization == nil && req.Project == nil { + req.Project = &defaultProject + } + + defaultOrganization, exist := s.client.GetDefaultOrganizationID() + if exist && req.Organization == nil && req.Project == nil { + req.Organization = &defaultOrganization + } + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "POST", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/volumes", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp CreateVolumeResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type GetVolumeRequest struct { + Zone scw.Zone `json:"-"` + // VolumeID: UUID of the volume you want to get + VolumeID string `json:"-"` +} + +// GetVolume: get a volume +// +// Get details of a volume with the given ID. +func (s *API) GetVolume(req *GetVolumeRequest, opts ...scw.RequestOption) (*GetVolumeResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.VolumeID) == "" { + return nil, errors.New("field VolumeID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/volumes/" + fmt.Sprint(req.VolumeID) + "", + Headers: http.Header{}, + } + + var resp GetVolumeResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type UpdateVolumeRequest struct { + Zone scw.Zone `json:"-"` + // VolumeID: UUID of the volume + VolumeID string `json:"-"` + // Name: the volume name + Name *string `json:"name,omitempty"` + // Size: the volume disk size + Size *scw.Size `json:"size,omitempty"` +} + +// UpdateVolume: update a volume +// +// Replace name and/or size properties of given ID volume with the given value(s). Any volume name can be changed while, for now, only `b_ssd` volume growing is supported. +func (s *API) UpdateVolume(req *UpdateVolumeRequest, opts ...scw.RequestOption) (*UpdateVolumeResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.VolumeID) == "" { + return nil, errors.New("field VolumeID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "PATCH", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/volumes/" + fmt.Sprint(req.VolumeID) + "", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp UpdateVolumeResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type DeleteVolumeRequest struct { + Zone scw.Zone `json:"-"` + // VolumeID: UUID of the volume you want to delete + VolumeID string `json:"-"` +} + +// DeleteVolume: delete a volume +// +// Delete the volume with the given ID. +func (s *API) DeleteVolume(req *DeleteVolumeRequest, opts ...scw.RequestOption) error { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.VolumeID) == "" { + return errors.New("field VolumeID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "DELETE", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/volumes/" + fmt.Sprint(req.VolumeID) + "", + Headers: http.Header{}, + } + + err = s.client.Do(scwReq, nil, opts...) + if err != nil { + return err + } + return nil +} + +type ListSecurityGroupsRequest struct { + Zone scw.Zone `json:"-"` + // Name: name of the security group + Name *string `json:"-"` + // Organization: the security group organization ID + Organization *string `json:"-"` + // Project: the security group project ID + Project *string `json:"-"` + // PerPage: a positive integer lower or equal to 100 to select the number of items to return + // + // Default value: 50 + PerPage *uint32 `json:"-"` + // Page: a positive integer to choose the page to return + Page *int32 `json:"-"` +} + +// ListSecurityGroups: list security groups +// +// List all security groups available in an account. +func (s *API) ListSecurityGroups(req *ListSecurityGroupsRequest, opts ...scw.RequestOption) (*ListSecurityGroupsResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + defaultPerPage, exist := s.client.GetDefaultPageSize() + if (req.PerPage == nil || *req.PerPage == 0) && exist { + req.PerPage = &defaultPerPage + } + + query := url.Values{} + parameter.AddToQuery(query, "name", req.Name) + parameter.AddToQuery(query, "organization", req.Organization) + parameter.AddToQuery(query, "project", req.Project) + parameter.AddToQuery(query, "per_page", req.PerPage) + parameter.AddToQuery(query, "page", req.Page) + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups", + Query: query, + Headers: http.Header{}, + } + + var resp ListSecurityGroupsResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +// UnsafeGetTotalCount should not be used +// Internal usage only +func (r *ListSecurityGroupsResponse) UnsafeGetTotalCount() uint32 { + return r.TotalCount +} + +// UnsafeAppend should not be used +// Internal usage only +func (r *ListSecurityGroupsResponse) UnsafeAppend(res interface{}) (uint32, error) { + results, ok := res.(*ListSecurityGroupsResponse) + if !ok { + return 0, errors.New("%T type cannot be appended to type %T", res, r) + } + + r.SecurityGroups = append(r.SecurityGroups, results.SecurityGroups...) + r.TotalCount += uint32(len(results.SecurityGroups)) + return uint32(len(results.SecurityGroups)), nil +} + +type CreateSecurityGroupRequest struct { + Zone scw.Zone `json:"-"` + // Name: name of the security group + Name string `json:"name,omitempty"` + // Description: description of the security group + Description string `json:"description,omitempty"` + // Organization: organization the security group belongs to + // Precisely one of Organization, Project must be set. + Organization *string `json:"organization,omitempty"` + // Project: project ID the security group belong to + // Precisely one of Organization, Project must be set. + Project *string `json:"project,omitempty"` + // OrganizationDefault: whether this security group becomes the default security group for new instances + // + // Default value: false + // Precisely one of OrganizationDefault, ProjectDefault must be set. + OrganizationDefault *bool `json:"organization_default,omitempty"` + // ProjectDefault: whether this security group becomes the default security group for new instances + // + // Default value: false + // Precisely one of OrganizationDefault, ProjectDefault must be set. + ProjectDefault *bool `json:"project_default,omitempty"` + // Stateful: whether the security group is stateful or not + // + // Default value: false + Stateful bool `json:"stateful,omitempty"` + // InboundDefaultPolicy: default policy for inbound rules + // + // Default value: accept + InboundDefaultPolicy SecurityGroupPolicy `json:"inbound_default_policy"` + // OutboundDefaultPolicy: default policy for outbound rules + // + // Default value: accept + OutboundDefaultPolicy SecurityGroupPolicy `json:"outbound_default_policy"` +} + +// CreateSecurityGroup: create a security group +func (s *API) CreateSecurityGroup(req *CreateSecurityGroupRequest, opts ...scw.RequestOption) (*CreateSecurityGroupResponse, error) { + var err error + + defaultProject, exist := s.client.GetDefaultProjectID() + if exist && req.Organization == nil && req.Project == nil { + req.Project = &defaultProject + } + + defaultOrganization, exist := s.client.GetDefaultOrganizationID() + if exist && req.Organization == nil && req.Project == nil { + req.Organization = &defaultOrganization + } + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if req.Name == "" { + req.Name = namegenerator.GetRandomName("sg") + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "POST", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp CreateSecurityGroupResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type GetSecurityGroupRequest struct { + Zone scw.Zone `json:"-"` + // SecurityGroupID: UUID of the security group you want to get + SecurityGroupID string `json:"-"` +} + +// GetSecurityGroup: get a security group +// +// Get the details of a Security Group with the given ID. +func (s *API) GetSecurityGroup(req *GetSecurityGroupRequest, opts ...scw.RequestOption) (*GetSecurityGroupResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.SecurityGroupID) == "" { + return nil, errors.New("field SecurityGroupID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.SecurityGroupID) + "", + Headers: http.Header{}, + } + + var resp GetSecurityGroupResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type DeleteSecurityGroupRequest struct { + Zone scw.Zone `json:"-"` + // SecurityGroupID: UUID of the security group you want to delete + SecurityGroupID string `json:"-"` +} + +// DeleteSecurityGroup: delete a security group +func (s *API) DeleteSecurityGroup(req *DeleteSecurityGroupRequest, opts ...scw.RequestOption) error { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.SecurityGroupID) == "" { + return errors.New("field SecurityGroupID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "DELETE", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.SecurityGroupID) + "", + Headers: http.Header{}, + } + + err = s.client.Do(scwReq, nil, opts...) + if err != nil { + return err + } + return nil +} + +type setSecurityGroupRequest struct { + Zone scw.Zone `json:"-"` + + ID string `json:"-"` + + Name string `json:"name"` + + CreationDate *time.Time `json:"creation_date"` + + ModificationDate *time.Time `json:"modification_date"` + + Description string `json:"description"` + + EnableDefaultSecurity bool `json:"enable_default_security"` + // InboundDefaultPolicy: + // + // Default value: accept + InboundDefaultPolicy SecurityGroupPolicy `json:"inbound_default_policy"` + + Organization string `json:"organization"` + + OrganizationDefault bool `json:"organization_default"` + // OutboundDefaultPolicy: + // + // Default value: accept + OutboundDefaultPolicy SecurityGroupPolicy `json:"outbound_default_policy"` + + Servers []*ServerSummary `json:"servers"` + + Stateful bool `json:"stateful"` + + Project string `json:"project"` + + ProjectDefault bool `json:"project_default"` +} + +// setSecurityGroup: update a security group +// +// Replace all security group properties with a security group message. +func (s *API) setSecurityGroup(req *setSecurityGroupRequest, opts ...scw.RequestOption) (*setSecurityGroupResponse, error) { + var err error + + if req.Project == "" { + defaultProject, _ := s.client.GetDefaultProjectID() + req.Project = defaultProject + } + + if req.Organization == "" { + defaultOrganization, _ := s.client.GetDefaultOrganizationID() + req.Organization = defaultOrganization + } + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ID) == "" { + return nil, errors.New("field ID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "PUT", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.ID) + "", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp setSecurityGroupResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type ListSecurityGroupRulesRequest struct { + Zone scw.Zone `json:"-"` + // SecurityGroupID: UUID of the security group + SecurityGroupID string `json:"-"` + // PerPage: a positive integer lower or equal to 100 to select the number of items to return + // + // Default value: 50 + PerPage *uint32 `json:"-"` + // Page: a positive integer to choose the page to return + Page *int32 `json:"-"` +} + +// ListSecurityGroupRules: list rules +func (s *API) ListSecurityGroupRules(req *ListSecurityGroupRulesRequest, opts ...scw.RequestOption) (*ListSecurityGroupRulesResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + defaultPerPage, exist := s.client.GetDefaultPageSize() + if (req.PerPage == nil || *req.PerPage == 0) && exist { + req.PerPage = &defaultPerPage + } + + query := url.Values{} + parameter.AddToQuery(query, "per_page", req.PerPage) + parameter.AddToQuery(query, "page", req.Page) + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.SecurityGroupID) == "" { + return nil, errors.New("field SecurityGroupID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.SecurityGroupID) + "/rules", + Query: query, + Headers: http.Header{}, + } + + var resp ListSecurityGroupRulesResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +// UnsafeGetTotalCount should not be used +// Internal usage only +func (r *ListSecurityGroupRulesResponse) UnsafeGetTotalCount() uint32 { + return r.TotalCount +} + +// UnsafeAppend should not be used +// Internal usage only +func (r *ListSecurityGroupRulesResponse) UnsafeAppend(res interface{}) (uint32, error) { + results, ok := res.(*ListSecurityGroupRulesResponse) + if !ok { + return 0, errors.New("%T type cannot be appended to type %T", res, r) + } + + r.Rules = append(r.Rules, results.Rules...) + r.TotalCount += uint32(len(results.Rules)) + return uint32(len(results.Rules)), nil +} + +type CreateSecurityGroupRuleRequest struct { + Zone scw.Zone `json:"-"` + // SecurityGroupID: UUID of the security group + SecurityGroupID string `json:"-"` + // Protocol: + // + // Default value: TCP + Protocol SecurityGroupRuleProtocol `json:"protocol"` + // Direction: + // + // Default value: inbound + Direction SecurityGroupRuleDirection `json:"direction"` + // Action: + // + // Default value: accept + Action SecurityGroupRuleAction `json:"action"` + + IPRange scw.IPNet `json:"ip_range,omitempty"` + + DestPortFrom *uint32 `json:"dest_port_from,omitempty"` + + DestPortTo *uint32 `json:"dest_port_to,omitempty"` + + Position uint32 `json:"position,omitempty"` + + Editable bool `json:"editable,omitempty"` +} + +// CreateSecurityGroupRule: create rule +func (s *API) CreateSecurityGroupRule(req *CreateSecurityGroupRuleRequest, opts ...scw.RequestOption) (*CreateSecurityGroupRuleResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.SecurityGroupID) == "" { + return nil, errors.New("field SecurityGroupID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "POST", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.SecurityGroupID) + "/rules", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp CreateSecurityGroupRuleResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type DeleteSecurityGroupRuleRequest struct { + Zone scw.Zone `json:"-"` + + SecurityGroupID string `json:"-"` + + SecurityGroupRuleID string `json:"-"` +} + +// DeleteSecurityGroupRule: delete rule +// +// Delete a security group rule with the given ID. +func (s *API) DeleteSecurityGroupRule(req *DeleteSecurityGroupRuleRequest, opts ...scw.RequestOption) error { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.SecurityGroupID) == "" { + return errors.New("field SecurityGroupID cannot be empty in request") + } + + if fmt.Sprint(req.SecurityGroupRuleID) == "" { + return errors.New("field SecurityGroupRuleID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "DELETE", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.SecurityGroupID) + "/rules/" + fmt.Sprint(req.SecurityGroupRuleID) + "", + Headers: http.Header{}, + } + + err = s.client.Do(scwReq, nil, opts...) + if err != nil { + return err + } + return nil +} + +type GetSecurityGroupRuleRequest struct { + Zone scw.Zone `json:"-"` + + SecurityGroupID string `json:"-"` + + SecurityGroupRuleID string `json:"-"` +} + +// GetSecurityGroupRule: get rule +// +// Get details of a security group rule with the given ID. +func (s *API) GetSecurityGroupRule(req *GetSecurityGroupRuleRequest, opts ...scw.RequestOption) (*GetSecurityGroupRuleResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.SecurityGroupID) == "" { + return nil, errors.New("field SecurityGroupID cannot be empty in request") + } + + if fmt.Sprint(req.SecurityGroupRuleID) == "" { + return nil, errors.New("field SecurityGroupRuleID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.SecurityGroupID) + "/rules/" + fmt.Sprint(req.SecurityGroupRuleID) + "", + Headers: http.Header{}, + } + + var resp GetSecurityGroupRuleResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type setSecurityGroupRuleRequest struct { + Zone scw.Zone `json:"-"` + + SecurityGroupID string `json:"-"` + + SecurityGroupRuleID string `json:"-"` + + ID string `json:"id"` + // Protocol: + // + // Default value: TCP + Protocol SecurityGroupRuleProtocol `json:"protocol"` + // Direction: + // + // Default value: inbound + Direction SecurityGroupRuleDirection `json:"direction"` + // Action: + // + // Default value: accept + Action SecurityGroupRuleAction `json:"action"` + + IPRange scw.IPNet `json:"ip_range"` + + DestPortFrom *uint32 `json:"dest_port_from"` + + DestPortTo *uint32 `json:"dest_port_to"` + + Position uint32 `json:"position"` + + Editable bool `json:"editable"` +} + +// setSecurityGroupRule: update security group rule +func (s *API) setSecurityGroupRule(req *setSecurityGroupRuleRequest, opts ...scw.RequestOption) (*setSecurityGroupRuleResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.SecurityGroupID) == "" { + return nil, errors.New("field SecurityGroupID cannot be empty in request") + } + + if fmt.Sprint(req.SecurityGroupRuleID) == "" { + return nil, errors.New("field SecurityGroupRuleID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "PUT", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/security_groups/" + fmt.Sprint(req.SecurityGroupID) + "/rules/" + fmt.Sprint(req.SecurityGroupRuleID) + "", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp setSecurityGroupRuleResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type ListPlacementGroupsRequest struct { + Zone scw.Zone `json:"-"` + // PerPage: a positive integer lower or equal to 100 to select the number of items to return + // + // Default value: 50 + PerPage *uint32 `json:"-"` + // Page: a positive integer to choose the page to return + Page *int32 `json:"-"` + // Organization: list only placement groups of this organization + Organization *string `json:"-"` + // Project: list only placement groups of this project ID + Project *string `json:"-"` + // Name: filter placement groups by name (for eg. "cluster1" will return "cluster100" and "cluster1" but not "foo") + Name *string `json:"-"` +} + +// ListPlacementGroups: list placement groups +// +// List all placement groups. +func (s *API) ListPlacementGroups(req *ListPlacementGroupsRequest, opts ...scw.RequestOption) (*ListPlacementGroupsResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + defaultPerPage, exist := s.client.GetDefaultPageSize() + if (req.PerPage == nil || *req.PerPage == 0) && exist { + req.PerPage = &defaultPerPage + } + + query := url.Values{} + parameter.AddToQuery(query, "per_page", req.PerPage) + parameter.AddToQuery(query, "page", req.Page) + parameter.AddToQuery(query, "organization", req.Organization) + parameter.AddToQuery(query, "project", req.Project) + parameter.AddToQuery(query, "name", req.Name) + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups", + Query: query, + Headers: http.Header{}, + } + + var resp ListPlacementGroupsResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +// UnsafeGetTotalCount should not be used +// Internal usage only +func (r *ListPlacementGroupsResponse) UnsafeGetTotalCount() uint32 { + return r.TotalCount +} + +// UnsafeAppend should not be used +// Internal usage only +func (r *ListPlacementGroupsResponse) UnsafeAppend(res interface{}) (uint32, error) { + results, ok := res.(*ListPlacementGroupsResponse) + if !ok { + return 0, errors.New("%T type cannot be appended to type %T", res, r) + } + + r.PlacementGroups = append(r.PlacementGroups, results.PlacementGroups...) + r.TotalCount += uint32(len(results.PlacementGroups)) + return uint32(len(results.PlacementGroups)), nil +} + +type CreatePlacementGroupRequest struct { + Zone scw.Zone `json:"-"` + // Name: name of the placement group + Name string `json:"name,omitempty"` + + // Precisely one of Organization, Project must be set. + Organization *string `json:"organization,omitempty"` + + // Precisely one of Organization, Project must be set. + Project *string `json:"project,omitempty"` + // PolicyMode: + // + // Default value: optional + PolicyMode PlacementGroupPolicyMode `json:"policy_mode"` + // PolicyType: + // + // Default value: max_availability + PolicyType PlacementGroupPolicyType `json:"policy_type"` +} + +// CreatePlacementGroup: create a placement group +// +// Create a new placement group. +func (s *API) CreatePlacementGroup(req *CreatePlacementGroupRequest, opts ...scw.RequestOption) (*CreatePlacementGroupResponse, error) { + var err error + + defaultProject, exist := s.client.GetDefaultProjectID() + if exist && req.Organization == nil && req.Project == nil { + req.Project = &defaultProject + } + + defaultOrganization, exist := s.client.GetDefaultOrganizationID() + if exist && req.Organization == nil && req.Project == nil { + req.Organization = &defaultOrganization + } + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if req.Name == "" { + req.Name = namegenerator.GetRandomName("pg") + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "POST", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp CreatePlacementGroupResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type GetPlacementGroupRequest struct { + Zone scw.Zone `json:"-"` + // PlacementGroupID: UUID of the placement group you want to get + PlacementGroupID string `json:"-"` +} + +// GetPlacementGroup: get a placement group +// +// Get the given placement group. +func (s *API) GetPlacementGroup(req *GetPlacementGroupRequest, opts ...scw.RequestOption) (*GetPlacementGroupResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.PlacementGroupID) == "" { + return nil, errors.New("field PlacementGroupID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups/" + fmt.Sprint(req.PlacementGroupID) + "", + Headers: http.Header{}, + } + + var resp GetPlacementGroupResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type SetPlacementGroupRequest struct { + Zone scw.Zone `json:"-"` + + PlacementGroupID string `json:"-"` + + Name string `json:"name"` + + Organization string `json:"organization"` + // PolicyMode: + // + // Default value: optional + PolicyMode PlacementGroupPolicyMode `json:"policy_mode"` + // PolicyType: + // + // Default value: max_availability + PolicyType PlacementGroupPolicyType `json:"policy_type"` + + Project string `json:"project"` +} + +// SetPlacementGroup: set placement group +// +// Set all parameters of the given placement group. +func (s *API) SetPlacementGroup(req *SetPlacementGroupRequest, opts ...scw.RequestOption) (*SetPlacementGroupResponse, error) { + var err error + + if req.Project == "" { + defaultProject, _ := s.client.GetDefaultProjectID() + req.Project = defaultProject + } + + if req.Organization == "" { + defaultOrganization, _ := s.client.GetDefaultOrganizationID() + req.Organization = defaultOrganization + } + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.PlacementGroupID) == "" { + return nil, errors.New("field PlacementGroupID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "PUT", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups/" + fmt.Sprint(req.PlacementGroupID) + "", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp SetPlacementGroupResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type UpdatePlacementGroupRequest struct { + Zone scw.Zone `json:"-"` + // PlacementGroupID: UUID of the placement group + PlacementGroupID string `json:"-"` + // Name: name of the placement group + Name *string `json:"name,omitempty"` + // PolicyMode: + // + // Default value: optional + PolicyMode PlacementGroupPolicyMode `json:"policy_mode"` + // PolicyType: + // + // Default value: max_availability + PolicyType PlacementGroupPolicyType `json:"policy_type"` +} + +// UpdatePlacementGroup: update a placement group +// +// Update one or more parameter of the given placement group. +func (s *API) UpdatePlacementGroup(req *UpdatePlacementGroupRequest, opts ...scw.RequestOption) (*UpdatePlacementGroupResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.PlacementGroupID) == "" { + return nil, errors.New("field PlacementGroupID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "PATCH", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups/" + fmt.Sprint(req.PlacementGroupID) + "", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp UpdatePlacementGroupResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type DeletePlacementGroupRequest struct { + Zone scw.Zone `json:"-"` + // PlacementGroupID: UUID of the placement group you want to delete + PlacementGroupID string `json:"-"` +} + +// DeletePlacementGroup: delete the given placement group +// +// Delete the given placement group. +func (s *API) DeletePlacementGroup(req *DeletePlacementGroupRequest, opts ...scw.RequestOption) error { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.PlacementGroupID) == "" { + return errors.New("field PlacementGroupID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "DELETE", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups/" + fmt.Sprint(req.PlacementGroupID) + "", + Headers: http.Header{}, + } + + err = s.client.Do(scwReq, nil, opts...) + if err != nil { + return err + } + return nil +} + +type GetPlacementGroupServersRequest struct { + Zone scw.Zone `json:"-"` + + PlacementGroupID string `json:"-"` +} + +// GetPlacementGroupServers: get placement group servers +// +// Get all servers belonging to the given placement group. +func (s *API) GetPlacementGroupServers(req *GetPlacementGroupServersRequest, opts ...scw.RequestOption) (*GetPlacementGroupServersResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.PlacementGroupID) == "" { + return nil, errors.New("field PlacementGroupID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups/" + fmt.Sprint(req.PlacementGroupID) + "/servers", + Headers: http.Header{}, + } + + var resp GetPlacementGroupServersResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type SetPlacementGroupServersRequest struct { + Zone scw.Zone `json:"-"` + + PlacementGroupID string `json:"-"` + + Servers []string `json:"servers"` +} + +// SetPlacementGroupServers: set placement group servers +// +// Set all servers belonging to the given placement group. +func (s *API) SetPlacementGroupServers(req *SetPlacementGroupServersRequest, opts ...scw.RequestOption) (*SetPlacementGroupServersResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.PlacementGroupID) == "" { + return nil, errors.New("field PlacementGroupID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "PUT", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups/" + fmt.Sprint(req.PlacementGroupID) + "/servers", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp SetPlacementGroupServersResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type UpdatePlacementGroupServersRequest struct { + Zone scw.Zone `json:"-"` + // PlacementGroupID: UUID of the placement group + PlacementGroupID string `json:"-"` + + Servers []string `json:"servers,omitempty"` +} + +// UpdatePlacementGroupServers: update placement group servers +// +// Update all servers belonging to the given placement group. +func (s *API) UpdatePlacementGroupServers(req *UpdatePlacementGroupServersRequest, opts ...scw.RequestOption) (*UpdatePlacementGroupServersResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.PlacementGroupID) == "" { + return nil, errors.New("field PlacementGroupID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "PATCH", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/placement_groups/" + fmt.Sprint(req.PlacementGroupID) + "/servers", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp UpdatePlacementGroupServersResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type ListIPsRequest struct { + Zone scw.Zone `json:"-"` + // Project: the project ID the IPs are reserved in + Project *string `json:"-"` + // Organization: the organization ID the IPs are reserved in + Organization *string `json:"-"` + // Name: filter on the IP address (Works as a LIKE operation on the IP address) + Name *string `json:"-"` + // PerPage: a positive integer lower or equal to 100 to select the number of items to return + // + // Default value: 50 + PerPage *uint32 `json:"-"` + // Page: a positive integer to choose the page to return + Page *int32 `json:"-"` +} + +// ListIPs: list all flexible IPs +func (s *API) ListIPs(req *ListIPsRequest, opts ...scw.RequestOption) (*ListIPsResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + defaultPerPage, exist := s.client.GetDefaultPageSize() + if (req.PerPage == nil || *req.PerPage == 0) && exist { + req.PerPage = &defaultPerPage + } + + query := url.Values{} + parameter.AddToQuery(query, "project", req.Project) + parameter.AddToQuery(query, "organization", req.Organization) + parameter.AddToQuery(query, "name", req.Name) + parameter.AddToQuery(query, "per_page", req.PerPage) + parameter.AddToQuery(query, "page", req.Page) + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/ips", + Query: query, + Headers: http.Header{}, + } + + var resp ListIPsResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +// UnsafeGetTotalCount should not be used +// Internal usage only +func (r *ListIPsResponse) UnsafeGetTotalCount() uint32 { + return r.TotalCount +} + +// UnsafeAppend should not be used +// Internal usage only +func (r *ListIPsResponse) UnsafeAppend(res interface{}) (uint32, error) { + results, ok := res.(*ListIPsResponse) + if !ok { + return 0, errors.New("%T type cannot be appended to type %T", res, r) + } + + r.IPs = append(r.IPs, results.IPs...) + r.TotalCount += uint32(len(results.IPs)) + return uint32(len(results.IPs)), nil +} + +type CreateIPRequest struct { + Zone scw.Zone `json:"-"` + // Organization: the organization ID the IP is reserved in + // Precisely one of Organization, Project must be set. + Organization *string `json:"organization,omitempty"` + // Project: the project ID the IP is reserved in + // Precisely one of Organization, Project must be set. + Project *string `json:"project,omitempty"` + // Server: UUID of the server you want to attach the IP to + Server *string `json:"server,omitempty"` + // Tags: an array of keywords you want to tag this IP with + Tags []string `json:"tags,omitempty"` +} + +// CreateIP: reserve a flexible IP +func (s *API) CreateIP(req *CreateIPRequest, opts ...scw.RequestOption) (*CreateIPResponse, error) { + var err error + + defaultProject, exist := s.client.GetDefaultProjectID() + if exist && req.Organization == nil && req.Project == nil { + req.Project = &defaultProject + } + + defaultOrganization, exist := s.client.GetDefaultOrganizationID() + if exist && req.Organization == nil && req.Project == nil { + req.Organization = &defaultOrganization + } + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "POST", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/ips", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp CreateIPResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type GetIPRequest struct { + Zone scw.Zone `json:"-"` + // IP: the IP ID or address to get + IP string `json:"-"` +} + +// GetIP: get a flexible IP +// +// Get details of an IP with the given ID or address. +func (s *API) GetIP(req *GetIPRequest, opts ...scw.RequestOption) (*GetIPResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.IP) == "" { + return nil, errors.New("field IP cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/ips/" + fmt.Sprint(req.IP) + "", + Headers: http.Header{}, + } + + var resp GetIPResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type UpdateIPRequest struct { + Zone scw.Zone `json:"-"` + // IP: IP ID or IP address + IP string `json:"-"` + // Reverse: reverse domain name + Reverse *NullableStringValue `json:"reverse,omitempty"` + // Tags: an array of keywords you want to tag this IP with + Tags *[]string `json:"tags,omitempty"` + + Server *NullableStringValue `json:"server,omitempty"` +} + +// UpdateIP: update a flexible IP +func (s *API) UpdateIP(req *UpdateIPRequest, opts ...scw.RequestOption) (*UpdateIPResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.IP) == "" { + return nil, errors.New("field IP cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "PATCH", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/ips/" + fmt.Sprint(req.IP) + "", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp UpdateIPResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type DeleteIPRequest struct { + Zone scw.Zone `json:"-"` + // IP: the ID or the address of the IP to delete + IP string `json:"-"` +} + +// DeleteIP: delete a flexible IP +// +// Delete the IP with the given ID. +func (s *API) DeleteIP(req *DeleteIPRequest, opts ...scw.RequestOption) error { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.IP) == "" { + return errors.New("field IP cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "DELETE", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/ips/" + fmt.Sprint(req.IP) + "", + Headers: http.Header{}, + } + + err = s.client.Do(scwReq, nil, opts...) + if err != nil { + return err + } + return nil +} + +type ListPrivateNICsRequest struct { + Zone scw.Zone `json:"-"` + + ServerID string `json:"-"` +} + +// ListPrivateNICs: list all private NICs +// +// List all private NICs of a given server. +func (s *API) ListPrivateNICs(req *ListPrivateNICsRequest, opts ...scw.RequestOption) (*ListPrivateNICsResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ServerID) == "" { + return nil, errors.New("field ServerID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private_nics", + Headers: http.Header{}, + } + + var resp ListPrivateNICsResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type CreatePrivateNICRequest struct { + Zone scw.Zone `json:"-"` + + ServerID string `json:"-"` + + PrivateNetworkID string `json:"private_network_id,omitempty"` +} + +// CreatePrivateNIC: create a private NIC connecting a server to a private network +// +// Create a private NIC connecting a server to a private network. +func (s *API) CreatePrivateNIC(req *CreatePrivateNICRequest, opts ...scw.RequestOption) (*CreatePrivateNICResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ServerID) == "" { + return nil, errors.New("field ServerID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "POST", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private_nics", + Headers: http.Header{}, + } + + err = scwReq.SetBody(req) + if err != nil { + return nil, err + } + + var resp CreatePrivateNICResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type GetPrivateNICRequest struct { + Zone scw.Zone `json:"-"` + + ServerID string `json:"-"` + + PrivateNicID string `json:"-"` +} + +// GetPrivateNIC: get a private NIC +// +// Get private NIC properties. +func (s *API) GetPrivateNIC(req *GetPrivateNICRequest, opts ...scw.RequestOption) (*GetPrivateNICResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ServerID) == "" { + return nil, errors.New("field ServerID cannot be empty in request") + } + + if fmt.Sprint(req.PrivateNicID) == "" { + return nil, errors.New("field PrivateNicID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private_nics/" + fmt.Sprint(req.PrivateNicID) + "", + Headers: http.Header{}, + } + + var resp GetPrivateNICResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type DeletePrivateNICRequest struct { + Zone scw.Zone `json:"-"` + + ServerID string `json:"-"` + + PrivateNicID string `json:"-"` +} + +// DeletePrivateNIC: delete a private NIC +// +// Delete a private NIC. +func (s *API) DeletePrivateNIC(req *DeletePrivateNICRequest, opts ...scw.RequestOption) error { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ServerID) == "" { + return errors.New("field ServerID cannot be empty in request") + } + + if fmt.Sprint(req.PrivateNicID) == "" { + return errors.New("field PrivateNicID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "DELETE", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/private_nics/" + fmt.Sprint(req.PrivateNicID) + "", + Headers: http.Header{}, + } + + err = s.client.Do(scwReq, nil, opts...) + if err != nil { + return err + } + return nil +} + +type ListBootscriptsRequest struct { + Zone scw.Zone `json:"-"` + + Arch *string `json:"-"` + + Title *string `json:"-"` + + Default *bool `json:"-"` + + Public *bool `json:"-"` + + PerPage *uint32 `json:"-"` + + Page *int32 `json:"-"` +} + +// ListBootscripts: list bootscripts +func (s *API) ListBootscripts(req *ListBootscriptsRequest, opts ...scw.RequestOption) (*ListBootscriptsResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + defaultPerPage, exist := s.client.GetDefaultPageSize() + if (req.PerPage == nil || *req.PerPage == 0) && exist { + req.PerPage = &defaultPerPage + } + + query := url.Values{} + parameter.AddToQuery(query, "arch", req.Arch) + parameter.AddToQuery(query, "title", req.Title) + parameter.AddToQuery(query, "default", req.Default) + parameter.AddToQuery(query, "public", req.Public) + parameter.AddToQuery(query, "per_page", req.PerPage) + parameter.AddToQuery(query, "page", req.Page) + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/bootscripts", + Query: query, + Headers: http.Header{}, + } + + var resp ListBootscriptsResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +// UnsafeGetTotalCount should not be used +// Internal usage only +func (r *ListBootscriptsResponse) UnsafeGetTotalCount() uint32 { + return r.TotalCount +} + +// UnsafeAppend should not be used +// Internal usage only +func (r *ListBootscriptsResponse) UnsafeAppend(res interface{}) (uint32, error) { + results, ok := res.(*ListBootscriptsResponse) + if !ok { + return 0, errors.New("%T type cannot be appended to type %T", res, r) + } + + r.Bootscripts = append(r.Bootscripts, results.Bootscripts...) + r.TotalCount += uint32(len(results.Bootscripts)) + return uint32(len(results.Bootscripts)), nil +} + +type GetBootscriptRequest struct { + Zone scw.Zone `json:"-"` + + BootscriptID string `json:"-"` +} + +// GetBootscript: get bootscripts +// +// Get details of a bootscript with the given ID. +func (s *API) GetBootscript(req *GetBootscriptRequest, opts ...scw.RequestOption) (*GetBootscriptResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.BootscriptID) == "" { + return nil, errors.New("field BootscriptID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/bootscripts/" + fmt.Sprint(req.BootscriptID) + "", + Headers: http.Header{}, + } + + var resp GetBootscriptResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type GetDashboardRequest struct { + Zone scw.Zone `json:"-"` + + Organization *string `json:"-"` + + Project *string `json:"-"` +} + +func (s *API) GetDashboard(req *GetDashboardRequest, opts ...scw.RequestOption) (*GetDashboardResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + query := url.Values{} + parameter.AddToQuery(query, "organization", req.Organization) + parameter.AddToQuery(query, "project", req.Project) + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/dashboard", + Query: query, + Headers: http.Header{}, + } + + var resp GetDashboardResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/instance_utils.go b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/instance_utils.go new file mode 100644 index 000000000..5fa431e92 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/instance_utils.go @@ -0,0 +1,329 @@ +package instance + +import ( + "encoding/json" + "fmt" + "sync" + + "github.com/scaleway/scaleway-sdk-go/internal/errors" + "github.com/scaleway/scaleway-sdk-go/scw" +) + +var ( + resourceLock sync.Map +) + +// lockResource locks a resource from a specific resourceID +func lockResource(resourceID string) *sync.Mutex { + v, _ := resourceLock.LoadOrStore(resourceID, &sync.Mutex{}) + mutex := v.(*sync.Mutex) + mutex.Lock() + return mutex +} + +// lockServer locks a server from its zone and its ID +func lockServer(zone scw.Zone, serverID string) *sync.Mutex { + return lockResource(fmt.Sprint("server", zone, serverID)) +} + +// AttachIPRequest contains the parameters to attach an IP to a server +// +// Deprecated: UpdateIPRequest should be used instead +type AttachIPRequest struct { + Zone scw.Zone `json:"-"` + IP string `json:"-"` + ServerID string `json:"server_id"` +} + +// AttachIPResponse contains the updated IP after attaching +// +// Deprecated: UpdateIPResponse should be used instead +type AttachIPResponse struct { + IP *IP +} + +// AttachIP attaches an IP to a server. +// +// Deprecated: UpdateIP() should be used instead +func (s *API) AttachIP(req *AttachIPRequest, opts ...scw.RequestOption) (*AttachIPResponse, error) { + ipResponse, err := s.UpdateIP(&UpdateIPRequest{ + Zone: req.Zone, + IP: req.IP, + Server: &NullableStringValue{Value: req.ServerID}, + }) + if err != nil { + return nil, err + } + + return &AttachIPResponse{IP: ipResponse.IP}, nil +} + +// DetachIPRequest contains the parameters to detach an IP from a server +// +// Deprecated: UpdateIPRequest should be used instead +type DetachIPRequest struct { + Zone scw.Zone `json:"-"` + IP string `json:"-"` +} + +// DetachIPResponse contains the updated IP after detaching +// +// Deprecated: UpdateIPResponse should be used instead +type DetachIPResponse struct { + IP *IP +} + +// DetachIP detaches an IP from a server. +// +// Deprecated: UpdateIP() should be used instead +func (s *API) DetachIP(req *DetachIPRequest, opts ...scw.RequestOption) (*DetachIPResponse, error) { + ipResponse, err := s.UpdateIP(&UpdateIPRequest{ + Zone: req.Zone, + IP: req.IP, + Server: &NullableStringValue{Null: true}, + }) + if err != nil { + return nil, err + } + + return &DetachIPResponse{IP: ipResponse.IP}, nil +} + +// AttachVolumeRequest contains the parameters to attach a volume to a server +type AttachVolumeRequest struct { + Zone scw.Zone `json:"-"` + ServerID string `json:"-"` + VolumeID string `json:"-"` +} + +// AttachVolumeResponse contains the updated server after attaching a volume +type AttachVolumeResponse struct { + Server *Server `json:"-"` +} + +// volumesToVolumeTemplates converts a map of *Volume to a map of *VolumeTemplate +// so it can be used in a UpdateServer request +func volumesToVolumeTemplates(volumes map[string]*Volume) map[string]*VolumeTemplate { + volumeTemplates := map[string]*VolumeTemplate{} + for key, volume := range volumes { + volumeTemplates[key] = &VolumeTemplate{ID: volume.ID, Name: volume.Name} + } + return volumeTemplates +} + +// AttachVolume attaches a volume to a server +// +// Note: Implementation is thread-safe. +func (s *API) AttachVolume(req *AttachVolumeRequest, opts ...scw.RequestOption) (*AttachVolumeResponse, error) { + defer lockServer(req.Zone, req.ServerID).Unlock() + // get server with volumes + getServerResponse, err := s.GetServer(&GetServerRequest{ + Zone: req.Zone, + ServerID: req.ServerID, + }) + if err != nil { + return nil, err + } + volumes := getServerResponse.Server.Volumes + + newVolumes := volumesToVolumeTemplates(volumes) + + // add volume to volumes list + // We loop through all the possible volume keys (0 to len(volumes)) + // to find a non existing key and assign it to the requested volume. + // A key should always be found. However we return an error if no keys were found. + found := false + for i := 0; i <= len(volumes); i++ { + key := fmt.Sprintf("%d", i) + if _, ok := newVolumes[key]; !ok { + newVolumes[key] = &VolumeTemplate{ + ID: req.VolumeID, + // name is ignored on this PATCH + Name: req.VolumeID, + } + found = true + break + } + } + + if !found { + return nil, fmt.Errorf("could not find key to attach volume %s", req.VolumeID) + } + + // update server + updateServerResponse, err := s.updateServer(&UpdateServerRequest{ + Zone: req.Zone, + ServerID: req.ServerID, + Volumes: &newVolumes, + }) + if err != nil { + return nil, err + } + + return &AttachVolumeResponse{Server: updateServerResponse.Server}, nil +} + +// DetachVolumeRequest contains the parameters to detach a volume from a server +type DetachVolumeRequest struct { + Zone scw.Zone `json:"-"` + VolumeID string `json:"-"` +} + +// DetachVolumeResponse contains the updated server after detaching a volume +type DetachVolumeResponse struct { + Server *Server `json:"-"` +} + +// DetachVolume detaches a volume from a server +// +// Note: Implementation is thread-safe. +func (s *API) DetachVolume(req *DetachVolumeRequest, opts ...scw.RequestOption) (*DetachVolumeResponse, error) { + // get volume + getVolumeResponse, err := s.GetVolume(&GetVolumeRequest{ + Zone: req.Zone, + VolumeID: req.VolumeID, + }) + if err != nil { + return nil, err + } + if getVolumeResponse.Volume == nil { + return nil, errors.New("expected volume to have value in response") + } + if getVolumeResponse.Volume.Server == nil { + return nil, errors.New("volume should be attached to a server") + } + serverID := getVolumeResponse.Volume.Server.ID + + defer lockServer(req.Zone, serverID).Unlock() + // get server with volumes + getServerResponse, err := s.GetServer(&GetServerRequest{ + Zone: req.Zone, + ServerID: serverID, + }) + if err != nil { + return nil, err + } + volumes := getServerResponse.Server.Volumes + // remove volume from volumes list + for key, volume := range volumes { + if volume.ID == req.VolumeID { + delete(volumes, key) + } + } + + newVolumes := volumesToVolumeTemplates(volumes) + + // update server + updateServerResponse, err := s.updateServer(&UpdateServerRequest{ + Zone: req.Zone, + ServerID: serverID, + Volumes: &newVolumes, + }) + if err != nil { + return nil, err + } + + return &DetachVolumeResponse{Server: updateServerResponse.Server}, nil +} + +// UnsafeSetTotalCount should not be used +// Internal usage only +func (r *ListServersResponse) UnsafeSetTotalCount(totalCount int) { + r.TotalCount = uint32(totalCount) +} + +// UnsafeSetTotalCount should not be used +// Internal usage only +func (r *ListBootscriptsResponse) UnsafeSetTotalCount(totalCount int) { + r.TotalCount = uint32(totalCount) +} + +// UnsafeSetTotalCount should not be used +// Internal usage only +func (r *ListIPsResponse) UnsafeSetTotalCount(totalCount int) { + r.TotalCount = uint32(totalCount) +} + +// UnsafeSetTotalCount should not be used +// Internal usage only +func (r *ListSecurityGroupRulesResponse) UnsafeSetTotalCount(totalCount int) { + r.TotalCount = uint32(totalCount) +} + +// UnsafeSetTotalCount should not be used +// Internal usage only +func (r *ListSecurityGroupsResponse) UnsafeSetTotalCount(totalCount int) { + r.TotalCount = uint32(totalCount) +} + +// UnsafeSetTotalCount should not be used +// Internal usage only +func (r *ListServersTypesResponse) UnsafeSetTotalCount(totalCount int) { + r.TotalCount = uint32(totalCount) +} + +// UnsafeSetTotalCount should not be used +// Internal usage only +func (r *ListSnapshotsResponse) UnsafeSetTotalCount(totalCount int) { + r.TotalCount = uint32(totalCount) +} + +// UnsafeSetTotalCount should not be used +// Internal usage only +func (r *ListVolumesResponse) UnsafeSetTotalCount(totalCount int) { + r.TotalCount = uint32(totalCount) +} + +// UnsafeSetTotalCount should not be used +// Internal usage only +func (r *ListImagesResponse) UnsafeSetTotalCount(totalCount int) { + r.TotalCount = uint32(totalCount) +} + +// UnsafeGetTotalCount should not be used +// Internal usage only +func (r *ListServersTypesResponse) UnsafeGetTotalCount() uint32 { + return r.TotalCount +} + +// UnsafeAppend should not be used +// Internal usage only +func (r *ListServersTypesResponse) UnsafeAppend(res interface{}) (uint32, error) { + results, ok := res.(*ListServersTypesResponse) + if !ok { + return 0, errors.New("%T type cannot be appended to type %T", res, r) + } + + if r.Servers == nil { + r.Servers = make(map[string]*ServerType, len(results.Servers)) + } + + for name, serverType := range results.Servers { + r.Servers[name] = serverType + } + + r.TotalCount += uint32(len(results.Servers)) + return uint32(len(results.Servers)), nil +} + +func (v *NullableStringValue) UnmarshalJSON(b []byte) error { + if string(b) == "null" { + v.Null = true + return nil + } + + var tmp string + if err := json.Unmarshal(b, &tmp); err != nil { + return err + } + v.Null = false + v.Value = tmp + return nil +} + +func (v *NullableStringValue) MarshalJSON() ([]byte, error) { + if v.Null { + return []byte("null"), nil + } + return json.Marshal(v.Value) +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/security_group_utils.go b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/security_group_utils.go new file mode 100644 index 000000000..1645c54ec --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/security_group_utils.go @@ -0,0 +1,214 @@ +package instance + +import ( + "fmt" + + "github.com/scaleway/scaleway-sdk-go/internal/errors" + "github.com/scaleway/scaleway-sdk-go/scw" +) + +// UpdateSecurityGroupRequest contains the parameters to update a security group +type UpdateSecurityGroupRequest struct { + Zone scw.Zone `json:"-"` + SecurityGroupID string `json:"-"` + + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` + InboundDefaultPolicy *SecurityGroupPolicy `json:"inbound_default_policy,omitempty"` + OutboundDefaultPolicy *SecurityGroupPolicy `json:"outbound_default_policy,omitempty"` + Stateful *bool `json:"stateful,omitempty"` + OrganizationDefault *bool `json:"organization_default,omitempty"` + ProjectDefault *bool `json:"project_default,omitempty"` +} + +type UpdateSecurityGroupResponse struct { + SecurityGroup *SecurityGroup +} + +// UpdateSecurityGroup updates a security group. +func (s *API) UpdateSecurityGroup(req *UpdateSecurityGroupRequest, opts ...scw.RequestOption) (*UpdateSecurityGroupResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.SecurityGroupID) == "" { + return nil, errors.New("field SecurityGroupID cannot be empty in request") + } + + getSGResponse, err := s.GetSecurityGroup(&GetSecurityGroupRequest{ + Zone: req.Zone, + SecurityGroupID: req.SecurityGroupID, + }, opts...) + if err != nil { + return nil, err + } + + setRequest := &setSecurityGroupRequest{ + ID: getSGResponse.SecurityGroup.ID, + Name: getSGResponse.SecurityGroup.Name, + Description: getSGResponse.SecurityGroup.Description, + Organization: getSGResponse.SecurityGroup.Organization, + Project: getSGResponse.SecurityGroup.Project, + OrganizationDefault: getSGResponse.SecurityGroup.OrganizationDefault, + ProjectDefault: getSGResponse.SecurityGroup.ProjectDefault, + OutboundDefaultPolicy: getSGResponse.SecurityGroup.OutboundDefaultPolicy, + InboundDefaultPolicy: getSGResponse.SecurityGroup.InboundDefaultPolicy, + Stateful: getSGResponse.SecurityGroup.Stateful, + Zone: req.Zone, + EnableDefaultSecurity: getSGResponse.SecurityGroup.EnableDefaultSecurity, + CreationDate: getSGResponse.SecurityGroup.CreationDate, + ModificationDate: getSGResponse.SecurityGroup.ModificationDate, + Servers: getSGResponse.SecurityGroup.Servers, + } + + // Override the values that need to be updated + if req.Name != nil { + setRequest.Name = *req.Name + } + if req.Description != nil { + setRequest.Description = *req.Description + } + if req.InboundDefaultPolicy != nil { + setRequest.InboundDefaultPolicy = *req.InboundDefaultPolicy + } + if req.OutboundDefaultPolicy != nil { + setRequest.OutboundDefaultPolicy = *req.OutboundDefaultPolicy + } + if req.Stateful != nil { + setRequest.Stateful = *req.Stateful + } + if req.OrganizationDefault != nil { + setRequest.OrganizationDefault = *req.OrganizationDefault + } + if req.ProjectDefault != nil { + setRequest.ProjectDefault = *req.ProjectDefault + } + + setRes, err := s.setSecurityGroup(setRequest, opts...) + if err != nil { + return nil, err + } + + return &UpdateSecurityGroupResponse{ + SecurityGroup: setRes.SecurityGroup, + }, nil +} + +// UpdateSecurityGroupRuleRequest contains the parameters to update a security group rule +type UpdateSecurityGroupRuleRequest struct { + Zone scw.Zone `json:"-"` + SecurityGroupID string `json:"-"` + SecurityGroupRuleID string `json:"-"` + + Protocol *SecurityGroupRuleProtocol `json:"protocol"` + Direction *SecurityGroupRuleDirection `json:"direction"` + Action *SecurityGroupRuleAction `json:"action"` + IPRange *scw.IPNet `json:"ip_range"` + Position *uint32 `json:"position"` + + // If set to 0, DestPortFrom will be removed. + // See SecurityGroupRule.DestPortFrom for more information + DestPortFrom *uint32 `json:"dest_port_from"` + + // If set to 0, DestPortTo will be removed. + // See SecurityGroupRule.DestPortTo for more information + DestPortTo *uint32 `json:"dest_port_to"` +} + +type UpdateSecurityGroupRuleResponse struct { + Rule *SecurityGroupRule `json:"security_rule"` +} + +// UpdateSecurityGroupRule updates a security group. +func (s *API) UpdateSecurityGroupRule(req *UpdateSecurityGroupRuleRequest, opts ...scw.RequestOption) (*UpdateSecurityGroupRuleResponse, error) { + var err error + + if fmt.Sprint(req.Zone) == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + res, err := s.GetSecurityGroupRule(&GetSecurityGroupRuleRequest{ + SecurityGroupRuleID: req.SecurityGroupRuleID, + SecurityGroupID: req.SecurityGroupID, + Zone: req.Zone, + }) + if err != nil { + return nil, err + } + + setRequest := &setSecurityGroupRuleRequest{ + Zone: req.Zone, + SecurityGroupID: req.SecurityGroupID, + SecurityGroupRuleID: req.SecurityGroupRuleID, + ID: req.SecurityGroupRuleID, + Direction: res.Rule.Direction, + Protocol: res.Rule.Protocol, + DestPortFrom: res.Rule.DestPortFrom, + DestPortTo: res.Rule.DestPortTo, + IPRange: res.Rule.IPRange, + Action: res.Rule.Action, + Position: res.Rule.Position, + Editable: res.Rule.Editable, + } + + // Override the values that need to be updated + if req.Action != nil { + setRequest.Action = *req.Action + } + if req.IPRange != nil { + setRequest.IPRange = *req.IPRange + } + if req.DestPortTo != nil { + if *req.DestPortTo > 0 { + setRequest.DestPortTo = req.DestPortTo + } else { + setRequest.DestPortTo = nil + } + } + if req.DestPortFrom != nil { + if *req.DestPortFrom > 0 { + setRequest.DestPortFrom = req.DestPortFrom + } else { + setRequest.DestPortFrom = nil + } + } + if req.DestPortFrom != nil && req.DestPortTo != nil && *req.DestPortFrom == *req.DestPortTo { + setRequest.DestPortTo = nil + } + if req.Protocol != nil { + setRequest.Protocol = *req.Protocol + } + if req.Direction != nil { + setRequest.Direction = *req.Direction + } + if req.Position != nil { + setRequest.Position = *req.Position + } + + // When we use ICMP protocol portFrom and portTo should be set to nil + if req.Protocol != nil && *req.Protocol == SecurityGroupRuleProtocolICMP { + setRequest.DestPortFrom = nil + setRequest.DestPortTo = nil + } + + resp, err := s.setSecurityGroupRule(setRequest) + if err != nil { + return nil, err + } + + return &UpdateSecurityGroupRuleResponse{ + Rule: resp.Rule, + }, nil +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/server_utils.go b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/server_utils.go new file mode 100644 index 000000000..88f958351 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/server_utils.go @@ -0,0 +1,409 @@ +package instance + +import ( + "bytes" + "fmt" + "io" + "net/http" + "time" + + "github.com/scaleway/scaleway-sdk-go/api/marketplace/v1" + "github.com/scaleway/scaleway-sdk-go/internal/async" + "github.com/scaleway/scaleway-sdk-go/internal/errors" + "github.com/scaleway/scaleway-sdk-go/scw" + "github.com/scaleway/scaleway-sdk-go/validation" +) + +const ( + defaultTimeout = 5 * time.Minute + defaultRetryInterval = 5 * time.Second +) + +// CreateServer creates a server. +func (s *API) CreateServer(req *CreateServerRequest, opts ...scw.RequestOption) (*CreateServerResponse, error) { + // If image is not a UUID we try to fetch it from marketplace. + if req.Image != "" && !validation.IsUUID(req.Image) { + apiMarketplace := marketplace.NewAPI(s.client) + imageID, err := apiMarketplace.GetLocalImageIDByLabel(&marketplace.GetLocalImageIDByLabelRequest{ + ImageLabel: req.Image, + Zone: req.Zone, + CommercialType: req.CommercialType, + }) + if err != nil { + return nil, err + } + req.Image = imageID + } + + return s.createServer(req, opts...) +} + +// UpdateServer updates a server. +// +// Note: Implementation is thread-safe. +func (s *API) UpdateServer(req *UpdateServerRequest, opts ...scw.RequestOption) (*UpdateServerResponse, error) { + defer lockServer(req.Zone, req.ServerID).Unlock() + return s.updateServer(req, opts...) +} + +// WaitForServerRequest is used by WaitForServer method. +type WaitForServerRequest struct { + ServerID string + Zone scw.Zone + Timeout *time.Duration + RetryInterval *time.Duration +} + +// WaitForServer wait for the server to be in a "terminal state" before returning. +// This function can be used to wait for a server to be started for example. +func (s *API) WaitForServer(req *WaitForServerRequest) (*Server, error) { + timeout := defaultTimeout + if req.Timeout != nil { + timeout = *req.Timeout + } + retryInterval := defaultRetryInterval + if req.RetryInterval != nil { + retryInterval = *req.RetryInterval + } + + terminalStatus := map[ServerState]struct{}{ + ServerStateStopped: {}, + ServerStateStoppedInPlace: {}, + ServerStateLocked: {}, + ServerStateRunning: {}, + } + + server, err := async.WaitSync(&async.WaitSyncConfig{ + Get: func() (interface{}, bool, error) { + res, err := s.GetServer(&GetServerRequest{ + ServerID: req.ServerID, + Zone: req.Zone, + }) + + if err != nil { + return nil, false, err + } + _, isTerminal := terminalStatus[res.Server.State] + + return res.Server, isTerminal, err + }, + Timeout: timeout, + IntervalStrategy: async.LinearIntervalStrategy(retryInterval), + }) + if err != nil { + return nil, errors.Wrap(err, "waiting for server failed") + } + return server.(*Server), nil +} + +// ServerActionAndWaitRequest is used by ServerActionAndWait method. +type ServerActionAndWaitRequest struct { + ServerID string + Zone scw.Zone + Action ServerAction + + // Timeout: maximum time to wait before (default: 5 minutes) + Timeout *time.Duration + RetryInterval *time.Duration +} + +// ServerActionAndWait start an action and wait for the server to be in the correct "terminal state" +// expected by this action. +func (s *API) ServerActionAndWait(req *ServerActionAndWaitRequest) error { + timeout := defaultTimeout + if req.Timeout != nil { + timeout = *req.Timeout + } + retryInterval := defaultRetryInterval + if req.RetryInterval != nil { + retryInterval = *req.RetryInterval + } + + _, err := s.ServerAction(&ServerActionRequest{ + Zone: req.Zone, + ServerID: req.ServerID, + Action: req.Action, + }) + if err != nil { + return err + } + + finalServer, err := s.WaitForServer(&WaitForServerRequest{ + Zone: req.Zone, + ServerID: req.ServerID, + Timeout: &timeout, + RetryInterval: &retryInterval, + }) + if err != nil { + return err + } + + // check the action was properly executed + expectedState := ServerState("unknown") + switch req.Action { + case ServerActionPoweron, ServerActionReboot: + expectedState = ServerStateRunning + case ServerActionPoweroff: + expectedState = ServerStateStopped + case ServerActionStopInPlace: + expectedState = ServerStateStoppedInPlace + } + + // backup can be performed from any state + if expectedState != ServerState("unknown") && finalServer.State != expectedState { + return errors.New("expected state %s but found %s: %s", expectedState, finalServer.State, finalServer.StateDetail) + } + + return nil +} + +// GetServerTypeRequest is used by GetServerType. +type GetServerTypeRequest struct { + Zone scw.Zone + Name string +} + +// GetServerType get server type info by it's name. +func (s *API) GetServerType(req *GetServerTypeRequest) (*ServerType, error) { + res, err := s.ListServersTypes(&ListServersTypesRequest{ + Zone: req.Zone, + }, scw.WithAllPages()) + + if err != nil { + return nil, err + } + + if serverType, exist := res.Servers[req.Name]; exist { + return serverType, nil + } + + return nil, errors.New("could not find server type %q", req.Name) +} + +// GetServerUserDataRequest is used by GetServerUserData method. +type GetServerUserDataRequest struct { + Zone scw.Zone `json:"-"` + ServerID string `json:"-"` + + // Key defines the user data key to get. + Key string `json:"-"` +} + +// GetServerUserData gets the content of a user data on a server for the given key. +func (s *API) GetServerUserData(req *GetServerUserDataRequest, opts ...scw.RequestOption) (io.Reader, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ServerID) == "" { + return nil, errors.New("field ServerID cannot be empty in request") + } + + if fmt.Sprint(req.Key) == "" { + return nil, errors.New("field Key cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/user_data/" + fmt.Sprint(req.Key), + Headers: http.Header{}, + } + + res := &bytes.Buffer{} + + err = s.client.Do(scwReq, res, opts...) + if err != nil { + return nil, err + } + + return res, nil +} + +// SetServerUserDataRequest is used by SetServerUserData method. +type SetServerUserDataRequest struct { + Zone scw.Zone `json:"-"` + ServerID string `json:"-"` + + // Key defines the user data key to set. + Key string `json:"-"` + + // Content defines the data to set. + Content io.Reader +} + +// SetServerUserData sets the content of a user data on a server for the given key. +func (s *API) SetServerUserData(req *SetServerUserDataRequest, opts ...scw.RequestOption) error { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ServerID) == "" { + return errors.New("field ServerID cannot be empty in request") + } + + if fmt.Sprint(req.Key) == "" { + return errors.New("field Key cannot be empty in request") + } + + if req.Content == nil { + return errors.New("field Content cannot be nil in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "PATCH", + Path: "/instance/v1/zones/" + fmt.Sprint(req.Zone) + "/servers/" + fmt.Sprint(req.ServerID) + "/user_data/" + fmt.Sprint(req.Key), + Headers: http.Header{}, + } + + err = scwReq.SetBody(req.Content) + if err != nil { + return err + } + + err = s.client.Do(scwReq, nil, opts...) + if err != nil { + return err + } + + return nil +} + +// GetAllServerUserDataRequest is used by GetAllServerUserData method. +type GetAllServerUserDataRequest struct { + Zone scw.Zone `json:"-"` + ServerID string `json:"-"` +} + +// GetAllServerUserDataResponse is used by GetAllServerUserData method. +type GetAllServerUserDataResponse struct { + UserData map[string]io.Reader `json:"-"` +} + +// GetAllServerUserData gets all user data on a server. +func (s *API) GetAllServerUserData(req *GetAllServerUserDataRequest, opts ...scw.RequestOption) (*GetAllServerUserDataResponse, error) { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return nil, errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ServerID) == "" { + return nil, errors.New("field ServerID cannot be empty in request") + } + + // get all user data keys + allUserDataRes, err := s.ListServerUserData(&ListServerUserDataRequest{ + Zone: req.Zone, + ServerID: req.ServerID, + }) + if err != nil { + return nil, err + } + + res := &GetAllServerUserDataResponse{ + UserData: make(map[string]io.Reader, len(allUserDataRes.UserData)), + } + + // build a map with all user data + for _, key := range allUserDataRes.UserData { + value, err := s.GetServerUserData(&GetServerUserDataRequest{ + Zone: req.Zone, + ServerID: req.ServerID, + Key: key, + }) + if err != nil { + return nil, err + } + res.UserData[key] = value + } + + return res, nil +} + +// SetAllServerUserDataRequest is used by SetAllServerUserData method. +type SetAllServerUserDataRequest struct { + Zone scw.Zone `json:"-"` + ServerID string `json:"-"` + + // UserData defines all user data that will be set to the server. + // This map is idempotent, it means that all the current data will be overwritten and + // all keys not present in this map will be deleted.. All data will be removed if this map is nil. + UserData map[string]io.Reader `json:"-"` +} + +// SetAllServerUserData sets all user data on a server. +func (s *API) SetAllServerUserData(req *SetAllServerUserDataRequest, opts ...scw.RequestOption) error { + var err error + + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + if fmt.Sprint(req.Zone) == "" { + return errors.New("field Zone cannot be empty in request") + } + + if fmt.Sprint(req.ServerID) == "" { + return errors.New("field ServerID cannot be empty in request") + } + + // get all current user data keys + allUserDataRes, err := s.ListServerUserData(&ListServerUserDataRequest{ + Zone: req.Zone, + ServerID: req.ServerID, + }) + if err != nil { + return err + } + + // delete all current user data + for _, key := range allUserDataRes.UserData { + _, exist := req.UserData[key] + if exist { + continue + } + err := s.DeleteServerUserData(&DeleteServerUserDataRequest{ + Zone: req.Zone, + ServerID: req.ServerID, + Key: key, + }) + if err != nil { + return err + } + } + + // set all new user data + for key, value := range req.UserData { + err := s.SetServerUserData(&SetServerUserDataRequest{ + Zone: req.Zone, + ServerID: req.ServerID, + Key: key, + Content: value, + }) + if err != nil { + return err + } + } + + return nil +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/snapshot_utils.go b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/snapshot_utils.go new file mode 100644 index 000000000..683b0056a --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/snapshot_utils.go @@ -0,0 +1,56 @@ +package instance + +import ( + "time" + + "github.com/scaleway/scaleway-sdk-go/internal/async" + "github.com/scaleway/scaleway-sdk-go/internal/errors" + "github.com/scaleway/scaleway-sdk-go/scw" +) + +// WaitForImageRequest is used by WaitForImage method. +type WaitForSnapshotRequest struct { + SnapshotID string + Zone scw.Zone + Timeout *time.Duration + RetryInterval *time.Duration +} + +// WaitForSnapshot wait for the snapshot to be in a "terminal state" before returning. +func (s *API) WaitForSnapshot(req *WaitForSnapshotRequest) (*Snapshot, error) { + timeout := defaultTimeout + if req.Timeout != nil { + timeout = *req.Timeout + } + retryInterval := defaultRetryInterval + if req.RetryInterval != nil { + retryInterval = *req.RetryInterval + } + + terminalStatus := map[SnapshotState]struct{}{ + SnapshotStateAvailable: {}, + SnapshotStateError: {}, + } + + snapshot, err := async.WaitSync(&async.WaitSyncConfig{ + Get: func() (interface{}, bool, error) { + res, err := s.GetSnapshot(&GetSnapshotRequest{ + SnapshotID: req.SnapshotID, + Zone: req.Zone, + }) + + if err != nil { + return nil, false, err + } + _, isTerminal := terminalStatus[res.Snapshot.State] + + return res.Snapshot, isTerminal, err + }, + Timeout: timeout, + IntervalStrategy: async.LinearIntervalStrategy(retryInterval), + }) + if err != nil { + return nil, errors.Wrap(err, "waiting for snapshot failed") + } + return snapshot.(*Snapshot), nil +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/volume_utils.go b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/volume_utils.go new file mode 100644 index 000000000..1f9b7ad60 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/api/instance/v1/volume_utils.go @@ -0,0 +1,56 @@ +package instance + +import ( + "time" + + "github.com/scaleway/scaleway-sdk-go/internal/async" + "github.com/scaleway/scaleway-sdk-go/internal/errors" + "github.com/scaleway/scaleway-sdk-go/scw" +) + +// WaitForImageRequest is used by WaitForImage method. +type WaitForVolumeRequest struct { + VolumeID string + Zone scw.Zone + Timeout *time.Duration + RetryInterval *time.Duration +} + +// WaitForSnapshot wait for the snapshot to be in a "terminal state" before returning. +func (s *API) WaitForVolume(req *WaitForVolumeRequest) (*Volume, error) { + timeout := defaultTimeout + if req.Timeout != nil { + timeout = *req.Timeout + } + retryInterval := defaultRetryInterval + if req.RetryInterval != nil { + retryInterval = *req.RetryInterval + } + + terminalStatus := map[VolumeState]struct{}{ + VolumeStateAvailable: {}, + VolumeStateError: {}, + } + + volume, err := async.WaitSync(&async.WaitSyncConfig{ + Get: func() (interface{}, bool, error) { + res, err := s.GetVolume(&GetVolumeRequest{ + VolumeID: req.VolumeID, + Zone: req.Zone, + }) + + if err != nil { + return nil, false, err + } + _, isTerminal := terminalStatus[res.Volume.State] + + return res.Volume, isTerminal, err + }, + Timeout: timeout, + IntervalStrategy: async.LinearIntervalStrategy(retryInterval), + }) + if err != nil { + return nil, errors.Wrap(err, "waiting for volume failed") + } + return volume.(*Volume), nil +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/api/marketplace/v1/marketplace_sdk.go b/vendor/github.com/scaleway/scaleway-sdk-go/api/marketplace/v1/marketplace_sdk.go new file mode 100644 index 000000000..e82f62702 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/api/marketplace/v1/marketplace_sdk.go @@ -0,0 +1,304 @@ +// This file was automatically generated. DO NOT EDIT. +// If you have any remark or suggestion do not hesitate to open an issue. + +// Package marketplace provides methods and message types of the marketplace v1 API. +package marketplace + +import ( + "bytes" + "encoding/json" + "fmt" + "net" + "net/http" + "net/url" + "strings" + "time" + + "github.com/scaleway/scaleway-sdk-go/internal/errors" + "github.com/scaleway/scaleway-sdk-go/internal/marshaler" + "github.com/scaleway/scaleway-sdk-go/internal/parameter" + "github.com/scaleway/scaleway-sdk-go/namegenerator" + "github.com/scaleway/scaleway-sdk-go/scw" +) + +// always import dependencies +var ( + _ fmt.Stringer + _ json.Unmarshaler + _ url.URL + _ net.IP + _ http.Header + _ bytes.Reader + _ time.Time + _ = strings.Join + + _ scw.ScalewayRequest + _ marshaler.Duration + _ scw.File + _ = parameter.AddToQuery + _ = namegenerator.GetRandomName +) + +// API: marketplace API +type API struct { + client *scw.Client +} + +// NewAPI returns a API object from a Scaleway client. +func NewAPI(client *scw.Client) *API { + return &API{ + client: client, + } +} + +type GetImageResponse struct { + Image *Image `json:"image"` +} + +type GetServiceInfoResponse struct { + API string `json:"api"` + + Description string `json:"description"` + + Version string `json:"version"` +} + +type GetVersionResponse struct { + Version *Version `json:"version"` +} + +// Image: image +type Image struct { + // ID: UUID of this image + ID string `json:"id"` + // Name: name of the image + Name string `json:"name"` + // Description: text description of this image + Description string `json:"description"` + // Logo: URL of this image's logo + Logo string `json:"logo"` + // Categories: list of categories this image belongs to + Categories []string `json:"categories"` + // CreationDate: creation date of this image + CreationDate *time.Time `json:"creation_date"` + // ModificationDate: date of the last modification of this image + ModificationDate *time.Time `json:"modification_date"` + // ValidUntil: expiration date of this image + ValidUntil *time.Time `json:"valid_until"` + // Label: label of this image + Label string `json:"label"` + // Versions: list of versions of this image + Versions []*Version `json:"versions"` + // Organization: organization this image belongs to + Organization *Organization `json:"organization"` + + CurrentPublicVersion string `json:"current_public_version"` +} + +type ListImagesResponse struct { + Images []*Image `json:"images"` + + TotalCount uint32 `json:"total_count"` +} + +type ListVersionsResponse struct { + Versions []*Version `json:"versions"` + + TotalCount uint32 `json:"total_count"` +} + +// LocalImage: local image +type LocalImage struct { + // ID: UUID of this local image + ID string `json:"id"` + // CompatibleCommercialTypes: list of all commercial types that are compatible with this local image + CompatibleCommercialTypes []string `json:"compatible_commercial_types"` + // Arch: supported architecture for this local image + Arch string `json:"arch"` + // Zone: availability Zone where this local image is available + Zone scw.Zone `json:"zone"` +} + +type Organization struct { + ID string `json:"id"` + + Name string `json:"name"` +} + +// Version: version +type Version struct { + // ID: UUID of this version + ID string `json:"id"` + // Name: name of this version + Name string `json:"name"` + // CreationDate: creation date of this image version + CreationDate *time.Time `json:"creation_date"` + // ModificationDate: date of the last modification of this version + ModificationDate *time.Time `json:"modification_date"` + // LocalImages: list of local images available in this version + LocalImages []*LocalImage `json:"local_images"` +} + +// Service API + +type GetServiceInfoRequest struct { +} + +func (s *API) GetServiceInfo(req *GetServiceInfoRequest, opts ...scw.RequestOption) (*GetServiceInfoResponse, error) { + var err error + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/marketplace/v1", + Headers: http.Header{}, + } + + var resp GetServiceInfoResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type ListImagesRequest struct { + // PerPage: a positive integer lower or equal to 100 to select the number of items to display + PerPage *uint32 `json:"-"` + // Page: a positive integer to choose the page to display + Page *int32 `json:"-"` +} + +// ListImages: list marketplace images +func (s *API) ListImages(req *ListImagesRequest, opts ...scw.RequestOption) (*ListImagesResponse, error) { + var err error + + defaultPerPage, exist := s.client.GetDefaultPageSize() + if (req.PerPage == nil || *req.PerPage == 0) && exist { + req.PerPage = &defaultPerPage + } + + query := url.Values{} + parameter.AddToQuery(query, "per_page", req.PerPage) + parameter.AddToQuery(query, "page", req.Page) + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/marketplace/v1/images", + Query: query, + Headers: http.Header{}, + } + + var resp ListImagesResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +// UnsafeGetTotalCount should not be used +// Internal usage only +func (r *ListImagesResponse) UnsafeGetTotalCount() uint32 { + return r.TotalCount +} + +// UnsafeAppend should not be used +// Internal usage only +func (r *ListImagesResponse) UnsafeAppend(res interface{}) (uint32, error) { + results, ok := res.(*ListImagesResponse) + if !ok { + return 0, errors.New("%T type cannot be appended to type %T", res, r) + } + + r.Images = append(r.Images, results.Images...) + r.TotalCount += uint32(len(results.Images)) + return uint32(len(results.Images)), nil +} + +type GetImageRequest struct { + // ImageID: display the image name + ImageID string `json:"-"` +} + +// GetImage: get a specific marketplace image +func (s *API) GetImage(req *GetImageRequest, opts ...scw.RequestOption) (*GetImageResponse, error) { + var err error + + if fmt.Sprint(req.ImageID) == "" { + return nil, errors.New("field ImageID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/marketplace/v1/images/" + fmt.Sprint(req.ImageID) + "", + Headers: http.Header{}, + } + + var resp GetImageResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type ListVersionsRequest struct { + ImageID string `json:"-"` +} + +func (s *API) ListVersions(req *ListVersionsRequest, opts ...scw.RequestOption) (*ListVersionsResponse, error) { + var err error + + if fmt.Sprint(req.ImageID) == "" { + return nil, errors.New("field ImageID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/marketplace/v1/images/" + fmt.Sprint(req.ImageID) + "/versions", + Headers: http.Header{}, + } + + var resp ListVersionsResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} + +type GetVersionRequest struct { + ImageID string `json:"-"` + + VersionID string `json:"-"` +} + +func (s *API) GetVersion(req *GetVersionRequest, opts ...scw.RequestOption) (*GetVersionResponse, error) { + var err error + + if fmt.Sprint(req.ImageID) == "" { + return nil, errors.New("field ImageID cannot be empty in request") + } + + if fmt.Sprint(req.VersionID) == "" { + return nil, errors.New("field VersionID cannot be empty in request") + } + + scwReq := &scw.ScalewayRequest{ + Method: "GET", + Path: "/marketplace/v1/images/" + fmt.Sprint(req.ImageID) + "/versions/" + fmt.Sprint(req.VersionID) + "", + Headers: http.Header{}, + } + + var resp GetVersionResponse + + err = s.client.Do(scwReq, &resp, opts...) + if err != nil { + return nil, err + } + return &resp, nil +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/api/marketplace/v1/marketplace_utils.go b/vendor/github.com/scaleway/scaleway-sdk-go/api/marketplace/v1/marketplace_utils.go new file mode 100644 index 000000000..2d78bb266 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/api/marketplace/v1/marketplace_utils.go @@ -0,0 +1,98 @@ +package marketplace + +import ( + "fmt" + "strings" + + "github.com/scaleway/scaleway-sdk-go/internal/errors" + "github.com/scaleway/scaleway-sdk-go/scw" +) + +// getLocalImage returns the correct local version of an image matching +// the current zone and the compatible commercial type +func (version *Version) getLocalImage(zone scw.Zone, commercialType string) (*LocalImage, error) { + for _, localImage := range version.LocalImages { + // Check if in correct zone + if localImage.Zone != zone { + continue + } + + // Check if compatible with wanted commercial type + for _, compatibleCommercialType := range localImage.CompatibleCommercialTypes { + if compatibleCommercialType == commercialType { + return localImage, nil + } + } + } + + return nil, fmt.Errorf("couldn't find compatible local image for this image version (%s)", version.ID) +} + +// getLatestVersion returns the current/latests version on an image, +// or an error in case the image doesn't have a public version. +func (image *Image) getLatestVersion() (*Version, error) { + for _, version := range image.Versions { + if version.ID == image.CurrentPublicVersion { + return version, nil + } + } + + return nil, errors.New("latest version could not be found for image %s", image.Label) +} + +// GetLocalImageIDByLabelRequest is used by GetLocalImageIDByLabel +type GetLocalImageIDByLabelRequest struct { + ImageLabel string + Zone scw.Zone + CommercialType string +} + +// GetLocalImageIDByLabel search for an image with the given label (exact match) in the given region +// it returns the latest version of this specific image. +func (s *API) GetLocalImageIDByLabel(req *GetLocalImageIDByLabelRequest) (string, error) { + if req.Zone == "" { + defaultZone, _ := s.client.GetDefaultZone() + req.Zone = defaultZone + } + + listImageRequest := &ListImagesRequest{} + listImageResponse, err := s.ListImages(listImageRequest, scw.WithAllPages()) + if err != nil { + return "", err + } + + images := listImageResponse.Images + label := strings.Replace(req.ImageLabel, "-", "_", -1) + commercialType := strings.ToUpper(req.CommercialType) + + for _, image := range images { + // Match label of the image + if label == image.Label { + latestVersion, err := image.getLatestVersion() + if err != nil { + return "", errors.Wrap(err, "couldn't find a matching image for the given label (%s), zone (%s) and commercial type (%s)", req.ImageLabel, req.Zone, req.CommercialType) + } + + localImage, err := latestVersion.getLocalImage(req.Zone, commercialType) + if err != nil { + return "", errors.Wrap(err, "couldn't find a matching image for the given label (%s), zone (%s) and commercial type (%s)", req.ImageLabel, req.Zone, req.CommercialType) + } + + return localImage.ID, nil + } + } + + return "", errors.New("couldn't find a matching image for the given label (%s), zone (%s) and commercial type (%s)", req.ImageLabel, req.Zone, req.CommercialType) +} + +// UnsafeSetTotalCount should not be used +// Internal usage only +func (r *ListImagesResponse) UnsafeSetTotalCount(totalCount int) { + r.TotalCount = uint32(totalCount) +} + +// UnsafeSetTotalCount should not be used +// Internal usage only +func (r *ListVersionsResponse) UnsafeSetTotalCount(totalCount int) { + r.TotalCount = uint32(totalCount) +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/internal/async/wait.go b/vendor/github.com/scaleway/scaleway-sdk-go/internal/async/wait.go new file mode 100644 index 000000000..7e0d2158f --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/internal/async/wait.go @@ -0,0 +1,90 @@ +package async + +import ( + "fmt" + "time" +) + +var ( + defaultInterval = time.Second + defaultTimeout = time.Minute * 5 +) + +type IntervalStrategy func() <-chan time.Time + +// WaitSyncConfig defines the waiting options. +type WaitSyncConfig struct { + // This method will be called from another goroutine. + Get func() (value interface{}, isTerminal bool, err error) + IntervalStrategy IntervalStrategy + Timeout time.Duration +} + +// LinearIntervalStrategy defines a linear interval duration. +func LinearIntervalStrategy(interval time.Duration) IntervalStrategy { + return func() <-chan time.Time { + return time.After(interval) + } +} + +// FibonacciIntervalStrategy defines an interval duration who follow the Fibonacci sequence. +func FibonacciIntervalStrategy(base time.Duration, factor float32) IntervalStrategy { + var x, y float32 = 0, 1 + + return func() <-chan time.Time { + x, y = y, x+(y*factor) + return time.After(time.Duration(x) * base) + } +} + +// WaitSync waits and returns when a given stop condition is true or if an error occurs. +func WaitSync(config *WaitSyncConfig) (terminalValue interface{}, err error) { + // initialize configuration + if config.IntervalStrategy == nil { + config.IntervalStrategy = LinearIntervalStrategy(defaultInterval) + } + + if config.Timeout == 0 { + config.Timeout = defaultTimeout + } + + resultValue := make(chan interface{}) + resultErr := make(chan error) + timeout := make(chan bool) + + go func() { + for { + // get the payload + value, stopCondition, err := config.Get() + + // send the payload + if err != nil { + resultErr <- err + return + } + if stopCondition { + resultValue <- value + return + } + + // waiting for an interval before next get() call or a timeout + select { + case <-timeout: + return + case <-config.IntervalStrategy(): + // sleep + } + } + }() + + // waiting for a result or a timeout + select { + case val := <-resultValue: + return val, nil + case err := <-resultErr: + return nil, err + case <-time.After(config.Timeout): + timeout <- true + return nil, fmt.Errorf("timeout after %v", config.Timeout) + } +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/auth.go b/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/auth.go new file mode 100644 index 000000000..f7ee31fcb --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/auth.go @@ -0,0 +1,14 @@ +package auth + +import "net/http" + +// Auth implement methods required for authentication. +// Valid authentication are currently a token or no auth. +type Auth interface { + // Headers returns headers that must be add to the http request + Headers() http.Header + + // AnonymizedHeaders returns an anonymised version of Headers() + // This method could be use for logging purpose. + AnonymizedHeaders() http.Header +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/no_auth.go b/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/no_auth.go new file mode 100644 index 000000000..2181c57c2 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/no_auth.go @@ -0,0 +1,19 @@ +package auth + +import "net/http" + +type NoAuth struct { +} + +// NewNoAuth return an auth with no authentication method +func NewNoAuth() *NoAuth { + return &NoAuth{} +} + +func (t *NoAuth) Headers() http.Header { + return http.Header{} +} + +func (t *NoAuth) AnonymizedHeaders() http.Header { + return http.Header{} +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/token.go b/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/token.go new file mode 100644 index 000000000..6a0902755 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/internal/auth/token.go @@ -0,0 +1,45 @@ +package auth + +import "net/http" + +// Token is the pair accessKey + secretKey. +// This type is public because it's an internal package. +type Token struct { + AccessKey string + SecretKey string +} + +// XAuthTokenHeader is Scaleway standard auth header +const XAuthTokenHeader = "X-Auth-Token" // #nosec G101 + +// NewToken create a token authentication from an +// access key and a secret key +func NewToken(accessKey, secretKey string) *Token { + return &Token{AccessKey: accessKey, SecretKey: secretKey} +} + +// Headers returns headers that must be add to the http request +func (t *Token) Headers() http.Header { + headers := http.Header{} + headers.Set(XAuthTokenHeader, t.SecretKey) + return headers +} + +// AnonymizedHeaders returns an anonymized version of Headers() +// This method could be use for logging purpose. +func (t *Token) AnonymizedHeaders() http.Header { + headers := http.Header{} + headers.Set(XAuthTokenHeader, HideSecretKey(t.SecretKey)) + return headers +} + +func HideSecretKey(k string) string { + switch { + case len(k) == 0: + return "" + case len(k) > 8: + return k[0:8] + "-xxxx-xxxx-xxxx-xxxxxxxxxxxx" + default: + return "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" + } +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/internal/errors/error.go b/vendor/github.com/scaleway/scaleway-sdk-go/internal/errors/error.go new file mode 100644 index 000000000..351dd7084 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/internal/errors/error.go @@ -0,0 +1,41 @@ +package errors + +import "fmt" + +// Error is a base error that implement scw.SdkError +type Error struct { + Str string + Err error +} + +// Error implement standard xerror.Wrapper interface +func (e *Error) Unwrap() error { + return e.Err +} + +// Error implement standard error interface +func (e *Error) Error() string { + str := "scaleway-sdk-go: " + e.Str + if e.Err != nil { + str += ": " + e.Err.Error() + } + return str +} + +// IsScwSdkError implement SdkError interface +func (e *Error) IsScwSdkError() {} + +// New creates a new error with that same interface as fmt.Errorf +func New(format string, args ...interface{}) *Error { + return &Error{ + Str: fmt.Sprintf(format, args...), + } +} + +// Wrap an error with additional information +func Wrap(err error, format string, args ...interface{}) *Error { + return &Error{ + Err: err, + Str: fmt.Sprintf(format, args...), + } +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/internal/marshaler/duration.go b/vendor/github.com/scaleway/scaleway-sdk-go/internal/marshaler/duration.go new file mode 100644 index 000000000..0eaf70e56 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/internal/marshaler/duration.go @@ -0,0 +1,160 @@ +package marshaler + +import ( + "encoding/json" + "time" +) + +// Duration implements a JSON Marshaler to encode a time.Duration in milliseconds. +type Duration int64 + +const milliSec = Duration(time.Millisecond) + +// NewDuration converts a *time.Duration to a *Duration type. +func NewDuration(t *time.Duration) *Duration { + if t == nil { + return nil + } + d := Duration(t.Nanoseconds()) + return &d +} + +// Standard converts a *Duration to a *time.Duration type. +func (d *Duration) Standard() *time.Duration { + return (*time.Duration)(d) +} + +// MarshalJSON encodes the Duration in milliseconds. +func (d Duration) MarshalJSON() ([]byte, error) { + return json.Marshal(int64(d / milliSec)) +} + +// UnmarshalJSON decodes milliseconds to Duration. +func (d *Duration) UnmarshalJSON(b []byte) error { + var tmp int64 + err := json.Unmarshal(b, &tmp) + if err != nil { + return err + } + *d = Duration(tmp) * milliSec + return nil +} + +// DurationSlice is a slice of *Duration +type DurationSlice []*Duration + +// NewDurationSlice converts a []*time.Duration to a DurationSlice type. +func NewDurationSlice(t []*time.Duration) DurationSlice { + ds := make([]*Duration, len(t)) + for i := range ds { + ds[i] = NewDuration(t[i]) + } + return ds +} + +// Standard converts a DurationSlice to a []*time.Duration type. +func (ds *DurationSlice) Standard() []*time.Duration { + t := make([]*time.Duration, len(*ds)) + for i := range t { + t[i] = (*ds)[i].Standard() + } + return t +} + +// Durationint32Map is a int32 map of *Duration +type Durationint32Map map[int32]*Duration + +// NewDurationint32Map converts a map[int32]*time.Duration to a Durationint32Map type. +func NewDurationint32Map(t map[int32]*time.Duration) Durationint32Map { + dm := make(Durationint32Map, len(t)) + for i := range t { + dm[i] = NewDuration(t[i]) + } + return dm +} + +// Standard converts a Durationint32Map to a map[int32]*time.Duration type. +func (dm *Durationint32Map) Standard() map[int32]*time.Duration { + t := make(map[int32]*time.Duration, len(*dm)) + for key, value := range *dm { + t[key] = value.Standard() + } + return t +} + +// LongDuration implements a JSON Marshaler to encode a time.Duration in days. +type LongDuration int64 + +const day = LongDuration(time.Hour) * 24 + +// NewLongDuration converts a *time.Duration to a *LongDuration type. +func NewLongDuration(t *time.Duration) *LongDuration { + if t == nil { + return nil + } + d := LongDuration(t.Nanoseconds()) + return &d +} + +// Standard converts a *LongDuration to a *time.Duration type. +func (d *LongDuration) Standard() *time.Duration { + return (*time.Duration)(d) +} + +// MarshalJSON encodes the LongDuration in days. +func (d LongDuration) MarshalJSON() ([]byte, error) { + return json.Marshal(int64(d / day)) +} + +// UnmarshalJSON decodes days to LongDuration. +func (d *LongDuration) UnmarshalJSON(b []byte) error { + var tmp int64 + err := json.Unmarshal(b, &tmp) + if err != nil { + return err + } + *d = LongDuration(tmp) * day + return nil +} + +// LongDurationSlice is a slice of *LongDuration +type LongDurationSlice []*LongDuration + +// NewLongDurationSlice converts a []*time.Duration to a LongDurationSlice type. +func NewLongDurationSlice(t []*time.Duration) LongDurationSlice { + ds := make([]*LongDuration, len(t)) + for i := range ds { + ds[i] = NewLongDuration(t[i]) + } + return ds +} + +// Standard converts a LongDurationSlice to a []*time.Duration type. +func (ds *LongDurationSlice) Standard() []*time.Duration { + t := make([]*time.Duration, len(*ds)) + for i := range t { + t[i] = (*ds)[i].Standard() + } + return t +} + +// LongDurationint32Map is a int32 map of *LongDuration +type LongDurationint32Map map[int32]*LongDuration + +// NewLongDurationint32Map converts a map[int32]*time.LongDuration to a LongDurationint32Map type. +func NewLongDurationint32Map(t map[int32]*time.Duration) LongDurationint32Map { + dm := make(LongDurationint32Map, len(t)) + for i := range t { + dm[i] = NewLongDuration(t[i]) + } + return dm +} + +// Standard converts a LongDurationint32Map to a map[int32]*time.LongDuration type. +func (dm *LongDurationint32Map) Standard() map[int32]*time.Duration { + t := make(map[int32]*time.Duration, len(*dm)) + for key, value := range *dm { + t[key] = value.Standard() + } + return t +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/internal/parameter/query.go b/vendor/github.com/scaleway/scaleway-sdk-go/internal/parameter/query.go new file mode 100644 index 000000000..bbb5d1123 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/internal/parameter/query.go @@ -0,0 +1,33 @@ +package parameter + +import ( + "fmt" + "net/url" + "reflect" + "time" +) + +// AddToQuery add a key/value pair to an URL query +func AddToQuery(query url.Values, key string, value interface{}) { + elemValue := reflect.ValueOf(value) + + if elemValue.Kind() == reflect.Invalid || elemValue.Kind() == reflect.Ptr && elemValue.IsNil() { + return + } + + for elemValue.Kind() == reflect.Ptr { + elemValue = reflect.ValueOf(value).Elem() + } + + elemType := elemValue.Type() + switch { + case elemType.Kind() == reflect.Slice: + for i := 0; i < elemValue.Len(); i++ { + query.Add(key, fmt.Sprint(elemValue.Index(i).Interface())) + } + case elemType == reflect.TypeOf(time.Time{}): + query.Add(key, value.(time.Time).Format(time.RFC3339)) + default: + query.Add(key, fmt.Sprint(elemValue.Interface())) + } +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/logger/default_logger.go b/vendor/github.com/scaleway/scaleway-sdk-go/logger/default_logger.go new file mode 100644 index 000000000..04316d8e5 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/logger/default_logger.go @@ -0,0 +1,111 @@ +package logger + +import ( + "fmt" + "io" + "io/ioutil" + "log" + "os" + "strconv" +) + +var DefaultLogger = newLogger(os.Stderr, LogLevelWarning) +var logger Logger = DefaultLogger + +// loggerT is the default logger used by scaleway-sdk-go. +type loggerT struct { + m [4]*log.Logger + v LogLevel +} + +// Init create a new default logger. +// Not mutex-protected, should be called before any scaleway-sdk-go functions. +func (g *loggerT) Init(w io.Writer, level LogLevel) { + g.m = newLogger(w, level).m +} + +// Debugf logs to the DEBUG log. Arguments are handled in the manner of fmt.Printf. +func Debugf(format string, args ...interface{}) { logger.Debugf(format, args...) } +func (g *loggerT) Debugf(format string, args ...interface{}) { + g.m[LogLevelDebug].Printf(format, args...) +} + +// Infof logs to the INFO log. Arguments are handled in the manner of fmt.Printf. +func Infof(format string, args ...interface{}) { logger.Infof(format, args...) } +func (g *loggerT) Infof(format string, args ...interface{}) { + g.m[LogLevelInfo].Printf(format, args...) +} + +// Warningf logs to the WARNING log. Arguments are handled in the manner of fmt.Printf. +func Warningf(format string, args ...interface{}) { logger.Warningf(format, args...) } +func (g *loggerT) Warningf(format string, args ...interface{}) { + g.m[LogLevelWarning].Printf(format, args...) +} + +// Errorf logs to the ERROR log. Arguments are handled in the manner of fmt.Printf. +func Errorf(format string, args ...interface{}) { logger.Errorf(format, args...) } +func (g *loggerT) Errorf(format string, args ...interface{}) { + g.m[LogLevelError].Printf(format, args...) +} + +// ShouldLog reports whether verbosity level l is at least the requested verbose level. +func ShouldLog(level LogLevel) bool { return logger.ShouldLog(level) } +func (g *loggerT) ShouldLog(level LogLevel) bool { + return level <= g.v +} + +func isEnabled(envKey string) bool { + env, exist := os.LookupEnv(envKey) + if !exist { + return false + } + + value, err := strconv.ParseBool(env) + if err != nil { + fmt.Fprintf(os.Stderr, "ERROR: environment variable %s has invalid boolean value\n", envKey) + } + + return value +} + +// newLogger creates a logger to be used as default logger. +// All logs are written to w. +func newLogger(w io.Writer, level LogLevel) *loggerT { + errorW := ioutil.Discard + warningW := ioutil.Discard + infoW := ioutil.Discard + debugW := ioutil.Discard + if isEnabled("SCW_DEBUG") { + level = LogLevelDebug + } + switch level { + case LogLevelDebug: + debugW = w + case LogLevelInfo: + infoW = w + case LogLevelWarning: + warningW = w + case LogLevelError: + errorW = w + } + + // Error logs will be written to errorW, warningW, infoW and debugW. + // Warning logs will be written to warningW, infoW and debugW. + // Info logs will be written to infoW and debugW. + // Debug logs will be written to debugW. + var m [4]*log.Logger + + m[LogLevelError] = log.New(io.MultiWriter(debugW, infoW, warningW, errorW), + severityName[LogLevelError]+": ", log.LstdFlags) + + m[LogLevelWarning] = log.New(io.MultiWriter(debugW, infoW, warningW), + severityName[LogLevelWarning]+": ", log.LstdFlags) + + m[LogLevelInfo] = log.New(io.MultiWriter(debugW, infoW), + severityName[LogLevelInfo]+": ", log.LstdFlags) + + m[LogLevelDebug] = log.New(debugW, + severityName[LogLevelDebug]+": ", log.LstdFlags) + + return &loggerT{m: m, v: level} +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/logger/logger.go b/vendor/github.com/scaleway/scaleway-sdk-go/logger/logger.go new file mode 100644 index 000000000..834f765ea --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/logger/logger.go @@ -0,0 +1,50 @@ +package logger + +import "os" + +type LogLevel int + +const ( + // LogLevelDebug indicates Debug severity. + LogLevelDebug LogLevel = iota + // LogLevelInfo indicates Info severity. + LogLevelInfo + // LogLevelWarning indicates Warning severity. + LogLevelWarning + // LogLevelError indicates Error severity. + LogLevelError +) + +// severityName contains the string representation of each severity. +var severityName = []string{ + LogLevelDebug: "DEBUG", + LogLevelInfo: "INFO", + LogLevelWarning: "WARNING", + LogLevelError: "ERROR", +} + +// Logger does underlying logging work for scaleway-sdk-go. +type Logger interface { + // Debugf logs to DEBUG log. Arguments are handled in the manner of fmt.Printf. + Debugf(format string, args ...interface{}) + // Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf. + Infof(format string, args ...interface{}) + // Warningf logs to WARNING log. Arguments are handled in the manner of fmt.Printf. + Warningf(format string, args ...interface{}) + // Errorf logs to ERROR log. Arguments are handled in the manner of fmt.Printf. + Errorf(format string, args ...interface{}) + // ShouldLog reports whether verbosity level l is at least the requested verbose level. + ShouldLog(level LogLevel) bool +} + +// SetLogger sets logger that is used in by the SDK. +// Not mutex-protected, should be called before any scaleway-sdk-go functions. +func SetLogger(l Logger) { + logger = l +} + +// EnableDebugMode enable LogLevelDebug on the default logger. +// If a custom logger was provided with SetLogger this method has no effect. +func EnableDebugMode() { + DefaultLogger.Init(os.Stderr, LogLevelDebug) +} diff --git a/vendor/github.com/docker/docker/pkg/namesgenerator/names-generator.go b/vendor/github.com/scaleway/scaleway-sdk-go/namegenerator/name_generator.go similarity index 66% rename from vendor/github.com/docker/docker/pkg/namesgenerator/names-generator.go rename to vendor/github.com/scaleway/scaleway-sdk-go/namegenerator/name_generator.go index d1da8539b..11fda4532 100644 --- a/vendor/github.com/docker/docker/pkg/namesgenerator/names-generator.go +++ b/vendor/github.com/scaleway/scaleway-sdk-go/namegenerator/name_generator.go @@ -1,10 +1,20 @@ -package namesgenerator // import "github.com/docker/docker/pkg/namesgenerator" +// Source: github.com/docker/docker/pkg/namesgenerator + +package namegenerator import ( - "fmt" "math/rand" + "strings" + "time" ) +var r *rand.Rand + +func init() { + source := rand.NewSource(time.Now().UnixNano()) + r = rand.New(source) +} + var ( left = [...]string{ "admiring", @@ -14,16 +24,22 @@ var ( "amazing", "angry", "awesome", + "beautiful", "blissful", + "bold", "boring", "brave", + "busy", + "charming", "clever", "cocky", + "cool", "compassionate", "competent", "condescending", "confident", "cranky", + "crazy", "dazzling", "determined", "distracted", @@ -35,16 +51,19 @@ var ( "elegant", "eloquent", "epic", + "exciting", "fervent", "festive", "flamboyant", "focused", "friendly", "frosty", + "funny", "gallant", "gifted", "goofy", "gracious", + "great", "happy", "hardcore", "heuristic", @@ -52,6 +71,8 @@ var ( "hungry", "infallible", "inspiring", + "interesting", + "intelligent", "jolly", "jovial", "keen", @@ -59,11 +80,13 @@ var ( "laughing", "loving", "lucid", + "magical", "mystifying", "modest", "musing", "naughty", "nervous", + "nice", "nifty", "nostalgic", "objective", @@ -75,6 +98,7 @@ var ( "priceless", "quirky", "quizzical", + "recursing", "relaxed", "reverent", "romantic", @@ -84,8 +108,10 @@ var ( "silly", "sleepy", "stoic", + "strange", "stupefied", "suspicious", + "sweet", "tender", "thirsty", "trusting", @@ -114,6 +140,9 @@ var ( // June Almeida - Scottish virologist who took the first pictures of the rubella virus - https://en.wikipedia.org/wiki/June_Almeida "almeida", + // Kathleen Antonelli, American computer programmer and one of the six original programmers of the ENIAC - https://en.wikipedia.org/wiki/Kathleen_Antonelli + "antonelli", + // Maria Gaetana Agnesi - Italian mathematician, philosopher, theologian and humanitarian. She was the first woman to write a mathematics handbook and the first woman appointed as a Mathematics Professor at a University. https://en.wikipedia.org/wiki/Maria_Gaetana_Agnesi "agnesi", @@ -135,6 +164,9 @@ var ( // Stefan Banach - Polish mathematician, was one of the founders of modern functional analysis. https://en.wikipedia.org/wiki/Stefan_Banach "banach", + // Buckaroo Banzai and his mentor Dr. Hikita perfectd the "oscillation overthruster", a device that allows one to pass through solid matter. - https://en.wikipedia.org/wiki/The_Adventures_of_Buckaroo_Banzai_Across_the_8th_Dimension + "banzai", + // John Bardeen co-invented the transistor - https://en.wikipedia.org/wiki/John_Bardeen "bardeen", @@ -159,6 +191,12 @@ var ( // Bhaskara II - Ancient Indian mathematician-astronomer whose work on calculus predates Newton and Leibniz by over half a millennium - https://en.wikipedia.org/wiki/Bh%C4%81skara_II#Calculus "bhaskara", + // Sue Black - British computer scientist and campaigner. She has been instrumental in saving Bletchley Park, the site of World War II codebreaking - https://en.wikipedia.org/wiki/Sue_Black_(computer_scientist) + "black", + + // Elizabeth Helen Blackburn - Australian-American Nobel laureate; best known for co-discovering telomerase. https://en.wikipedia.org/wiki/Elizabeth_Blackburn + "blackburn", + // Elizabeth Blackwell - American doctor and first American woman to receive a medical degree - https://en.wikipedia.org/wiki/Elizabeth_Blackwell "blackwell", @@ -174,6 +212,9 @@ var ( // Satyendra Nath Bose - He provided the foundation for Bose–Einstein statistics and the theory of the Bose–Einstein condensate. - https://en.wikipedia.org/wiki/Satyendra_Nath_Bose "bose", + // Katherine Louise Bouman is an imaging scientist and Assistant Professor of Computer Science at the California Institute of Technology. She researches computational methods for imaging, and developed an algorithm that made possible the picture first visualization of a black hole using the Event Horizon Telescope. - https://en.wikipedia.org/wiki/Katie_Bouman + "bouman", + // Evelyn Boyd Granville - She was one of the first African-American woman to receive a Ph.D. in mathematics; she earned it in 1949 from Yale University. https://en.wikipedia.org/wiki/Evelyn_Boyd_Granville "boyd", @@ -186,23 +227,44 @@ var ( // Emmett Brown invented time travel. https://en.wikipedia.org/wiki/Emmett_Brown (thanks Brian Goff) "brown", + // Linda Brown Buck - American biologist and Nobel laureate best known for her genetic and molecular analyses of the mechanisms of smell. https://en.wikipedia.org/wiki/Linda_B._Buck + "buck", + + // Dame Susan Jocelyn Bell Burnell - Northern Irish astrophysicist who discovered radio pulsars and was the first to analyse them. https://en.wikipedia.org/wiki/Jocelyn_Bell_Burnell + "burnell", + + // Annie Jump Cannon - pioneering female astronomer who classified hundreds of thousands of stars and created the system we use to understand stars today. https://en.wikipedia.org/wiki/Annie_Jump_Cannon + "cannon", + // Rachel Carson - American marine biologist and conservationist, her book Silent Spring and other writings are credited with advancing the global environmental movement. https://en.wikipedia.org/wiki/Rachel_Carson "carson", + // Dame Mary Lucy Cartwright - British mathematician who was one of the first to study what is now known as chaos theory. Also known for Cartwright's theorem which finds applications in signal processing. https://en.wikipedia.org/wiki/Mary_Cartwright + "cartwright", + + // Vinton Gray Cerf - American Internet pioneer, recognised as one of "the fathers of the Internet". With Robert Elliot Kahn, he designed TCP and IP, the primary data communication protocols of the Internet and other computer networks. https://en.wikipedia.org/wiki/Vint_Cerf + "cerf", + // Subrahmanyan Chandrasekhar - Astrophysicist known for his mathematical theory on different stages and evolution in structures of the stars. He has won nobel prize for physics - https://en.wikipedia.org/wiki/Subrahmanyan_Chandrasekhar "chandrasekhar", - //Sergey Alexeyevich Chaplygin (Russian: Серге́й Алексе́евич Чаплы́гин; April 5, 1869 – October 8, 1942) was a Russian and Soviet physicist, mathematician, and mechanical engineer. He is known for mathematical formulas such as Chaplygin's equation and for a hypothetical substance in cosmology called Chaplygin gas, named after him. https://en.wikipedia.org/wiki/Sergey_Chaplygin + // Sergey Alexeyevich Chaplygin (Russian: Серге́й Алексе́евич Чаплы́гин; April 5, 1869 – October 8, 1942) was a Russian and Soviet physicist, mathematician, and mechanical engineer. He is known for mathematical formulas such as Chaplygin's equation and for a hypothetical substance in cosmology called Chaplygin gas, named after him. https://en.wikipedia.org/wiki/Sergey_Chaplygin "chaplygin", - // Asima Chatterjee was an indian organic chemist noted for her research on vinca alkaloids, development of drugs for treatment of epilepsy and malaria - https://en.wikipedia.org/wiki/Asima_Chatterjee + // Émilie du Châtelet - French natural philosopher, mathematician, physicist, and author during the early 1730s, known for her translation of and commentary on Isaac Newton's book Principia containing basic laws of physics. https://en.wikipedia.org/wiki/%C3%89milie_du_Ch%C3%A2telet + "chatelet", + + // Asima Chatterjee was an Indian organic chemist noted for her research on vinca alkaloids, development of drugs for treatment of epilepsy and malaria - https://en.wikipedia.org/wiki/Asima_Chatterjee "chatterjee", - // Pafnuty Chebyshev - Russian mathematitian. He is known fo his works on probability, statistics, mechanics, analytical geometry and number theory https://en.wikipedia.org/wiki/Pafnuty_Chebyshev + // Pafnuty Chebyshev - Russian mathematician. He is known fo his works on probability, statistics, mechanics, analytical geometry and number theory https://en.wikipedia.org/wiki/Pafnuty_Chebyshev "chebyshev", - //Claude Shannon - The father of information theory and founder of digital circuit design theory. (https://en.wikipedia.org/wiki/Claude_Shannon) - "shannon", + // Bram Cohen - American computer programmer and author of the BitTorrent peer-to-peer protocol. https://en.wikipedia.org/wiki/Bram_Cohen + "cohen", + + // David Lee Chaum - American computer scientist and cryptographer. Known for his seminal contributions in the field of anonymous communication. https://en.wikipedia.org/wiki/David_Chaum + "chaum", // Joan Clarke - Bletchley Park code breaker during the Second World War who pioneered techniques that remained top secret for decades. Also an accomplished numismatist https://en.wikipedia.org/wiki/Joan_Clarke "clarke", @@ -230,9 +292,24 @@ var ( // Leonardo Da Vinci invented too many things to list here. https://en.wikipedia.org/wiki/Leonardo_da_Vinci. "davinci", + // A. K. (Alexander Keewatin) Dewdney, Canadian mathematician, computer scientist, author and filmmaker. Contributor to Scientific American's "Computer Recreations" from 1984 to 1991. Author of Core War (program), The Planiverse, The Armchair Universe, The Magic Machine, The New Turing Omnibus, and more. https://en.wikipedia.org/wiki/Alexander_Dewdney + "dewdney", + + // Satish Dhawan - Indian mathematician and aerospace engineer, known for leading the successful and indigenous development of the Indian space programme. https://en.wikipedia.org/wiki/Satish_Dhawan + "dhawan", + + // Bailey Whitfield Diffie - American cryptographer and one of the pioneers of public-key cryptography. https://en.wikipedia.org/wiki/Whitfield_Diffie + "diffie", + // Edsger Wybe Dijkstra was a Dutch computer scientist and mathematical scientist. https://en.wikipedia.org/wiki/Edsger_W._Dijkstra. "dijkstra", + // Paul Adrien Maurice Dirac - English theoretical physicist who made fundamental contributions to the early development of both quantum mechanics and quantum electrodynamics. https://en.wikipedia.org/wiki/Paul_Dirac + "dirac", + + // Agnes Meyer Driscoll - American cryptanalyst during World Wars I and II who successfully cryptanalysed a number of Japanese ciphers. She was also the co-developer of one of the cipher machines of the US Navy, the CM. https://en.wikipedia.org/wiki/Agnes_Meyer_Driscoll + "driscoll", + // Donna Dubinsky - played an integral role in the development of personal digital assistants (PDAs) serving as CEO of Palm, Inc. and co-founding Handspring. https://en.wikipedia.org/wiki/Donna_Dubinsky "dubinsky", @@ -245,11 +322,17 @@ var ( // Albert Einstein invented the general theory of relativity. https://en.wikipedia.org/wiki/Albert_Einstein "einstein", + // Alexandra Asanovna Elbakyan (Russian: Алекса́ндра Аса́новна Элбакя́н) is a Kazakhstani graduate student, computer programmer, internet pirate in hiding, and the creator of the site Sci-Hub. Nature has listed her in 2016 in the top ten people that mattered in science, and Ars Technica has compared her to Aaron Swartz. - https://en.wikipedia.org/wiki/Alexandra_Elbakyan + "elbakyan", + + // Taher A. ElGamal - Egyptian cryptographer best known for the ElGamal discrete log cryptosystem and the ElGamal digital signature scheme. https://en.wikipedia.org/wiki/Taher_Elgamal + "elgamal", + // Gertrude Elion - American biochemist, pharmacologist and the 1988 recipient of the Nobel Prize in Medicine - https://en.wikipedia.org/wiki/Gertrude_Elion "elion", - // Alexandra Asanovna Elbakyan (Russian: Алекса́ндра Аса́новна Элбакя́н) is a Kazakhstani graduate student, computer programmer, internet pirate in hiding, and the creator of the site Sci-Hub. Nature has listed her in 2016 in the top ten people that mattered in science, and Ars Technica has compared her to Aaron Swartz. - https://en.wikipedia.org/wiki/Alexandra_Elbakyan - "elbakyan", + // James Henry Ellis - British engineer and cryptographer employed by the GCHQ. Best known for conceiving for the first time, the idea of public-key cryptography. https://en.wikipedia.org/wiki/James_H._Ellis + "ellis", // Douglas Engelbart gave the mother of all demos: https://en.wikipedia.org/wiki/Douglas_Engelbart "engelbart", @@ -260,6 +343,12 @@ var ( // Leonhard Euler invented large parts of modern mathematics. https://de.wikipedia.org/wiki/Leonhard_Euler "euler", + // Michael Faraday - British scientist who contributed to the study of electromagnetism and electrochemistry. https://en.wikipedia.org/wiki/Michael_Faraday + "faraday", + + // Horst Feistel - German-born American cryptographer who was one of the earliest non-government researchers to study the design and theory of block ciphers. Co-developer of DES and Lucifer. Feistel networks, a symmetric structure used in the construction of block ciphers are named after him. https://en.wikipedia.org/wiki/Horst_Feistel + "feistel", + // Pierre de Fermat pioneered several aspects of modern mathematics. https://en.wikipedia.org/wiki/Pierre_de_Fermat "fermat", @@ -272,12 +361,27 @@ var ( // Benjamin Franklin is famous for his experiments in electricity and the invention of the lightning rod. "franklin", + // Yuri Alekseyevich Gagarin - Soviet pilot and cosmonaut, best known as the first human to journey into outer space. https://en.wikipedia.org/wiki/Yuri_Gagarin + "gagarin", + // Galileo was a founding father of modern astronomy, and faced politics and obscurantism to establish scientific truth. https://en.wikipedia.org/wiki/Galileo_Galilei "galileo", + // Évariste Galois - French mathematician whose work laid the foundations of Galois theory and group theory, two major branches of abstract algebra, and the subfield of Galois connections, all while still in his late teens. https://en.wikipedia.org/wiki/%C3%89variste_Galois + "galois", + + // Kadambini Ganguly - Indian physician, known for being the first South Asian female physician, trained in western medicine, to graduate in South Asia. https://en.wikipedia.org/wiki/Kadambini_Ganguly + "ganguly", + // William Henry "Bill" Gates III is an American business magnate, philanthropist, investor, computer programmer, and inventor. https://en.wikipedia.org/wiki/Bill_Gates "gates", + // Johann Carl Friedrich Gauss - German mathematician who made significant contributions to many fields, including number theory, algebra, statistics, analysis, differential geometry, geodesy, geophysics, mechanics, electrostatics, magnetic fields, astronomy, matrix theory, and optics. https://en.wikipedia.org/wiki/Carl_Friedrich_Gauss + "gauss", + + // Marie-Sophie Germain - French mathematician, physicist and philosopher. Known for her work on elasticity theory, number theory and philosophy. https://en.wikipedia.org/wiki/Sophie_Germain + "germain", + // Adele Goldberg, was one of the designers and developers of the Smalltalk language. https://en.wikipedia.org/wiki/Adele_Goldberg_(computer_scientist) "goldberg", @@ -293,27 +397,51 @@ var ( // Jane Goodall - British primatologist, ethologist, and anthropologist who is considered to be the world's foremost expert on chimpanzees - https://en.wikipedia.org/wiki/Jane_Goodall "goodall", + // Stephen Jay Gould was was an American paleontologist, evolutionary biologist, and historian of science. He is most famous for the theory of punctuated equilibrium - https://en.wikipedia.org/wiki/Stephen_Jay_Gould + "gould", + + // Carolyn Widney Greider - American molecular biologist and joint winner of the 2009 Nobel Prize for Physiology or Medicine for the discovery of telomerase. https://en.wikipedia.org/wiki/Carol_W._Greider + "greider", + + // Alexander Grothendieck - German-born French mathematician who became a leading figure in the creation of modern algebraic geometry. https://en.wikipedia.org/wiki/Alexander_Grothendieck + "grothendieck", + // Lois Haibt - American computer scientist, part of the team at IBM that developed FORTRAN - https://en.wikipedia.org/wiki/Lois_Haibt "haibt", // Margaret Hamilton - Director of the Software Engineering Division of the MIT Instrumentation Laboratory, which developed on-board flight software for the Apollo space program. https://en.wikipedia.org/wiki/Margaret_Hamilton_(scientist) "hamilton", + // Caroline Harriet Haslett - English electrical engineer, electricity industry administrator and champion of women's rights. Co-author of British Standard 1363 that specifies AC power plugs and sockets used across the United Kingdom (which is widely considered as one of the safest designs). https://en.wikipedia.org/wiki/Caroline_Haslett + "haslett", + // Stephen Hawking pioneered the field of cosmology by combining general relativity and quantum mechanics. https://en.wikipedia.org/wiki/Stephen_Hawking "hawking", + // Martin Edward Hellman - American cryptologist, best known for his invention of public-key cryptography in co-operation with Whitfield Diffie and Ralph Merkle. https://en.wikipedia.org/wiki/Martin_Hellman + "hellman", + // Werner Heisenberg was a founding father of quantum mechanics. https://en.wikipedia.org/wiki/Werner_Heisenberg "heisenberg", // Grete Hermann was a German philosopher noted for her philosophical work on the foundations of quantum mechanics. https://en.wikipedia.org/wiki/Grete_Hermann "hermann", + // Caroline Lucretia Herschel - German astronomer and discoverer of several comets. https://en.wikipedia.org/wiki/Caroline_Herschel + "herschel", + + // Heinrich Rudolf Hertz - German physicist who first conclusively proved the existence of the electromagnetic waves. https://en.wikipedia.org/wiki/Heinrich_Hertz + "hertz", + // Jaroslav Heyrovský was the inventor of the polarographic method, father of the electroanalytical method, and recipient of the Nobel Prize in 1959. His main field of work was polarography. https://en.wikipedia.org/wiki/Jaroslav_Heyrovsk%C3%BD "heyrovsky", // Dorothy Hodgkin was a British biochemist, credited with the development of protein crystallography. She was awarded the Nobel Prize in Chemistry in 1964. https://en.wikipedia.org/wiki/Dorothy_Hodgkin "hodgkin", + // Douglas R. Hofstadter is an American professor of cognitive science and author of the Pulitzer Prize and American Book Award-winning work Goedel, Escher, Bach: An Eternal Golden Braid in 1979. A mind-bending work which coined Hofstadter's Law: "It always takes longer than you expect, even when you take into account Hofstadter's Law." https://en.wikipedia.org/wiki/Douglas_Hofstadter + "hofstadter", + // Erna Schneider Hoover revolutionized modern communication by inventing a computerized telephone switching method. https://en.wikipedia.org/wiki/Erna_Schneider_Hoover "hoover", @@ -326,6 +454,9 @@ var ( // Hypatia - Greek Alexandrine Neoplatonist philosopher in Egypt who was one of the earliest mothers of mathematics - https://en.wikipedia.org/wiki/Hypatia "hypatia", + // Teruko Ishizaka - Japanese scientist and immunologist who co-discovered the antibody class Immunoglobulin E. https://en.wikipedia.org/wiki/Teruko_Ishizaka + "ishizaka", + // Mary Jackson, American mathematician and aerospace engineer who earned the highest title within NASA's engineering department - https://en.wikipedia.org/wiki/Mary_Jackson_(engineer) "jackson", @@ -365,6 +496,9 @@ var ( // Johannes Kepler, German astronomer known for his three laws of planetary motion - https://en.wikipedia.org/wiki/Johannes_Kepler "kepler", + // Omar Khayyam - Persian mathematician, astronomer and poet. Known for his work on the classification and solution of cubic equations, for his contribution to the understanding of Euclid's fifth postulate and for computing the length of a year very accurately. https://en.wikipedia.org/wiki/Omar_Khayyam + "khayyam", + // Har Gobind Khorana - Indian-American biochemist who shared the 1968 Nobel Prize for Physiology - https://en.wikipedia.org/wiki/Har_Gobind_Khorana "khorana", @@ -392,10 +526,16 @@ var ( // Mary Leakey - British paleoanthropologist who discovered the first fossilized Proconsul skull - https://en.wikipedia.org/wiki/Mary_Leakey "leakey", - // Henrietta Swan Leavitt - she was an American astronomer who discovered the relation between the luminosity and the period of Cepheid variable stars. https://en.wikipedia.org/wiki/Henrietta_Swan_Leavitt + // Henrietta Swan Leavitt - she was an American astronomer who discovered the relation between the luminosity and the period of Cepheid variable stars. https://en.wikipedia.org/wiki/Henrietta_Swan_Leavitt "leavitt", - //Daniel Lewin - Mathematician, Akamai co-founder, soldier, 9/11 victim-- Developed optimization techniques for routing traffic on the internet. Died attempting to stop the 9-11 hijackers. https://en.wikipedia.org/wiki/Daniel_Lewin + // Esther Miriam Zimmer Lederberg - American microbiologist and a pioneer of bacterial genetics. https://en.wikipedia.org/wiki/Esther_Lederberg + "lederberg", + + // Inge Lehmann - Danish seismologist and geophysicist. Known for discovering in 1936 that the Earth has a solid inner core inside a molten outer core. https://en.wikipedia.org/wiki/Inge_Lehmann + "lehmann", + + // Daniel Lewin - Mathematician, Akamai co-founder, soldier, 9/11 victim-- Developed optimization techniques for routing traffic on the internet. Died attempting to stop the 9-11 hijackers. https://en.wikipedia.org/wiki/Daniel_Lewin "lewin", // Ruth Lichterman - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Ruth_Teitelbaum @@ -413,6 +553,15 @@ var ( // Mahavira - Ancient Indian mathematician during 9th century AD who discovered basic algebraic identities - https://en.wikipedia.org/wiki/Mah%C4%81v%C4%ABra_(mathematician) "mahavira", + // Lynn Margulis (b. Lynn Petra Alexander) - an American evolutionary theorist and biologist, science author, educator, and popularizer, and was the primary modern proponent for the significance of symbiosis in evolution. - https://en.wikipedia.org/wiki/Lynn_Margulis + "margulis", + + // Yukihiro Matsumoto - Japanese computer scientist and software programmer best known as the chief designer of the Ruby programming language. https://en.wikipedia.org/wiki/Yukihiro_Matsumoto + "matsumoto", + + // James Clerk Maxwell - Scottish physicist, best known for his formulation of electromagnetic theory. https://en.wikipedia.org/wiki/James_Clerk_Maxwell + "maxwell", + // Maria Mayer - American theoretical physicist and Nobel laureate in Physics for proposing the nuclear shell model of the atomic nucleus - https://en.wikipedia.org/wiki/Maria_Mayer "mayer", @@ -422,12 +571,18 @@ var ( // Barbara McClintock - a distinguished American cytogeneticist, 1983 Nobel Laureate in Physiology or Medicine for discovering transposons. https://en.wikipedia.org/wiki/Barbara_McClintock "mcclintock", + // Anne Laura Dorinthea McLaren - British developmental biologist whose work helped lead to human in-vitro fertilisation. https://en.wikipedia.org/wiki/Anne_McLaren + "mclaren", + // Malcolm McLean invented the modern shipping container: https://en.wikipedia.org/wiki/Malcom_McLean "mclean", // Kay McNulty - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Kathleen_Antonelli "mcnulty", + // Gregor Johann Mendel - Czech scientist and founder of genetics. https://en.wikipedia.org/wiki/Gregor_Mendel + "mendel", + // Dmitri Mendeleev - a chemist and inventor. He formulated the Periodic Law, created a farsighted version of the periodic table of elements, and used it to correct the properties of some already discovered elements and also to predict the properties of eight elements yet to be discovered. https://en.wikipedia.org/wiki/Dmitri_Mendeleev "mendeleev", @@ -437,6 +592,9 @@ var ( // Carla Meninsky, was the game designer and programmer for Atari 2600 games Dodge 'Em and Warlords. https://en.wikipedia.org/wiki/Carla_Meninsky "meninsky", + // Ralph C. Merkle - American computer scientist, known for devising Merkle's puzzles - one of the very first schemes for public-key cryptography. Also, inventor of Merkle trees and co-inventor of the Merkle-Damgård construction for building collision-resistant cryptographic hash functions and the Merkle-Hellman knapsack cryptosystem. https://en.wikipedia.org/wiki/Ralph_Merkle + "merkle", + // Johanna Mestorf - German prehistoric archaeologist and first female museum director in Germany - https://en.wikipedia.org/wiki/Johanna_Mestorf "mestorf", @@ -446,18 +604,33 @@ var ( // Maryam Mirzakhani - an Iranian mathematician and the first woman to win the Fields Medal. https://en.wikipedia.org/wiki/Maryam_Mirzakhani "mirzakhani", + // Gordon Earle Moore - American engineer, Silicon Valley founding father, author of Moore's law. https://en.wikipedia.org/wiki/Gordon_Moore + "moore", + // Samuel Morse - contributed to the invention of a single-wire telegraph system based on European telegraphs and was a co-developer of the Morse code - https://en.wikipedia.org/wiki/Samuel_Morse "morse", // Ian Murdock - founder of the Debian project - https://en.wikipedia.org/wiki/Ian_Murdock "murdock", + // May-Britt Moser - Nobel prize winner neuroscientist who contributed to the discovery of grid cells in the brain. https://en.wikipedia.org/wiki/May-Britt_Moser + "moser", + + // John Napier of Merchiston - Scottish landowner known as an astronomer, mathematician and physicist. Best known for his discovery of logarithms. https://en.wikipedia.org/wiki/John_Napier + "napier", + + // John Forbes Nash, Jr. - American mathematician who made fundamental contributions to game theory, differential geometry, and the study of partial differential equations. https://en.wikipedia.org/wiki/John_Forbes_Nash_Jr. + "nash", + // John von Neumann - todays computer architectures are based on the von Neumann architecture. https://en.wikipedia.org/wiki/Von_Neumann_architecture "neumann", // Isaac Newton invented classic mechanics and modern optics. https://en.wikipedia.org/wiki/Isaac_Newton "newton", + // Xavier Niel - ;) https://en.wikipedia.org/wiki/Xavier_Niel + "niel", + // Florence Nightingale, more prominently known as a nurse, was also the first female member of the Royal Statistical Society and a pioneer in statistical graphics https://en.wikipedia.org/wiki/Florence_Nightingale#Statistics_and_sanitary_reform "nightingale", @@ -479,6 +652,9 @@ var ( // Ambroise Pare invented modern surgery. https://en.wikipedia.org/wiki/Ambroise_Par%C3%A9 "pare", + // Blaise Pascal, French mathematician, physicist, and inventor - https://en.wikipedia.org/wiki/Blaise_Pascal + "pascal", + // Louis Pasteur discovered vaccination, fermentation and pasteurization. https://en.wikipedia.org/wiki/Louis_Pasteur. "pasteur", @@ -518,18 +694,39 @@ var ( // Dennis Ritchie - co-creator of UNIX and the C programming language. - https://en.wikipedia.org/wiki/Dennis_Ritchie "ritchie", + // Ida Rhodes - American pioneer in computer programming, designed the first computer used for Social Security. https://en.wikipedia.org/wiki/Ida_Rhodes + "rhodes", + + // Julia Hall Bowman Robinson - American mathematician renowned for her contributions to the fields of computability theory and computational complexity theory. https://en.wikipedia.org/wiki/Julia_Robinson + "robinson", + // Wilhelm Conrad Röntgen - German physicist who was awarded the first Nobel Prize in Physics in 1901 for the discovery of X-rays (Röntgen rays). https://en.wikipedia.org/wiki/Wilhelm_R%C3%B6ntgen "roentgen", // Rosalind Franklin - British biophysicist and X-ray crystallographer whose research was critical to the understanding of DNA - https://en.wikipedia.org/wiki/Rosalind_Franklin "rosalind", + // Vera Rubin - American astronomer who pioneered work on galaxy rotation rates. https://en.wikipedia.org/wiki/Vera_Rubin + "rubin", + // Meghnad Saha - Indian astrophysicist best known for his development of the Saha equation, used to describe chemical and physical conditions in stars - https://en.wikipedia.org/wiki/Meghnad_Saha "saha", // Jean E. Sammet developed FORMAC, the first widely used computer language for symbolic manipulation of mathematical formulas. https://en.wikipedia.org/wiki/Jean_E._Sammet "sammet", + // Mildred Sanderson - American mathematician best known for Sanderson's theorem concerning modular invariants. https://en.wikipedia.org/wiki/Mildred_Sanderson + "sanderson", + + // Satoshi Nakamoto is the name used by the unknown person or group of people who developed bitcoin, authored the bitcoin white paper, and created and deployed bitcoin's original reference implementation. https://en.wikipedia.org/wiki/Satoshi_Nakamoto + "satoshi", + + // Adi Shamir - Israeli cryptographer whose numerous inventions and contributions to cryptography include the Ferge Fiat Shamir identification scheme, the Rivest Shamir Adleman (RSA) public-key cryptosystem, the Shamir's secret sharing scheme, the breaking of the Merkle-Hellman cryptosystem, the TWINKLE and TWIRL factoring devices and the discovery of differential cryptanalysis (with Eli Biham). https://en.wikipedia.org/wiki/Adi_Shamir + "shamir", + + // Claude Shannon - The father of information theory and founder of digital circuit design theory. (https://en.wikipedia.org/wiki/Claude_Shannon) + "shannon", + // Carol Shaw - Originally an Atari employee, Carol Shaw is said to be the first female video game designer. https://en.wikipedia.org/wiki/Carol_Shaw_(video_game_designer) "shaw", @@ -539,24 +736,30 @@ var ( // William Shockley co-invented the transistor - https://en.wikipedia.org/wiki/William_Shockley "shockley", + // Lina Solomonovna Stern (or Shtern; Russian: Лина Соломоновна Штерн; 26 August 1878 – 7 March 1968) was a Soviet biochemist, physiologist and humanist whose medical discoveries saved thousands of lives at the fronts of World War II. She is best known for her pioneering work on blood–brain barrier, which she described as hemato-encephalic barrier in 1921. https://en.wikipedia.org/wiki/Lina_Stern + "shtern", + // Françoise Barré-Sinoussi - French virologist and Nobel Prize Laureate in Physiology or Medicine; her work was fundamental in identifying HIV as the cause of AIDS. https://en.wikipedia.org/wiki/Fran%C3%A7oise_Barr%C3%A9-Sinoussi "sinoussi", // Betty Snyder - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Betty_Holberton "snyder", + // Cynthia Solomon - Pioneer in the fields of artificial intelligence, computer science and educational computing. Known for creation of Logo, an educational programming language. https://en.wikipedia.org/wiki/Cynthia_Solomon + "solomon", + // Frances Spence - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Frances_Spence "spence", // Richard Matthew Stallman - the founder of the Free Software movement, the GNU project, the Free Software Foundation, and the League for Programming Freedom. He also invented the concept of copyleft to protect the ideals of this movement, and enshrined this concept in the widely-used GPL (General Public License) for software. https://en.wikiquote.org/wiki/Richard_Stallman "stallman", - // Lina Solomonovna Stern (or Shtern; Russian: Лина Соломоновна Штерн; 26 August 1878 – 7 March 1968) was a Soviet biochemist, physiologist and humanist whose medical discoveries saved thousands of lives at the fronts of World War II. She is best known for her pioneering work on blood–brain barrier, which she described as hemato-encephalic barrier in 1921. https://en.wikipedia.org/wiki/Lina_Stern - "shtern", - // Michael Stonebraker is a database research pioneer and architect of Ingres, Postgres, VoltDB and SciDB. Winner of 2014 ACM Turing Award. https://en.wikipedia.org/wiki/Michael_Stonebraker "stonebraker", + // Ivan Edward Sutherland - American computer scientist and Internet pioneer, widely regarded as the father of computer graphics. https://en.wikipedia.org/wiki/Ivan_Sutherland + "sutherland", + // Janese Swanson (with others) developed the first of the Carmen Sandiego games. She went on to found Girl Tech. https://en.wikipedia.org/wiki/Janese_Swanson "swanson", @@ -566,18 +769,27 @@ var ( // Bertha Swirles was a theoretical physicist who made a number of contributions to early quantum theory. https://en.wikipedia.org/wiki/Bertha_Swirles "swirles", - // Valentina Tereshkova is a russian engineer, cosmonaut and politician. She was the first woman flying to space in 1963. In 2013, at the age of 76, she offered to go on a one-way mission to mars. https://en.wikipedia.org/wiki/Valentina_Tereshkova + // Helen Brooke Taussig - American cardiologist and founder of the field of paediatric cardiology. https://en.wikipedia.org/wiki/Helen_B._Taussig + "taussig", + + // Valentina Tereshkova is a Russian engineer, cosmonaut and politician. She was the first woman to fly to space in 1963. In 2013, at the age of 76, she offered to go on a one-way mission to Mars. https://en.wikipedia.org/wiki/Valentina_Tereshkova "tereshkova", // Nikola Tesla invented the AC electric system and every gadget ever used by a James Bond villain. https://en.wikipedia.org/wiki/Nikola_Tesla "tesla", + // Marie Tharp - American geologist and oceanic cartographer who co-created the first scientific map of the Atlantic Ocean floor. Her work led to the acceptance of the theories of plate tectonics and continental drift. https://en.wikipedia.org/wiki/Marie_Tharp + "tharp", + // Ken Thompson - co-creator of UNIX and the C programming language - https://en.wikipedia.org/wiki/Ken_Thompson "thompson", // Linus Torvalds invented Linux and Git. https://en.wikipedia.org/wiki/Linus_Torvalds "torvalds", + // Youyou Tu - Chinese pharmaceutical chemist and educator known for discovering artemisinin and dihydroartemisinin, used to treat malaria, which has saved millions of lives. Joint winner of the 2015 Nobel Prize in Physiology or Medicine. https://en.wikipedia.org/wiki/Tu_Youyou + "tu", + // Alan Turing was a founding father of computer science. https://en.wikipedia.org/wiki/Alan_Turing. "turing", @@ -599,12 +811,18 @@ var ( // Marlyn Wescoff - one of the original programmers of the ENIAC. https://en.wikipedia.org/wiki/ENIAC - https://en.wikipedia.org/wiki/Marlyn_Meltzer "wescoff", + // Sylvia B. Wilbur - British computer scientist who helped develop the ARPANET, was one of the first to exchange email in the UK and a leading researcher in computer-supported collaborative work. https://en.wikipedia.org/wiki/Sylvia_Wilbur + "wilbur", + // Andrew Wiles - Notable British mathematician who proved the enigmatic Fermat's Last Theorem - https://en.wikipedia.org/wiki/Andrew_Wiles "wiles", // Roberta Williams, did pioneering work in graphical adventure games for personal computers, particularly the King's Quest series. https://en.wikipedia.org/wiki/Roberta_Williams "williams", + // Malcolm John Williamson - British mathematician and cryptographer employed by the GCHQ. Developed in 1974 what is now known as Diffie-Hellman key exchange (Diffie and Hellman first published the scheme in 1976). https://en.wikipedia.org/wiki/Malcolm_J._Williamson + "williamson", + // Sophie Wilson designed the first Acorn Micro-Computer and the instruction set for ARM processors. https://en.wikipedia.org/wiki/Sophie_Wilson "wilson", @@ -617,6 +835,9 @@ var ( // The Wright brothers, Orville and Wilbur - credited with inventing and building the world's first successful airplane and making the first controlled, powered and sustained heavier-than-air human flight - https://en.wikipedia.org/wiki/Wright_brothers "wright", + // Chien-Shiung Wu - Chinese-American experimental physicist who made significant contributions to nuclear physics. https://en.wikipedia.org/wiki/Chien-Shiung_Wu + "wu", + // Rosalyn Sussman Yalow - Rosalyn Sussman Yalow was an American medical physicist, and a co-winner of the 1977 Nobel Prize in Physiology or Medicine for development of the radioimmunoassay technique. https://en.wikipedia.org/wiki/Rosalyn_Sussman_Yalow "yalow", @@ -629,17 +850,14 @@ var ( ) // GetRandomName generates a random name from the list of adjectives and surnames in this package -// formatted as "adjective_surname". For example 'focused_turing'. If retry is non-zero, a random -// integer between 0 and 10 will be added to the end of the name, e.g `focused_turing3` -func GetRandomName(retry int) string { +// formatted as "scw-adjective-surname". For example 'scw-focused-turing'. +func GetRandomName(prefixes ...string) string { begin: - name := fmt.Sprintf("%s_%s", left[rand.Intn(len(left))], right[rand.Intn(len(right))]) - if name == "boring_wozniak" /* Steve Wozniak is not boring */ { + parts := append(prefixes, left[r.Intn(len(left))], right[r.Intn(len(right))]) + name := strings.Join(parts, "-") + if strings.Contains(name, "boring-wozniak") /* Steve Wozniak is not boring */ { goto begin } - if retry > 0 { - name = fmt.Sprintf("%s%d", name, rand.Intn(10)) - } return name } diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/README.md b/vendor/github.com/scaleway/scaleway-sdk-go/scw/README.md new file mode 100644 index 000000000..0ab7eae24 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/README.md @@ -0,0 +1,55 @@ +# Scaleway config + +## TL;DR + +Recommended config file: + +```yaml +# get your credentials on https://console.scaleway.com/account/credentials +access_key: SCWXXXXXXXXXXXXXXXXX +secret_key: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx +default_organization_id: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx +default_region: fr-par +default_zone: fr-par-1 +``` + +## Config file path + +The function [`GetConfigPath`](https://godoc.org/github.com/scaleway/scaleway-sdk-go/scw#GetConfigPath) will try to locate the config file in the following ways: + +1. Custom directory: `$SCW_CONFIG_PATH` +2. [XDG base directory](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html): `$XDG_CONFIG_HOME/scw/config.yaml` +3. Unix home directory: `$HOME/.config/scw/config.yaml` +3. Windows home directory: `%USERPROFILE%/.config/scw/config.yaml` + +## V1 config (DEPRECATED) + +The V1 config (AKA legacy config) `.scwrc` is deprecated. +To migrate the V1 config to the new format use the function [`MigrateLegacyConfig`](https://godoc.org/github.com/scaleway/scaleway-sdk-go/scw#MigrateLegacyConfig), this will create a [proper config file](#tl-dr) the new [config file path](#config-file-path). + +## Reading config order + +[ClientOption](https://godoc.org/github.com/scaleway/scaleway-sdk-go/scw#ClientOption) ordering will decide the order in which the config should apply: + +```go +p, _ := scw.MustLoadConfig().GetActiveProfile() + +scw.NewClient( + scw.WithProfile(p), // active profile applies first + scw.WithEnv(), // existing env variables may overwrite active profile + scw.WithDefaultRegion(scw.RegionFrPar) // any prior region set will be discarded to usr the new one +) +``` + +## Environment variables + +| Variable | Description | Legacy variables | +| :------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------ | +| `$SCW_ACCESS_KEY` | Access key of a token ([get yours](https://console.scaleway.com/account/credentials)) | `$SCALEWAY_ACCESS_KEY` (used by terraform) | +| `$SCW_SECRET_KEY` | Secret key of a token ([get yours](https://console.scaleway.com/account/credentials)) | `$SCW_TOKEN` (used by cli), `$SCALEWAY_TOKEN` (used by terraform), `$SCALEWAY_ACCESS_KEY` (used by terraform) | +| `$SCW_DEFAULT_ORGANIZATION_ID` | Your default organization ID, if you don't have one use your organization ID ([get yours](https://console.scaleway.com/account/credentials)) | `$SCW_ORGANIZATION` (used by cli),`$SCALEWAY_ORGANIZATION` (used by terraform) | +| `$SCW_DEFAULT_REGION` | Your default [region](https://developers.scaleway.com/en/quickstart/#region-and-zone) | `$SCW_REGION` (used by cli),`$SCALEWAY_REGION` (used by terraform) | +| `$SCW_DEFAULT_ZONE` | Your default [availability zone](https://developers.scaleway.com/en/quickstart/#region-and-zone) | `$SCW_ZONE` (used by cli),`$SCALEWAY_ZONE` (used by terraform) | +| `$SCW_API_URL` | Url of the API | - | +| `$SCW_INSECURE` | Set this to `true` to enable the insecure mode | `$SCW_TLSVERIFY` (inverse flag used by the cli) | +| `$SCW_PROFILE` | Set the config profile to use | - | diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/client.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/client.go new file mode 100644 index 000000000..0bdb13bca --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/client.go @@ -0,0 +1,376 @@ +package scw + +import ( + "crypto/tls" + "encoding/json" + "io" + "math" + "net" + "net/http" + "net/http/httputil" + "reflect" + "strconv" + "sync/atomic" + "time" + + "github.com/scaleway/scaleway-sdk-go/internal/auth" + "github.com/scaleway/scaleway-sdk-go/internal/errors" + "github.com/scaleway/scaleway-sdk-go/logger" +) + +// Client is the Scaleway client which performs API requests. +// +// This client should be passed in the `NewApi` functions whenever an API instance is created. +// Creating a Client is done with the `NewClient` function. +type Client struct { + httpClient httpClient + auth auth.Auth + apiURL string + userAgent string + defaultOrganizationID *string + defaultProjectID *string + defaultRegion *Region + defaultZone *Zone + defaultPageSize *uint32 +} + +func defaultOptions() []ClientOption { + return []ClientOption{ + WithoutAuth(), + WithAPIURL("https://api.scaleway.com"), + withDefaultUserAgent(userAgent), + } +} + +// NewClient instantiate a new Client object. +// +// Zero or more ClientOption object can be passed as a parameter. +// These options will then be applied to the client. +func NewClient(opts ...ClientOption) (*Client, error) { + s := newSettings() + + // apply options + s.apply(append(defaultOptions(), opts...)) + + // validate settings + err := s.validate() + if err != nil { + return nil, err + } + + // dial the API + if s.httpClient == nil { + s.httpClient = newHTTPClient() + } + + // insecure mode + if s.insecure { + logger.Debugf("client: using insecure mode") + setInsecureMode(s.httpClient) + } + + logger.Debugf("client: using sdk version " + version) + + return &Client{ + auth: s.token, + httpClient: s.httpClient, + apiURL: s.apiURL, + userAgent: s.userAgent, + defaultOrganizationID: s.defaultOrganizationID, + defaultProjectID: s.defaultProjectID, + defaultRegion: s.defaultRegion, + defaultZone: s.defaultZone, + defaultPageSize: s.defaultPageSize, + }, nil +} + +// GetDefaultOrganizationID returns the default organization ID +// of the client. This value can be set in the client option +// WithDefaultOrganizationID(). Be aware this value can be empty. +func (c *Client) GetDefaultOrganizationID() (organizationID string, exists bool) { + if c.defaultOrganizationID != nil { + return *c.defaultOrganizationID, true + } + return "", false +} + +// GetDefaultProjectID returns the default project ID +// of the client. This value can be set in the client option +// WithDefaultProjectID(). Be aware this value can be empty. +func (c *Client) GetDefaultProjectID() (projectID string, exists bool) { + if c.defaultProjectID != nil { + return *c.defaultProjectID, true + } + return "", false +} + +// GetDefaultRegion returns the default region of the client. +// This value can be set in the client option +// WithDefaultRegion(). Be aware this value can be empty. +func (c *Client) GetDefaultRegion() (region Region, exists bool) { + if c.defaultRegion != nil { + return *c.defaultRegion, true + } + return Region(""), false +} + +// GetDefaultZone returns the default zone of the client. +// This value can be set in the client option +// WithDefaultZone(). Be aware this value can be empty. +func (c *Client) GetDefaultZone() (zone Zone, exists bool) { + if c.defaultZone != nil { + return *c.defaultZone, true + } + return Zone(""), false +} + +func (c *Client) GetSecretKey() (secretKey string, exists bool) { + if token, isToken := c.auth.(*auth.Token); isToken { + return token.SecretKey, isToken + } + return "", false +} + +func (c *Client) GetAccessKey() (accessKey string, exists bool) { + if token, isToken := c.auth.(*auth.Token); isToken { + return token.AccessKey, isToken + } + return "", false +} + +// GetDefaultPageSize returns the default page size of the client. +// This value can be set in the client option +// WithDefaultPageSize(). Be aware this value can be empty. +func (c *Client) GetDefaultPageSize() (pageSize uint32, exists bool) { + if c.defaultPageSize != nil { + return *c.defaultPageSize, true + } + return 0, false +} + +// Do performs HTTP request(s) based on the ScalewayRequest object. +// RequestOptions are applied prior to doing the request. +func (c *Client) Do(req *ScalewayRequest, res interface{}, opts ...RequestOption) (err error) { + // apply request options + req.apply(opts) + + // validate request options + err = req.validate() + if err != nil { + return err + } + + if req.auth == nil { + req.auth = c.auth + } + + if req.allPages { + return c.doListAll(req, res) + } + + return c.do(req, res) +} + +// requestNumber auto increments on each do(). +// This allows easy distinguishing of concurrently performed requests in log. +var requestNumber uint32 + +// do performs a single HTTP request based on the ScalewayRequest object. +func (c *Client) do(req *ScalewayRequest, res interface{}) (sdkErr error) { + currentRequestNumber := atomic.AddUint32(&requestNumber, 1) + + if req == nil { + return errors.New("request must be non-nil") + } + + // build url + url, sdkErr := req.getURL(c.apiURL) + if sdkErr != nil { + return sdkErr + } + logger.Debugf("creating %s request on %s", req.Method, url.String()) + + // build request + httpRequest, err := http.NewRequest(req.Method, url.String(), req.Body) + if err != nil { + return errors.Wrap(err, "could not create request") + } + + httpRequest.Header = req.getAllHeaders(req.auth, c.userAgent, false) + + if req.ctx != nil { + httpRequest = httpRequest.WithContext(req.ctx) + } + + if logger.ShouldLog(logger.LogLevelDebug) { + // Keep original headers (before anonymization) + originalHeaders := httpRequest.Header + + // Get anonymized headers + httpRequest.Header = req.getAllHeaders(req.auth, c.userAgent, true) + + dump, err := httputil.DumpRequestOut(httpRequest, true) + if err != nil { + logger.Warningf("cannot dump outgoing request: %s", err) + } else { + var logString string + logString += "\n--------------- Scaleway SDK REQUEST %d : ---------------\n" + logString += "%s\n" + logString += "---------------------------------------------------------" + + logger.Debugf(logString, currentRequestNumber, dump) + } + + // Restore original headers before sending the request + httpRequest.Header = originalHeaders + } + + // execute request + httpResponse, err := c.httpClient.Do(httpRequest) + if err != nil { + return errors.Wrap(err, "error executing request") + } + + defer func() { + closeErr := httpResponse.Body.Close() + if sdkErr == nil && closeErr != nil { + sdkErr = errors.Wrap(closeErr, "could not close http response") + } + }() + if logger.ShouldLog(logger.LogLevelDebug) { + dump, err := httputil.DumpResponse(httpResponse, true) + if err != nil { + logger.Warningf("cannot dump ingoing response: %s", err) + } else { + var logString string + logString += "\n--------------- Scaleway SDK RESPONSE %d : ---------------\n" + logString += "%s\n" + logString += "----------------------------------------------------------" + + logger.Debugf(logString, currentRequestNumber, dump) + } + } + + sdkErr = hasResponseError(httpResponse) + if sdkErr != nil { + return sdkErr + } + + if res != nil { + contentType := httpResponse.Header.Get("Content-Type") + + switch contentType { + case "application/json": + err = json.NewDecoder(httpResponse.Body).Decode(&res) + if err != nil { + return errors.Wrap(err, "could not parse %s response body", contentType) + } + default: + buffer, isBuffer := res.(io.Writer) + if !isBuffer { + return errors.Wrap(err, "could not handle %s response body with %T result type", contentType, buffer) + } + + _, err := io.Copy(buffer, httpResponse.Body) + if err != nil { + return errors.Wrap(err, "could not copy %s response body", contentType) + } + } + + // Handle instance API X-Total-Count header + xTotalCountStr := httpResponse.Header.Get("X-Total-Count") + if legacyLister, isLegacyLister := res.(legacyLister); isLegacyLister && xTotalCountStr != "" { + xTotalCount, err := strconv.Atoi(xTotalCountStr) + if err != nil { + return errors.Wrap(err, "could not parse X-Total-Count header") + } + legacyLister.UnsafeSetTotalCount(xTotalCount) + } + } + + return nil +} + +type lister interface { + UnsafeGetTotalCount() uint32 + UnsafeAppend(interface{}) (uint32, error) +} + +type legacyLister interface { + UnsafeSetTotalCount(totalCount int) +} + +const maxPageCount uint32 = math.MaxUint32 + +// doListAll collects all pages of a List request and aggregate all results on a single response. +func (c *Client) doListAll(req *ScalewayRequest, res interface{}) (err error) { + // check for lister interface + if response, isLister := res.(lister); isLister { + pageCount := maxPageCount + for page := uint32(1); page <= pageCount; page++ { + // set current page + req.Query.Set("page", strconv.FormatUint(uint64(page), 10)) + + // request the next page + nextPage := newVariableFromType(response) + err := c.do(req, nextPage) + if err != nil { + return err + } + + // append results + pageSize, err := response.UnsafeAppend(nextPage) + if err != nil { + return err + } + + if pageSize == 0 { + return nil + } + + // set total count on first request + if pageCount == maxPageCount { + totalCount := nextPage.(lister).UnsafeGetTotalCount() + pageCount = (totalCount + pageSize - 1) / pageSize + } + } + return nil + } + + return errors.New("%T does not support pagination", res) +} + +// newVariableFromType returns a variable set to the zero value of the given type +func newVariableFromType(t interface{}) interface{} { + // reflect.New always create a pointer, that's why we use reflect.Indirect before + return reflect.New(reflect.Indirect(reflect.ValueOf(t)).Type()).Interface() +} + +func newHTTPClient() *http.Client { + return &http.Client{ + Timeout: 30 * time.Second, + Transport: &http.Transport{ + DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext, + TLSHandshakeTimeout: 5 * time.Second, + ResponseHeaderTimeout: 30 * time.Second, + MaxIdleConnsPerHost: 20, + }, + } +} + +func setInsecureMode(c httpClient) { + standardHTTPClient, ok := c.(*http.Client) + if !ok { + logger.Warningf("client: cannot use insecure mode with HTTP client of type %T", c) + return + } + transportClient, ok := standardHTTPClient.Transport.(*http.Transport) + if !ok { + logger.Warningf("client: cannot use insecure mode with Transport client of type %T", standardHTTPClient.Transport) + return + } + if transportClient.TLSClientConfig == nil { + transportClient.TLSClientConfig = &tls.Config{} + } + transportClient.TLSClientConfig.InsecureSkipVerify = true +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/client_option.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/client_option.go new file mode 100644 index 000000000..f01b37400 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/client_option.go @@ -0,0 +1,265 @@ +package scw + +import ( + "net/http" + "strings" + + "github.com/scaleway/scaleway-sdk-go/internal/auth" + "github.com/scaleway/scaleway-sdk-go/internal/errors" + "github.com/scaleway/scaleway-sdk-go/validation" +) + +// ClientOption is a function which applies options to a settings object. +type ClientOption func(*settings) + +// httpClient wraps the net/http Client Do method +type httpClient interface { + Do(*http.Request) (*http.Response, error) +} + +// WithHTTPClient client option allows passing a custom http.Client which will be used for all requests. +func WithHTTPClient(httpClient httpClient) ClientOption { + return func(s *settings) { + s.httpClient = httpClient + } +} + +// WithoutAuth client option sets the client token to an empty token. +func WithoutAuth() ClientOption { + return func(s *settings) { + s.token = auth.NewNoAuth() + } +} + +// WithAuth client option sets the client access key and secret key. +func WithAuth(accessKey, secretKey string) ClientOption { + return func(s *settings) { + s.token = auth.NewToken(accessKey, secretKey) + } +} + +// WithAPIURL client option overrides the API URL of the Scaleway API to the given URL. +func WithAPIURL(apiURL string) ClientOption { + return func(s *settings) { + s.apiURL = apiURL + } +} + +// WithInsecure client option enables insecure transport on the client. +func WithInsecure() ClientOption { + return func(s *settings) { + s.insecure = true + } +} + +// WithUserAgent client option append a user agent to the default user agent of the SDK. +func WithUserAgent(ua string) ClientOption { + return func(s *settings) { + if s.userAgent != "" && ua != "" { + s.userAgent += " " + } + s.userAgent += ua + } +} + +// withDefaultUserAgent client option overrides the default user agent of the SDK. +func withDefaultUserAgent(ua string) ClientOption { + return func(s *settings) { + s.userAgent = ua + } +} + +// WithProfile client option configures a client from the given profile. +func WithProfile(p *Profile) ClientOption { + return func(s *settings) { + accessKey := "" + if p.AccessKey != nil { + accessKey = *p.AccessKey + } + + if p.SecretKey != nil { + s.token = auth.NewToken(accessKey, *p.SecretKey) + } + + if p.APIURL != nil { + s.apiURL = *p.APIURL + } + + if p.Insecure != nil { + s.insecure = *p.Insecure + } + + if p.DefaultOrganizationID != nil { + organizationID := *p.DefaultOrganizationID + s.defaultOrganizationID = &organizationID + } + + if p.DefaultProjectID != nil { + projectID := *p.DefaultProjectID + s.defaultProjectID = &projectID + } + + if p.DefaultRegion != nil { + defaultRegion := Region(*p.DefaultRegion) + s.defaultRegion = &defaultRegion + } + + if p.DefaultZone != nil { + defaultZone := Zone(*p.DefaultZone) + s.defaultZone = &defaultZone + } + } +} + +// WithProfile client option configures a client from the environment variables. +func WithEnv() ClientOption { + return WithProfile(LoadEnvProfile()) +} + +// WithDefaultOrganizationID client option sets the client default organization ID. +// +// It will be used as the default value of the organization_id field in all requests made with this client. +func WithDefaultOrganizationID(organizationID string) ClientOption { + return func(s *settings) { + s.defaultOrganizationID = &organizationID + } +} + +// WithDefaultProjectID client option sets the client default project ID. +// +// It will be used as the default value of the projectID field in all requests made with this client. +func WithDefaultProjectID(projectID string) ClientOption { + return func(s *settings) { + s.defaultProjectID = &projectID + } +} + +// WithDefaultRegion client option sets the client default region. +// +// It will be used as the default value of the region field in all requests made with this client. +func WithDefaultRegion(region Region) ClientOption { + return func(s *settings) { + s.defaultRegion = ®ion + } +} + +// WithDefaultZone client option sets the client default zone. +// +// It will be used as the default value of the zone field in all requests made with this client. +func WithDefaultZone(zone Zone) ClientOption { + return func(s *settings) { + s.defaultZone = &zone + } +} + +// WithDefaultPageSize client option overrides the default page size of the SDK. +// +// It will be used as the default value of the page_size field in all requests made with this client. +func WithDefaultPageSize(pageSize uint32) ClientOption { + return func(s *settings) { + s.defaultPageSize = &pageSize + } +} + +// settings hold the values of all client options +type settings struct { + apiURL string + token auth.Auth + userAgent string + httpClient httpClient + insecure bool + defaultOrganizationID *string + defaultProjectID *string + defaultRegion *Region + defaultZone *Zone + defaultPageSize *uint32 +} + +func newSettings() *settings { + return &settings{} +} + +func (s *settings) apply(opts []ClientOption) { + for _, opt := range opts { + opt(s) + } +} + +func (s *settings) validate() error { + // Auth. + if s.token == nil { + // It should not happen, WithoutAuth option is used by default. + panic(errors.New("no credential option provided")) + } + if token, isToken := s.token.(*auth.Token); isToken { + if token.AccessKey == "" { + return NewInvalidClientOptionError("access key cannot be empty") + } + if !validation.IsAccessKey(token.AccessKey) { + return NewInvalidClientOptionError("invalid access key format '%s', expected SCWXXXXXXXXXXXXXXXXX format", token.AccessKey) + } + if token.SecretKey == "" { + return NewInvalidClientOptionError("secret key cannot be empty") + } + if !validation.IsSecretKey(token.SecretKey) { + return NewInvalidClientOptionError("invalid secret key format '%s', expected a UUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", token.SecretKey) + } + } + + // Default Organization ID. + if s.defaultOrganizationID != nil { + if *s.defaultOrganizationID == "" { + return NewInvalidClientOptionError("default organization ID cannot be empty") + } + if !validation.IsOrganizationID(*s.defaultOrganizationID) { + return NewInvalidClientOptionError("invalid organization ID format '%s', expected a UUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", *s.defaultOrganizationID) + } + } + + // Default Project ID. + if s.defaultProjectID != nil { + if *s.defaultProjectID == "" { + return NewInvalidClientOptionError("default project ID cannot be empty") + } + if !validation.IsProjectID(*s.defaultProjectID) { + return NewInvalidClientOptionError("invalid project ID format '%s', expected a UUID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", *s.defaultProjectID) + } + } + + // Default Region. + if s.defaultRegion != nil { + if *s.defaultRegion == "" { + return NewInvalidClientOptionError("default region cannot be empty") + } + if !validation.IsRegion(string(*s.defaultRegion)) { + regions := []string(nil) + for _, r := range AllRegions { + regions = append(regions, string(r)) + } + return NewInvalidClientOptionError("invalid default region format '%s', available regions are: %s", *s.defaultRegion, strings.Join(regions, ", ")) + } + } + + // Default Zone. + if s.defaultZone != nil { + if *s.defaultZone == "" { + return NewInvalidClientOptionError("default zone cannot be empty") + } + if !validation.IsZone(string(*s.defaultZone)) { + zones := []string(nil) + for _, z := range AllZones { + zones = append(zones, string(z)) + } + return NewInvalidClientOptionError("invalid default zone format '%s', available zones are: %s", *s.defaultZone, strings.Join(zones, ", ")) + } + } + + // API URL. + if !validation.IsURL(s.apiURL) { + return NewInvalidClientOptionError("invalid url %s", s.apiURL) + } + + // TODO: check for max s.defaultPageSize + + return nil +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/config.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/config.go new file mode 100644 index 000000000..eb423162f --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/config.go @@ -0,0 +1,343 @@ +package scw + +import ( + "bytes" + "io/ioutil" + "os" + "path/filepath" + "text/template" + + "github.com/scaleway/scaleway-sdk-go/internal/auth" + "github.com/scaleway/scaleway-sdk-go/internal/errors" + "github.com/scaleway/scaleway-sdk-go/logger" + "gopkg.in/yaml.v2" +) + +const ( + documentationLink = "https://github.com/scaleway/scaleway-sdk-go/blob/master/scw/README.md" + defaultConfigPermission = 0600 + + // Reserved name for the default profile. + DefaultProfileName = "default" +) + +const configFileTemplate = `# Scaleway configuration file +# https://github.com/scaleway/scaleway-sdk-go/tree/master/scw#scaleway-config + +# This configuration file can be used with: +# - Scaleway SDK Go (https://github.com/scaleway/scaleway-sdk-go) +# - Scaleway CLI (>2.0.0) (https://github.com/scaleway/scaleway-cli) +# - Scaleway Terraform Provider (https://www.terraform.io/docs/providers/scaleway/index.html) + +# You need an access key and a secret key to connect to Scaleway API. +# Generate your token at the following address: https://console.scaleway.com/account/credentials + +# An access key is a secret key identifier. +{{ if .AccessKey }}access_key: {{.AccessKey}}{{ else }}# access_key: SCW11111111111111111{{ end }} + +# The secret key is the value that can be used to authenticate against the API (the value used in X-Auth-Token HTTP-header). +# The secret key MUST remain secret and not given to anyone or published online. +{{ if .SecretKey }}secret_key: {{ .SecretKey }}{{ else }}# secret_key: 11111111-1111-1111-1111-111111111111{{ end }} + +# Your organization ID is the identifier of your account inside Scaleway infrastructure. +{{ if .DefaultOrganizationID }}default_organization_id: {{ .DefaultOrganizationID }}{{ else }}# default_organization_id: 11111111-1111-1111-1111-111111111111{{ end }} + +# Your project ID is the identifier of the project your resources are attached to (beta). +{{ if .DefaultProjectID }}default_project_id: {{ .DefaultProjectID }}{{ else }}# default_project_id: 11111111-1111-1111-1111-111111111111{{ end }} + +# A region is represented as a geographical area such as France (Paris) or the Netherlands (Amsterdam). +# It can contain multiple availability zones. +# Example of region: fr-par, nl-ams +{{ if .DefaultRegion }}default_region: {{ .DefaultRegion }}{{ else }}# default_region: fr-par{{ end }} + +# A region can be split into many availability zones (AZ). +# Latency between multiple AZ of the same region are low as they have a common network layer. +# Example of zones: fr-par-1, nl-ams-1 +{{ if .DefaultZone }}default_zone: {{.DefaultZone}}{{ else }}# default_zone: fr-par-1{{ end }} + +# APIURL overrides the API URL of the Scaleway API to the given URL. +# Change that if you want to direct requests to a different endpoint. +{{ if .APIURL }}apiurl: {{ .APIURL }}{{ else }}# api_url: https://api.scaleway.com{{ end }} + +# Insecure enables insecure transport on the client. +# Default to false +{{ if .Insecure }}insecure: {{ .Insecure }}{{ else }}# insecure: false{{ end }} + +# A configuration is a named set of Scaleway properties. +# Starting off with a Scaleway SDK or Scaleway CLI, you’ll work with a single configuration named default. +# You can set properties of the default profile by running either scw init or scw config set. +# This single default configuration is suitable for most use cases. +{{ if .ActiveProfile }}active_profile: {{ .ActiveProfile }}{{ else }}# active_profile: myProfile{{ end }} + +# To improve the Scaleway CLI we rely on diagnostic and usage data. +# Sending such data is optional and can be disable at any time by setting send_telemetry variable to false. +{{ if .SendTelemetry }}send_telemetry: {{ .SendTelemetry }}{{ else }}# send_telemetry: false{{ end }} + +# To work with multiple projects or authorization accounts, you can set up multiple configurations with scw config configurations create and switch among them accordingly. +# You can use a profile by either: +# - Define the profile you want to use as the SCW_PROFILE environment variable +# - Use the GetActiveProfile() function in the SDK +# - Use the --profile flag with the CLI + +# You can define a profile using the following syntax: +{{ if gt (len .Profiles) 0 }} +profiles: +{{- range $k,$v := .Profiles }} + {{ $k }}: + {{ if $v.AccessKey }}access_key: {{ $v.AccessKey }}{{ else }}# access_key: SCW11111111111111111{{ end }} + {{ if $v.SecretKey }}secret_key: {{ $v.SecretKey }}{{ else }}# secret_key: 11111111-1111-1111-1111-111111111111{{ end }} + {{ if $v.DefaultOrganizationID }}default_organization_id: {{ $v.DefaultOrganizationID }}{{ else }}# default_organization_id: 11111111-1111-1111-1111-111111111111{{ end }} + {{ if $v.DefaultProjectID }}default_project_id: {{ $v.DefaultProjectID }}{{ else }}# default_project_id: 11111111-1111-1111-1111-111111111111{{ end }} + {{ if $v.DefaultZone }}default_zone: {{ $v.DefaultZone }}{{ else }}# default_zone: fr-par-1{{ end }} + {{ if $v.DefaultRegion }}default_region: {{ $v.DefaultRegion }}{{ else }}# default_region: fr-par{{ end }} + {{ if $v.APIURL }}api_url: {{ $v.APIURL }}{{ else }}# api_url: https://api.scaleway.com{{ end }} + {{ if $v.Insecure }}insecure: {{ $v.Insecure }}{{ else }}# insecure: false{{ end }} +{{ end }} +{{- else }} +# profiles: +# myProfile: +# access_key: 11111111-1111-1111-1111-111111111111 +# secret_key: 11111111-1111-1111-1111-111111111111 +# default_organization_id: 11111111-1111-1111-1111-111111111111 +# default_project_id: 11111111-1111-1111-1111-111111111111 +# default_zone: fr-par-1 +# default_region: fr-par +# api_url: https://api.scaleway.com +# insecure: false +{{ end -}} +` + +type Config struct { + Profile `yaml:",inline"` + ActiveProfile *string `yaml:"active_profile,omitempty" json:"active_profile,omitempty"` + Profiles map[string]*Profile `yaml:"profiles,omitempty" json:"profiles,omitempty"` +} + +type Profile struct { + AccessKey *string `yaml:"access_key,omitempty" json:"access_key,omitempty"` + SecretKey *string `yaml:"secret_key,omitempty" json:"secret_key,omitempty"` + APIURL *string `yaml:"api_url,omitempty" json:"api_url,omitempty"` + Insecure *bool `yaml:"insecure,omitempty" json:"insecure,omitempty"` + DefaultOrganizationID *string `yaml:"default_organization_id,omitempty" json:"default_organization_id,omitempty"` + DefaultProjectID *string `yaml:"default_project_id,omitempty" json:"default_project_id,omitempty"` + DefaultRegion *string `yaml:"default_region,omitempty" json:"default_region,omitempty"` + DefaultZone *string `yaml:"default_zone,omitempty" json:"default_zone,omitempty"` + SendTelemetry *bool `yaml:"send_telemetry,omitempty" json:"send_telemetry,omitempty"` +} + +func (p *Profile) String() string { + p2 := *p + p2.SecretKey = hideSecretKey(p2.SecretKey) + configRaw, _ := yaml.Marshal(p2) + return string(configRaw) +} + +// clone deep copy config object +func (c *Config) clone() *Config { + c2 := &Config{} + configRaw, _ := yaml.Marshal(c) + _ = yaml.Unmarshal(configRaw, c2) + return c2 +} + +func (c *Config) String() string { + c2 := c.clone() + c2.SecretKey = hideSecretKey(c2.SecretKey) + for _, p := range c2.Profiles { + p.SecretKey = hideSecretKey(p.SecretKey) + } + + configRaw, _ := yaml.Marshal(c2) + return string(configRaw) +} + +func (c *Config) IsEmpty() bool { + return c.String() == "{}\n" +} + +func hideSecretKey(key *string) *string { + if key == nil { + return nil + } + + newKey := auth.HideSecretKey(*key) + return &newKey +} + +func unmarshalConfV2(content []byte) (*Config, error) { + var config Config + + err := yaml.Unmarshal(content, &config) + if err != nil { + return nil, err + } + return &config, nil +} + +// MustLoadConfig is like LoadConfig but panic instead of returning an error. +func MustLoadConfig() *Config { + c, err := LoadConfigFromPath(GetConfigPath()) + if err != nil { + panic(err) + } + return c +} + +// LoadConfig read the config from the default path. +func LoadConfig() (*Config, error) { + return LoadConfigFromPath(GetConfigPath()) +} + +// LoadConfigFromPath read the config from the given path. +func LoadConfigFromPath(path string) (*Config, error) { + _, err := os.Stat(path) + if os.IsNotExist(err) { + return nil, configFileNotFound(path) + } + if err != nil { + return nil, err + } + + file, err := ioutil.ReadFile(path) + if err != nil { + return nil, errors.Wrap(err, "cannot read config file") + } + + _, err = unmarshalConfV1(file) + if err == nil { + // reject V1 config + return nil, errors.New("found legacy config in %s: legacy config is not allowed, please switch to the new config file format: %s", path, documentationLink) + } + + confV2, err := unmarshalConfV2(file) + if err != nil { + return nil, errors.Wrap(err, "content of config file %s is invalid", path) + } + + return confV2, nil +} + +// GetProfile returns the profile corresponding to the given profile name. +func (c *Config) GetProfile(profileName string) (*Profile, error) { + if profileName == "" { + return nil, errors.New("profileName cannot be empty") + } + + if profileName == DefaultProfileName { + return &c.Profile, nil + } + + p, exist := c.Profiles[profileName] + if !exist { + return nil, errors.New("given profile %s does not exist", profileName) + } + + // Merge selected profile on top of default profile + return MergeProfiles(&c.Profile, p), nil +} + +// GetActiveProfile returns the active profile of the config based on the following order: +// env SCW_PROFILE > config active_profile > config root profile +func (c *Config) GetActiveProfile() (*Profile, error) { + switch { + case os.Getenv(ScwActiveProfileEnv) != "": + logger.Debugf("using active profile from env: %s=%s", ScwActiveProfileEnv, os.Getenv(ScwActiveProfileEnv)) + return c.GetProfile(os.Getenv(ScwActiveProfileEnv)) + case c.ActiveProfile != nil: + logger.Debugf("using active profile from config: active_profile=%s", ScwActiveProfileEnv, *c.ActiveProfile) + return c.GetProfile(*c.ActiveProfile) + default: + return &c.Profile, nil + } +} + +// SaveTo will save the config to the default config path. This +// action will overwrite the previous file when it exists. +func (c *Config) Save() error { + return c.SaveTo(GetConfigPath()) +} + +// HumanConfig will generate a config file with documented arguments. +func (c *Config) HumanConfig() (string, error) { + tmpl, err := template.New("configuration").Parse(configFileTemplate) + if err != nil { + return "", err + } + + var buf bytes.Buffer + err = tmpl.Execute(&buf, c) + if err != nil { + return "", err + } + + return buf.String(), nil +} + +// SaveTo will save the config to the given path. This action will +// overwrite the previous file when it exists. +func (c *Config) SaveTo(path string) error { + path = filepath.Clean(path) + + // STEP 1: Render the configuration file as a file + file, err := c.HumanConfig() + if err != nil { + return err + } + + // STEP 2: create config path dir in cases it didn't exist before + err = os.MkdirAll(filepath.Dir(path), 0700) + if err != nil { + return err + } + + // STEP 3: write new config file + err = ioutil.WriteFile(path, []byte(file), defaultConfigPermission) + if err != nil { + return err + } + + return nil +} + +// MergeProfiles merges profiles in a new one. The last profile has priority. +func MergeProfiles(original *Profile, others ...*Profile) *Profile { + np := &Profile{ + AccessKey: original.AccessKey, + SecretKey: original.SecretKey, + APIURL: original.APIURL, + Insecure: original.Insecure, + DefaultOrganizationID: original.DefaultOrganizationID, + DefaultProjectID: original.DefaultProjectID, + DefaultRegion: original.DefaultRegion, + DefaultZone: original.DefaultZone, + } + + for _, other := range others { + if other.AccessKey != nil { + np.AccessKey = other.AccessKey + } + if other.SecretKey != nil { + np.SecretKey = other.SecretKey + } + if other.APIURL != nil { + np.APIURL = other.APIURL + } + if other.Insecure != nil { + np.Insecure = other.Insecure + } + if other.DefaultOrganizationID != nil { + np.DefaultOrganizationID = other.DefaultOrganizationID + } + if other.DefaultProjectID != nil { + np.DefaultProjectID = other.DefaultProjectID + } + if other.DefaultRegion != nil { + np.DefaultRegion = other.DefaultRegion + } + if other.DefaultZone != nil { + np.DefaultZone = other.DefaultZone + } + } + + return np +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/config_legacy.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/config_legacy.go new file mode 100644 index 000000000..9a81df685 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/config_legacy.go @@ -0,0 +1,92 @@ +package scw + +import ( + "encoding/json" + "io/ioutil" + "os" + "path/filepath" + + "github.com/scaleway/scaleway-sdk-go/internal/errors" + "github.com/scaleway/scaleway-sdk-go/logger" + "gopkg.in/yaml.v2" +) + +// configV1 is a Scaleway CLI configuration file +type configV1 struct { + // Organization is the identifier of the Scaleway organization + Organization string `json:"organization"` + + // Token is the authentication token for the Scaleway organization + Token string `json:"token"` + + // Version is the actual version of scw CLI + Version string `json:"version"` +} + +func unmarshalConfV1(content []byte) (*configV1, error) { + var config configV1 + err := json.Unmarshal(content, &config) + if err != nil { + return nil, err + } + return &config, err +} + +func (v1 *configV1) toV2() *Config { + return &Config{ + Profile: Profile{ + DefaultOrganizationID: &v1.Organization, + DefaultProjectID: &v1.Organization, // v1 config is not aware of project, so default project is set to organization ID + SecretKey: &v1.Token, + // ignore v1 version + }, + } +} + +// MigrateLegacyConfig will migrate the legacy config to the V2 when none exist yet. +// Returns a boolean set to true when the migration happened. +// TODO: get accesskey from account? +func MigrateLegacyConfig() (bool, error) { + // STEP 1: try to load config file V2 + v2Path, v2PathOk := getConfigV2FilePath() + if !v2PathOk || fileExist(v2Path) { + return false, nil + } + + // STEP 2: try to load config file V1 + v1Path, v1PathOk := getConfigV1FilePath() + if !v1PathOk { + return false, nil + } + file, err := ioutil.ReadFile(v1Path) + if err != nil { + return false, nil + } + confV1, err := unmarshalConfV1(file) + if err != nil { + return false, errors.Wrap(err, "content of config file %s is invalid json", v1Path) + } + + // STEP 3: create dir + err = os.MkdirAll(filepath.Dir(v2Path), 0700) + if err != nil { + return false, errors.Wrap(err, "mkdir did not work on %s", filepath.Dir(v2Path)) + } + + // STEP 4: marshal yaml config + newConfig := confV1.toV2() + file, err = yaml.Marshal(newConfig) + if err != nil { + return false, err + } + + // STEP 5: save config + err = ioutil.WriteFile(v2Path, file, defaultConfigPermission) + if err != nil { + return false, errors.Wrap(err, "cannot write file %s", v2Path) + } + + // STEP 6: log success + logger.Warningf("migrated existing config to %s", v2Path) + return true, nil +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/convert.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/convert.go new file mode 100644 index 000000000..7b671dcf5 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/convert.go @@ -0,0 +1,177 @@ +package scw + +import ( + "net" + "time" +) + +// StringPtr returns a pointer to the string value passed in. +func StringPtr(v string) *string { + return &v +} + +// StringSlicePtr converts a slice of string values into a slice of +// string pointers +func StringSlicePtr(src []string) []*string { + dst := make([]*string, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// StringsPtr returns a pointer to the []string value passed in. +func StringsPtr(v []string) *[]string { + return &v +} + +// StringsSlicePtr converts a slice of []string values into a slice of +// []string pointers +func StringsSlicePtr(src [][]string) []*[]string { + dst := make([]*[]string, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// BytesPtr returns a pointer to the []byte value passed in. +func BytesPtr(v []byte) *[]byte { + return &v +} + +// BytesSlicePtr converts a slice of []byte values into a slice of +// []byte pointers +func BytesSlicePtr(src [][]byte) []*[]byte { + dst := make([]*[]byte, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// BoolPtr returns a pointer to the bool value passed in. +func BoolPtr(v bool) *bool { + return &v +} + +// BoolSlicePtr converts a slice of bool values into a slice of +// bool pointers +func BoolSlicePtr(src []bool) []*bool { + dst := make([]*bool, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Int32Ptr returns a pointer to the int32 value passed in. +func Int32Ptr(v int32) *int32 { + return &v +} + +// Int32SlicePtr converts a slice of int32 values into a slice of +// int32 pointers +func Int32SlicePtr(src []int32) []*int32 { + dst := make([]*int32, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Int64Ptr returns a pointer to the int64 value passed in. +func Int64Ptr(v int64) *int64 { + return &v +} + +// Int64SlicePtr converts a slice of int64 values into a slice of +// int64 pointers +func Int64SlicePtr(src []int64) []*int64 { + dst := make([]*int64, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Uint32Ptr returns a pointer to the uint32 value passed in. +func Uint32Ptr(v uint32) *uint32 { + return &v +} + +// Uint32SlicePtr converts a slice of uint32 values into a slice of +// uint32 pointers +func Uint32SlicePtr(src []uint32) []*uint32 { + dst := make([]*uint32, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Uint64Ptr returns a pointer to the uint64 value passed in. +func Uint64Ptr(v uint64) *uint64 { + return &v +} + +// Uint64SlicePtr converts a slice of uint64 values into a slice of +// uint64 pointers +func Uint64SlicePtr(src []uint64) []*uint64 { + dst := make([]*uint64, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Float32Ptr returns a pointer to the float32 value passed in. +func Float32Ptr(v float32) *float32 { + return &v +} + +// Float32SlicePtr converts a slice of float32 values into a slice of +// float32 pointers +func Float32SlicePtr(src []float32) []*float32 { + dst := make([]*float32, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// Float64Ptr returns a pointer to the float64 value passed in. +func Float64Ptr(v float64) *float64 { + return &v +} + +// Float64SlicePtr converts a slice of float64 values into a slice of +// float64 pointers +func Float64SlicePtr(src []float64) []*float64 { + dst := make([]*float64, len(src)) + for i := 0; i < len(src); i++ { + dst[i] = &(src[i]) + } + return dst +} + +// TimeDurationPtr returns a pointer to the Duration value passed in. +// Deprecated: the use of time.Duration in request is deprecated and only available in lb API +func TimeDurationPtr(v time.Duration) *time.Duration { + return &v +} + +// TimePtr returns a pointer to the Time value passed in. +func TimePtr(v time.Time) *time.Time { + return &v +} + +// SizePtr returns a pointer to the Size value passed in. +func SizePtr(v Size) *Size { + return &v +} + +// IPPtr returns a pointer to the net.IP value passed in. +func IPPtr(v net.IP) *net.IP { + return &v +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/custom_types.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/custom_types.go new file mode 100644 index 000000000..75da2b159 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/custom_types.go @@ -0,0 +1,339 @@ +package scw + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net" + "strconv" + "strings" + "time" + + "github.com/scaleway/scaleway-sdk-go/internal/errors" + "github.com/scaleway/scaleway-sdk-go/logger" +) + +// ServiceInfo contains API metadata +// These metadata are only here for debugging. Do not rely on these values +type ServiceInfo struct { + // Name is the name of the API + Name string `json:"name"` + + // Description is a human readable description for the API + Description string `json:"description"` + + // Version is the version of the API + Version string `json:"version"` + + // DocumentationURL is the a web url where the documentation of the API can be found + DocumentationURL *string `json:"documentation_url"` +} + +// File is the structure used to receive / send a file from / to the API +type File struct { + // Name of the file + Name string `json:"name"` + + // ContentType used in the HTTP header `Content-Type` + ContentType string `json:"content_type"` + + // Content of the file + Content io.Reader `json:"content"` +} + +func (f *File) UnmarshalJSON(b []byte) error { + type file File + var tmpFile struct { + file + Content []byte `json:"content"` + } + + err := json.Unmarshal(b, &tmpFile) + if err != nil { + return err + } + + tmpFile.file.Content = bytes.NewReader(tmpFile.Content) + + *f = File(tmpFile.file) + return nil +} + +// Money represents an amount of money with its currency type. +type Money struct { + // CurrencyCode is the 3-letter currency code defined in ISO 4217. + CurrencyCode string `json:"currency_code"` + + // Units is the whole units of the amount. + // For example if `currencyCode` is `"USD"`, then 1 unit is one US dollar. + Units int64 `json:"units"` + + // Nanos is the number of nano (10^-9) units of the amount. + // The value must be between -999,999,999 and +999,999,999 inclusive. + // If `units` is positive, `nanos` must be positive or zero. + // If `units` is zero, `nanos` can be positive, zero, or negative. + // If `units` is negative, `nanos` must be negative or zero. + // For example $-1.75 is represented as `units`=-1 and `nanos`=-750,000,000. + Nanos int32 `json:"nanos"` +} + +// NewMoneyFromFloat converts a float with currency to a Money. +// +// value: The float value. +// currencyCode: The 3-letter currency code defined in ISO 4217. +// precision: The number of digits after the decimal point used to parse the nanos part of the value. +// +// Examples: +// - (value = 1.3333, precision = 2) => Money{Units = 1, Nanos = 330000000} +// - (value = 1.123456789, precision = 9) => Money{Units = 1, Nanos = 123456789} +func NewMoneyFromFloat(value float64, currencyCode string, precision int) *Money { + if precision > 9 { + panic(fmt.Errorf("max precision is 9")) + } + + strValue := strconv.FormatFloat(value, 'f', precision, 64) + units, nanos, err := splitFloatString(strValue) + if err != nil { + panic(err) + } + + return &Money{ + CurrencyCode: currencyCode, + Units: units, + Nanos: nanos, + } +} + +// String returns the string representation of Money. +func (m Money) String() string { + currencySignsByCodes := map[string]string{ + "EUR": "€", + "USD": "$", + } + + currencySign, currencySignFound := currencySignsByCodes[m.CurrencyCode] + if !currencySignFound { + logger.Debugf("%s currency code is not supported", m.CurrencyCode) + currencySign = m.CurrencyCode + } + + cents := fmt.Sprintf("%09d", m.Nanos) + cents = cents[:2] + strings.TrimRight(cents[2:], "0") + + return fmt.Sprintf("%s %d.%s", currencySign, m.Units, cents) +} + +// ToFloat converts a Money object to a float. +func (m Money) ToFloat() float64 { + return float64(m.Units) + float64(m.Nanos)/1e9 +} + +// Size represents a size in bytes. +type Size uint64 + +const ( + B Size = 1 + KB = 1000 * B + MB = 1000 * KB + GB = 1000 * MB + TB = 1000 * GB + PB = 1000 * TB +) + +// String returns the string representation of a Size. +func (s Size) String() string { + return fmt.Sprintf("%d", s) +} + +// TimeSeries represents a time series that could be used for graph purposes. +type TimeSeries struct { + // Name of the metric. + Name string `json:"name"` + + // Points contains all the points that composed the series. + Points []*TimeSeriesPoint `json:"points"` + + // Metadata contains some string metadata related to a metric. + Metadata map[string]string `json:"metadata"` +} + +// TimeSeriesPoint represents a point of a time series. +type TimeSeriesPoint struct { + Timestamp time.Time + Value float32 +} + +func (tsp TimeSeriesPoint) MarshalJSON() ([]byte, error) { + timestamp := tsp.Timestamp.Format(time.RFC3339) + value, err := json.Marshal(tsp.Value) + if err != nil { + return nil, err + } + + return []byte(`["` + timestamp + `",` + string(value) + "]"), nil +} + +func (tsp *TimeSeriesPoint) UnmarshalJSON(b []byte) error { + point := [2]interface{}{} + + err := json.Unmarshal(b, &point) + if err != nil { + return err + } + + if len(point) != 2 { + return fmt.Errorf("invalid point array") + } + + strTimestamp, isStrTimestamp := point[0].(string) + if !isStrTimestamp { + return fmt.Errorf("%s timestamp is not a string in RFC 3339 format", point[0]) + } + timestamp, err := time.Parse(time.RFC3339, strTimestamp) + if err != nil { + return fmt.Errorf("%s timestamp is not in RFC 3339 format", point[0]) + } + tsp.Timestamp = timestamp + + // By default, JSON unmarshal a float in float64 but the TimeSeriesPoint is a float32 value. + value, isValue := point[1].(float64) + if !isValue { + return fmt.Errorf("%s is not a valid float32 value", point[1]) + } + tsp.Value = float32(value) + + return nil +} + +// IPNet inherits net.IPNet and represents an IP network. +type IPNet struct { + net.IPNet +} + +func (n IPNet) MarshalJSON() ([]byte, error) { + value := n.String() + if value == "" { + value = "" + } + return []byte(`"` + value + `"`), nil +} + +func (n *IPNet) UnmarshalJSON(b []byte) error { + var str string + + err := json.Unmarshal(b, &str) + if err != nil { + return err + } + if str == "" { + *n = IPNet{} + return nil + } + + switch ip := net.ParseIP(str); { + case ip.To4() != nil: + str += "/32" + case ip.To16() != nil: + str += "/128" + } + + _, value, err := net.ParseCIDR(str) + if err != nil { + return err + } + n.IPNet = *value + + return nil +} + +// Duration represents a signed, fixed-length span of time represented as a +// count of seconds and fractions of seconds at nanosecond resolution. It is +// independent of any calendar and concepts like "day" or "month". It is related +// to Timestamp in that the difference between two Timestamp values is a Duration +// and it can be added or subtracted from a Timestamp. +// Range is approximately +-10,000 years. +type Duration struct { + Seconds int64 + Nanos int32 +} + +func (d *Duration) ToTimeDuration() *time.Duration { + if d == nil { + return nil + } + timeDuration := time.Duration(d.Nanos) + time.Duration(d.Seconds/1e9) + return &timeDuration +} + +func (d Duration) MarshalJSON() ([]byte, error) { + nanos := d.Nanos + if nanos < 0 { + nanos = -nanos + } + + return []byte(`"` + fmt.Sprintf("%d.%09d", d.Seconds, nanos) + `s"`), nil +} + +func (d *Duration) UnmarshalJSON(b []byte) error { + if string(b) == "null" { + return nil + } + var str string + + err := json.Unmarshal(b, &str) + if err != nil { + return err + } + if str == "" { + *d = Duration{} + return nil + } + + seconds, nanos, err := splitFloatString(strings.TrimRight(str, "s")) + if err != nil { + return err + } + + *d = Duration{ + Seconds: seconds, + Nanos: nanos, + } + + return nil +} + +// splitFloatString splits a float represented in a string, and returns its units (left-coma part) and nanos (right-coma part). +// E.g.: +// "3" ==> units = 3 | nanos = 0 +// "3.14" ==> units = 3 | nanos = 14*1e7 +// "-3.14" ==> units = -3 | nanos = -14*1e7 +func splitFloatString(input string) (units int64, nanos int32, err error) { + parts := strings.SplitN(input, ".", 2) + + // parse units as int64 + units, err = strconv.ParseInt(parts[0], 10, 64) + if err != nil { + return 0, 0, errors.Wrap(err, "invalid units") + } + + // handle nanos + if len(parts) == 2 { + // add leading zeros + strNanos := parts[1] + "000000000"[len(parts[1]):] + + // parse nanos as int32 + n, err := strconv.ParseUint(strNanos, 10, 32) + if err != nil { + return 0, 0, errors.Wrap(err, "invalid nanos") + } + + nanos = int32(n) + } + + if units < 0 { + nanos = -nanos + } + + return units, nanos, nil +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/env.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/env.go new file mode 100644 index 000000000..8672d8351 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/env.go @@ -0,0 +1,143 @@ +package scw + +import ( + "os" + "strconv" + + "github.com/scaleway/scaleway-sdk-go/logger" +) + +// Environment variables +const ( + // Up-to-date + ScwCacheDirEnv = "SCW_CACHE_DIR" + ScwConfigPathEnv = "SCW_CONFIG_PATH" + ScwAccessKeyEnv = "SCW_ACCESS_KEY" + ScwSecretKeyEnv = "SCW_SECRET_KEY" // #nosec G101 + ScwActiveProfileEnv = "SCW_PROFILE" + ScwAPIURLEnv = "SCW_API_URL" + ScwInsecureEnv = "SCW_INSECURE" + ScwDefaultOrganizationIDEnv = "SCW_DEFAULT_ORGANIZATION_ID" + ScwDefaultProjectIDEnv = "SCW_DEFAULT_PROJECT_ID" + ScwDefaultRegionEnv = "SCW_DEFAULT_REGION" + ScwDefaultZoneEnv = "SCW_DEFAULT_ZONE" + + // All deprecated (cli&terraform) + terraformAccessKeyEnv = "SCALEWAY_ACCESS_KEY" // used both as access key and secret key + terraformSecretKeyEnv = "SCALEWAY_TOKEN" + terraformOrganizationEnv = "SCALEWAY_ORGANIZATION" + terraformRegionEnv = "SCALEWAY_REGION" + cliTLSVerifyEnv = "SCW_TLSVERIFY" + cliOrganizationEnv = "SCW_ORGANIZATION" + cliRegionEnv = "SCW_REGION" + cliSecretKeyEnv = "SCW_TOKEN" + + // TBD + //cliVerboseEnv = "SCW_VERBOSE_API" + //cliDebugEnv = "DEBUG" + //cliNoCheckVersionEnv = "SCW_NOCHECKVERSION" + //cliTestWithRealAPIEnv = "TEST_WITH_REAL_API" + //cliSecureExecEnv = "SCW_SECURE_EXEC" + //cliGatewayEnv = "SCW_GATEWAY" + //cliSensitiveEnv = "SCW_SENSITIVE" + //cliAccountAPIEnv = "SCW_ACCOUNT_API" + //cliMetadataAPIEnv = "SCW_METADATA_API" + //cliMarketPlaceAPIEnv = "SCW_MARKETPLACE_API" + //cliComputePar1APIEnv = "SCW_COMPUTE_PAR1_API" + //cliComputeAms1APIEnv = "SCW_COMPUTE_AMS1_API" + //cliCommercialTypeEnv = "SCW_COMMERCIAL_TYPE" + //cliTargetArchEnv = "SCW_TARGET_ARCH" +) + +const ( + v1RegionFrPar = "par1" + v1RegionNlAms = "ams1" +) + +func LoadEnvProfile() *Profile { + p := &Profile{} + + accessKey, _, envExist := getEnv(ScwAccessKeyEnv, terraformAccessKeyEnv) + if envExist { + p.AccessKey = &accessKey + } + + secretKey, _, envExist := getEnv(ScwSecretKeyEnv, cliSecretKeyEnv, terraformSecretKeyEnv, terraformAccessKeyEnv) + if envExist { + p.SecretKey = &secretKey + } + + apiURL, _, envExist := getEnv(ScwAPIURLEnv) + if envExist { + p.APIURL = &apiURL + } + + insecureValue, envKey, envExist := getEnv(ScwInsecureEnv, cliTLSVerifyEnv) + if envExist { + insecure, err := strconv.ParseBool(insecureValue) + if err != nil { + logger.Warningf("env variable %s cannot be parsed: %s is invalid boolean", envKey, insecureValue) + } + + if envKey == cliTLSVerifyEnv { + insecure = !insecure // TLSVerify is the inverse of Insecure + } + + p.Insecure = &insecure + } + + organizationID, _, envExist := getEnv(ScwDefaultOrganizationIDEnv, cliOrganizationEnv, terraformOrganizationEnv) + if envExist { + p.DefaultOrganizationID = &organizationID + } + + projectID, _, envExist := getEnv(ScwDefaultProjectIDEnv) + if envExist { + p.DefaultProjectID = &projectID + } + + region, _, envExist := getEnv(ScwDefaultRegionEnv, cliRegionEnv, terraformRegionEnv) + if envExist { + region = v1RegionToV2(region) + p.DefaultRegion = ®ion + } + + zone, _, envExist := getEnv(ScwDefaultZoneEnv) + if envExist { + p.DefaultZone = &zone + } + + return p +} + +func getEnv(upToDateKey string, deprecatedKeys ...string) (string, string, bool) { + value, exist := os.LookupEnv(upToDateKey) + if exist { + logger.Debugf("reading value from %s", upToDateKey) + return value, upToDateKey, true + } + + for _, key := range deprecatedKeys { + value, exist := os.LookupEnv(key) + if exist { + logger.Debugf("reading value from %s", key) + logger.Warningf("%s is deprecated, please use %s instead", key, upToDateKey) + return value, key, true + } + } + + return "", "", false +} + +func v1RegionToV2(region string) string { + switch region { + case v1RegionFrPar: + logger.Warningf("par1 is a deprecated name for region, use fr-par instead") + return "fr-par" + case v1RegionNlAms: + logger.Warningf("ams1 is a deprecated name for region, use nl-ams instead") + return "nl-ams" + default: + return region + } +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/errors.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/errors.go new file mode 100644 index 000000000..9c0785a9e --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/errors.go @@ -0,0 +1,484 @@ +package scw + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "sort" + "strings" + "time" + + "github.com/scaleway/scaleway-sdk-go/internal/errors" + "github.com/scaleway/scaleway-sdk-go/validation" +) + +// SdkError is a base interface for all Scaleway SDK errors. +type SdkError interface { + Error() string + IsScwSdkError() +} + +// ResponseError is an error type for the Scaleway API +type ResponseError struct { + // Message is a human-friendly error message + Message string `json:"message"` + + // Type is a string code that defines the kind of error. This field is only used by instance API + Type string `json:"type,omitempty"` + + // Resource is a string code that defines the resource concerned by the error. This field is only used by instance API + Resource string `json:"resource,omitempty"` + + // Fields contains detail about validation error. This field is only used by instance API + Fields map[string][]string `json:"fields,omitempty"` + + // StatusCode is the HTTP status code received + StatusCode int `json:"-"` + + // Status is the HTTP status received + Status string `json:"-"` + + RawBody json.RawMessage `json:"-"` +} + +func (e *ResponseError) UnmarshalJSON(b []byte) error { + type tmpResponseError ResponseError + tmp := tmpResponseError(*e) + + err := json.Unmarshal(b, &tmp) + if err != nil { + return err + } + + tmp.Message = strings.ToLower(tmp.Message) + + *e = ResponseError(tmp) + return nil +} + +// IsScwSdkError implement SdkError interface +func (e *ResponseError) IsScwSdkError() {} +func (e *ResponseError) Error() string { + s := fmt.Sprintf("scaleway-sdk-go: http error %s", e.Status) + + if e.Resource != "" { + s = fmt.Sprintf("%s: resource %s", s, e.Resource) + } + + if e.Message != "" { + s = fmt.Sprintf("%s: %s", s, e.Message) + } + + if len(e.Fields) > 0 { + s = fmt.Sprintf("%s: %v", s, e.Fields) + } + + return s +} +func (e *ResponseError) GetRawBody() json.RawMessage { + return e.RawBody +} + +// hasResponseError returns an SdkError when the HTTP status is not OK. +func hasResponseError(res *http.Response) error { + if res.StatusCode >= 200 && res.StatusCode <= 299 { + return nil + } + + newErr := &ResponseError{ + StatusCode: res.StatusCode, + Status: res.Status, + } + + if res.Body == nil { + return newErr + } + + body, err := ioutil.ReadAll(res.Body) + if err != nil { + return errors.Wrap(err, "cannot read error response body") + } + newErr.RawBody = body + + // The error content is not encoded in JSON, only returns HTTP data. + if res.Header.Get("Content-Type") != "application/json" { + newErr.Message = res.Status + return newErr + } + + err = json.Unmarshal(body, newErr) + if err != nil { + return errors.Wrap(err, "could not parse error response body") + } + + err = unmarshalStandardError(newErr.Type, body) + if err != nil { + return err + } + + err = unmarshalNonStandardError(newErr.Type, body) + if err != nil { + return err + } + + return newErr +} + +func unmarshalStandardError(errorType string, body []byte) error { + var stdErr SdkError + + switch errorType { + case "invalid_arguments": + stdErr = &InvalidArgumentsError{RawBody: body} + case "quotas_exceeded": + stdErr = &QuotasExceededError{RawBody: body} + case "transient_state": + stdErr = &TransientStateError{RawBody: body} + case "not_found": + stdErr = &ResourceNotFoundError{RawBody: body} + case "locked": + stdErr = &ResourceLockedError{RawBody: body} + case "permissions_denied": + stdErr = &PermissionsDeniedError{RawBody: body} + case "out_of_stock": + stdErr = &OutOfStockError{RawBody: body} + case "resource_expired": + stdErr = &ResourceExpiredError{RawBody: body} + default: + return nil + } + + err := json.Unmarshal(body, stdErr) + if err != nil { + return errors.Wrap(err, "could not parse error %s response body", errorType) + } + + return stdErr +} + +func unmarshalNonStandardError(errorType string, body []byte) error { + switch errorType { + // Only in instance API. + + case "unknown_resource": + unknownResourceError := &UnknownResource{RawBody: body} + err := json.Unmarshal(body, unknownResourceError) + if err != nil { + return errors.Wrap(err, "could not parse error %s response body", errorType) + } + return unknownResourceError.ToResourceNotFoundError() + + case "invalid_request_error": + invalidRequestError := &InvalidRequestError{RawBody: body} + err := json.Unmarshal(body, invalidRequestError) + if err != nil { + return errors.Wrap(err, "could not parse error %s response body", errorType) + } + + invalidArgumentsError := invalidRequestError.ToInvalidArgumentsError() + if invalidArgumentsError != nil { + return invalidArgumentsError + } + + quotasExceededError := invalidRequestError.ToQuotasExceededError() + if quotasExceededError != nil { + return quotasExceededError + } + + // At this point, the invalid_request_error is not an InvalidArgumentsError and + // the default marshalling will be used. + return nil + + default: + return nil + } +} + +type InvalidArgumentsErrorDetail struct { + ArgumentName string `json:"argument_name"` + Reason string `json:"reason"` + HelpMessage string `json:"help_message"` +} + +type InvalidArgumentsError struct { + Details []InvalidArgumentsErrorDetail `json:"details"` + + RawBody json.RawMessage `json:"-"` +} + +// IsScwSdkError implements the SdkError interface +func (e *InvalidArgumentsError) IsScwSdkError() {} +func (e *InvalidArgumentsError) Error() string { + invalidArgs := make([]string, len(e.Details)) + for i, d := range e.Details { + invalidArgs[i] = d.ArgumentName + switch d.Reason { + case "unknown": + invalidArgs[i] += " is invalid for unexpected reason" + case "required": + invalidArgs[i] += " is required" + case "format": + invalidArgs[i] += " is wrongly formatted" + case "constraint": + invalidArgs[i] += " does not respect constraint" + } + if d.HelpMessage != "" { + invalidArgs[i] += ", " + d.HelpMessage + } + } + + return "scaleway-sdk-go: invalid argument(s): " + strings.Join(invalidArgs, "; ") +} +func (e *InvalidArgumentsError) GetRawBody() json.RawMessage { + return e.RawBody +} + +// UnknownResource is only returned by the instance API. +// Warning: this is not a standard error. +type UnknownResource struct { + Message string `json:"message"` + RawBody json.RawMessage `json:"-"` +} + +// ToSdkError returns a standard error InvalidArgumentsError or nil Fields is nil. +func (e *UnknownResource) ToResourceNotFoundError() SdkError { + resourceNotFound := &ResourceNotFoundError{ + RawBody: e.RawBody, + } + + messageParts := strings.Split(e.Message, `"`) + + // Some errors uses ' and not " + if len(messageParts) == 1 { + messageParts = strings.Split(e.Message, "'") + } + + switch len(messageParts) { + case 2: // message like: `"111..." not found` + resourceNotFound.ResourceID = messageParts[0] + case 3: // message like: `Security Group "111..." not found` + resourceNotFound.ResourceID = messageParts[1] + // transform `Security group ` to `security_group` + resourceNotFound.Resource = strings.ReplaceAll(strings.ToLower(strings.TrimSpace(messageParts[0])), " ", "_") + default: + return nil + } + if !validation.IsUUID(resourceNotFound.ResourceID) { + return nil + } + return resourceNotFound +} + +// InvalidRequestError is only returned by the instance API. +// Warning: this is not a standard error. +type InvalidRequestError struct { + Message string `json:"message"` + + Fields map[string][]string `json:"fields"` + + Resource string `json:"resource"` + + RawBody json.RawMessage `json:"-"` +} + +// ToSdkError returns a standard error InvalidArgumentsError or nil Fields is nil. +func (e *InvalidRequestError) ToInvalidArgumentsError() SdkError { + // If error has no fields, it is not an InvalidArgumentsError. + if e.Fields == nil || len(e.Fields) == 0 { + return nil + } + + invalidArguments := &InvalidArgumentsError{ + RawBody: e.RawBody, + } + fieldNames := []string(nil) + for fieldName := range e.Fields { + fieldNames = append(fieldNames, fieldName) + } + sort.Strings(fieldNames) + for _, fieldName := range fieldNames { + for _, message := range e.Fields[fieldName] { + invalidArguments.Details = append(invalidArguments.Details, InvalidArgumentsErrorDetail{ + ArgumentName: fieldName, + Reason: "constraint", + HelpMessage: message, + }) + } + } + return invalidArguments +} + +func (e *InvalidRequestError) ToQuotasExceededError() SdkError { + if !strings.Contains(strings.ToLower(e.Message), "quota exceeded for this resource") { + return nil + } + + return &QuotasExceededError{ + Details: []QuotasExceededErrorDetail{ + { + Resource: e.Resource, + Quota: 0, + Current: 0, + }, + }, + RawBody: e.RawBody, + } +} + +type QuotasExceededErrorDetail struct { + Resource string `json:"resource"` + Quota uint32 `json:"quota"` + Current uint32 `json:"current"` +} + +type QuotasExceededError struct { + Details []QuotasExceededErrorDetail `json:"details"` + RawBody json.RawMessage `json:"-"` +} + +// IsScwSdkError implements the SdkError interface +func (e *QuotasExceededError) IsScwSdkError() {} +func (e *QuotasExceededError) Error() string { + invalidArgs := make([]string, len(e.Details)) + for i, d := range e.Details { + invalidArgs[i] = fmt.Sprintf("%s has reached its quota (%d/%d)", d.Resource, d.Current, d.Current) + } + + return "scaleway-sdk-go: quota exceeded(s): " + strings.Join(invalidArgs, "; ") +} +func (e *QuotasExceededError) GetRawBody() json.RawMessage { + return e.RawBody +} + +type PermissionsDeniedError struct { + Details []struct { + Resource string `json:"resource"` + Action string `json:"action"` + } `json:"details"` + + RawBody json.RawMessage `json:"-"` +} + +// IsScwSdkError implements the SdkError interface +func (e *PermissionsDeniedError) IsScwSdkError() {} +func (e *PermissionsDeniedError) Error() string { + invalidArgs := make([]string, len(e.Details)) + for i, d := range e.Details { + invalidArgs[i] = fmt.Sprintf("%s %s", d.Action, d.Resource) + } + + return "scaleway-sdk-go: insufficient permissions: " + strings.Join(invalidArgs, "; ") +} +func (e *PermissionsDeniedError) GetRawBody() json.RawMessage { + return e.RawBody +} + +type TransientStateError struct { + Resource string `json:"resource"` + ResourceID string `json:"resource_id"` + CurrentState string `json:"current_state"` + + RawBody json.RawMessage `json:"-"` +} + +// IsScwSdkError implements the SdkError interface +func (e *TransientStateError) IsScwSdkError() {} +func (e *TransientStateError) Error() string { + return fmt.Sprintf("scaleway-sdk-go: resource %s with ID %s is in a transient state: %s", e.Resource, e.ResourceID, e.CurrentState) +} +func (e *TransientStateError) GetRawBody() json.RawMessage { + return e.RawBody +} + +type ResourceNotFoundError struct { + Resource string `json:"resource"` + ResourceID string `json:"resource_id"` + + RawBody json.RawMessage `json:"-"` +} + +// IsScwSdkError implements the SdkError interface +func (e *ResourceNotFoundError) IsScwSdkError() {} +func (e *ResourceNotFoundError) Error() string { + return fmt.Sprintf("scaleway-sdk-go: resource %s with ID %s is not found", e.Resource, e.ResourceID) +} +func (e *ResourceNotFoundError) GetRawBody() json.RawMessage { + return e.RawBody +} + +type ResourceLockedError struct { + Resource string `json:"resource"` + ResourceID string `json:"resource_id"` + + RawBody json.RawMessage `json:"-"` +} + +// IsScwSdkError implements the SdkError interface +func (e *ResourceLockedError) IsScwSdkError() {} +func (e *ResourceLockedError) Error() string { + return fmt.Sprintf("scaleway-sdk-go: resource %s with ID %s is locked", e.Resource, e.ResourceID) +} +func (e *ResourceLockedError) GetRawBody() json.RawMessage { + return e.RawBody +} + +type OutOfStockError struct { + Resource string `json:"resource"` + + RawBody json.RawMessage `json:"-"` +} + +// IsScwSdkError implements the SdkError interface +func (e *OutOfStockError) IsScwSdkError() {} +func (e *OutOfStockError) Error() string { + return fmt.Sprintf("scaleway-sdk-go: resource %s is out of stock", e.Resource) +} +func (e *OutOfStockError) GetRawBody() json.RawMessage { + return e.RawBody +} + +// InvalidClientOptionError indicates that at least one of client data has been badly provided for the client creation. +type InvalidClientOptionError struct { + errorType string +} + +func NewInvalidClientOptionError(format string, a ...interface{}) *InvalidClientOptionError { + return &InvalidClientOptionError{errorType: fmt.Sprintf(format, a...)} +} + +// IsScwSdkError implements the SdkError interface +func (e InvalidClientOptionError) IsScwSdkError() {} +func (e InvalidClientOptionError) Error() string { + return fmt.Sprintf("scaleway-sdk-go: %s", e.errorType) +} + +// ConfigFileNotFound indicates that the config file could not be found +type ConfigFileNotFoundError struct { + path string +} + +func configFileNotFound(path string) *ConfigFileNotFoundError { + return &ConfigFileNotFoundError{path: path} +} + +// ConfigFileNotFoundError implements the SdkError interface +func (e ConfigFileNotFoundError) IsScwSdkError() {} +func (e ConfigFileNotFoundError) Error() string { + return fmt.Sprintf("scaleway-sdk-go: cannot read config file %s: no such file or directory", e.path) +} + +// ResourceExpiredError implements the SdkError interface +type ResourceExpiredError struct { + Resource string `json:"resource"` + ResourceID string `json:"resource_id"` + ExpiredSince time.Time `json:"expired_since"` + + RawBody json.RawMessage `json:"-"` +} + +func (r ResourceExpiredError) Error() string { + return fmt.Sprintf("scaleway-sdk-go: resource %s with ID %s expired since %s", r.Resource, r.ResourceID, r.ExpiredSince.String()) +} + +func (r ResourceExpiredError) IsScwSdkError() {} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/locality.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/locality.go new file mode 100644 index 000000000..9cf72987b --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/locality.go @@ -0,0 +1,198 @@ +package scw + +import ( + "encoding/json" + "fmt" + "strings" + + "github.com/scaleway/scaleway-sdk-go/internal/errors" + "github.com/scaleway/scaleway-sdk-go/logger" + "github.com/scaleway/scaleway-sdk-go/validation" +) + +// localityPartsSeparator is the separator used in Zone and Region +const localityPartsSeparator = "-" + +// Zone is an availability zone +type Zone string + +const ( + // ZoneFrPar1 represents the fr-par-1 zone + ZoneFrPar1 = Zone("fr-par-1") + // ZoneFrPar2 represents the fr-par-2 zone + ZoneFrPar2 = Zone("fr-par-2") + // ZoneNlAms1 represents the nl-ams-1 zone + ZoneNlAms1 = Zone("nl-ams-1") +) + +var ( + // AllZones is an array that list all zones + AllZones = []Zone{ + ZoneFrPar1, + ZoneFrPar2, + ZoneNlAms1, + } +) + +// Exists checks whether a zone exists +func (zone Zone) Exists() bool { + for _, z := range AllZones { + if z == zone { + return true + } + } + return false +} + +// String returns a Zone as a string +func (zone Zone) String() string { + return string(zone) +} + +// Region returns the parent Region for the Zone. +// Manipulates the string directly to allow unlisted zones formatted as xx-yyy-z. +func (zone Zone) Region() (Region, error) { + zoneStr := zone.String() + if !validation.IsZone(zoneStr) { + return "", fmt.Errorf("invalid zone '%v'", zoneStr) + } + zoneParts := strings.Split(zoneStr, localityPartsSeparator) + return Region(strings.Join(zoneParts[:2], localityPartsSeparator)), nil +} + +// Region is a geographical location +type Region string + +const ( + // RegionFrPar represents the fr-par region + RegionFrPar = Region("fr-par") + // RegionNlAms represents the nl-ams region + RegionNlAms = Region("nl-ams") +) + +var ( + // AllRegions is an array that list all regions + AllRegions = []Region{ + RegionFrPar, + RegionNlAms, + } +) + +// Exists checks whether a region exists +func (region Region) Exists() bool { + for _, r := range AllRegions { + if r == region { + return true + } + } + return false +} + +// GetZones is a function that returns the zones for the specified region +func (region Region) GetZones() []Zone { + switch region { + case RegionFrPar: + return []Zone{ZoneFrPar1, ZoneFrPar2} + case RegionNlAms: + return []Zone{ZoneNlAms1} + default: + return []Zone{} + } +} + +// ParseZone parses a string value into a Zone and returns an error if it has a bad format. +func ParseZone(zone string) (Zone, error) { + switch zone { + case "par1": + // would be triggered by API market place + // logger.Warningf("par1 is a deprecated name for zone, use fr-par-1 instead") + return ZoneFrPar1, nil + case "ams1": + // would be triggered by API market place + // logger.Warningf("ams1 is a deprecated name for zone, use nl-ams-1 instead") + return ZoneNlAms1, nil + default: + if !validation.IsZone(zone) { + zones := []string(nil) + for _, z := range AllZones { + zones = append(zones, string(z)) + } + return "", errors.New("bad zone format, available zones are: %s", strings.Join(zones, ", ")) + } + + newZone := Zone(zone) + if !newZone.Exists() { + logger.Infof("%s is an unknown zone\n", newZone) + } + return newZone, nil + } +} + +// UnmarshalJSON implements the Unmarshaler interface for a Zone. +// this to call ParseZone on the string input and return the correct Zone object. +func (zone *Zone) UnmarshalJSON(input []byte) error { + // parse input value as string + var stringValue string + err := json.Unmarshal(input, &stringValue) + if err != nil { + return err + } + + // parse string as Zone + *zone, err = ParseZone(stringValue) + if err != nil { + return err + } + return nil +} + +// ParseRegion parses a string value into a Region and returns an error if it has a bad format. +func ParseRegion(region string) (Region, error) { + switch region { + case "par1": + // would be triggered by API market place + // logger.Warningf("par1 is a deprecated name for region, use fr-par instead") + return RegionFrPar, nil + case "ams1": + // would be triggered by API market place + // logger.Warningf("ams1 is a deprecated name for region, use nl-ams instead") + return RegionNlAms, nil + default: + if !validation.IsRegion(region) { + regions := []string(nil) + for _, r := range AllRegions { + regions = append(regions, string(r)) + } + return "", errors.New("bad region format, available regions are: %s", strings.Join(regions, ", ")) + } + + newRegion := Region(region) + if !newRegion.Exists() { + logger.Infof("%s is an unknown region\n", newRegion) + } + return newRegion, nil + } +} + +// UnmarshalJSON implements the Unmarshaler interface for a Region. +// this to call ParseRegion on the string input and return the correct Region object. +func (region *Region) UnmarshalJSON(input []byte) error { + // parse input value as string + var stringValue string + err := json.Unmarshal(input, &stringValue) + if err != nil { + return err + } + + // parse string as Region + *region, err = ParseRegion(stringValue) + if err != nil { + return err + } + return nil +} + +// String returns a Region as a string +func (region Region) String() string { + return string(region) +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/path.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/path.go new file mode 100644 index 000000000..0c90adace --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/path.go @@ -0,0 +1,98 @@ +package scw + +import ( + "errors" + "os" + "path/filepath" +) + +const ( + // XDG wiki: https://wiki.archlinux.org/index.php/XDG_Base_Directory + xdgConfigDirEnv = "XDG_CONFIG_HOME" + xdgCacheDirEnv = "XDG_CACHE_HOME" + + unixHomeDirEnv = "HOME" + windowsHomeDirEnv = "USERPROFILE" + + defaultConfigFileName = "config.yaml" +) + +var ( + // ErrNoHomeDir errors when no user directory is found + ErrNoHomeDir = errors.New("user home directory not found") +) + +// GetCacheDirectory returns the default cache directory. +// Cache directory is based on the following priority order: +// - $SCW_CACHE_DIR +// - $XDG_CACHE_HOME/scw +// - $HOME/.cache/scw +// - $USERPROFILE/.cache/scw +func GetCacheDirectory() string { + cacheDir := "" + switch { + case os.Getenv(ScwCacheDirEnv) != "": + cacheDir = os.Getenv(ScwCacheDirEnv) + case os.Getenv(xdgCacheDirEnv) != "": + cacheDir = filepath.Join(os.Getenv(xdgCacheDirEnv), "scw") + case os.Getenv(unixHomeDirEnv) != "": + cacheDir = filepath.Join(os.Getenv(unixHomeDirEnv), ".cache", "scw") + case os.Getenv(windowsHomeDirEnv) != "": + cacheDir = filepath.Join(os.Getenv(windowsHomeDirEnv), ".cache", "scw") + default: + // TODO: fallback on local folder? + } + + // Clean the cache directory path when exiting the function + return filepath.Clean(cacheDir) +} + +// GetConfigPath returns the default path. +// Default path is based on the following priority order: +// - $SCW_CONFIG_PATH +// - $XDG_CONFIG_HOME/scw/config.yaml +// - $HOME/.config/scw/config.yaml +// - $USERPROFILE/.config/scw/config.yaml +func GetConfigPath() string { + configPath := os.Getenv(ScwConfigPathEnv) + if configPath == "" { + configPath, _ = getConfigV2FilePath() + } + return filepath.Clean(configPath) +} + +// getConfigV2FilePath returns the path to the v2 config file +func getConfigV2FilePath() (string, bool) { + configDir, err := GetScwConfigDir() + if err != nil { + return "", false + } + return filepath.Clean(filepath.Join(configDir, defaultConfigFileName)), true +} + +// getConfigV1FilePath returns the path to the v1 config file +func getConfigV1FilePath() (string, bool) { + path, err := os.UserHomeDir() + if err != nil { + return "", false + } + return filepath.Clean(filepath.Join(path, ".scwrc")), true +} + +// GetScwConfigDir returns the path to scw config folder +func GetScwConfigDir() (string, error) { + if xdgPath := os.Getenv(xdgConfigDirEnv); xdgPath != "" { + return filepath.Join(xdgPath, "scw"), nil + } + + homeDir, err := os.UserHomeDir() + if err != nil { + return "", err + } + return filepath.Join(homeDir, ".config", "scw"), nil +} + +func fileExist(name string) bool { + _, err := os.Stat(name) + return err == nil +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/request.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/request.go new file mode 100644 index 000000000..19f0dd4d5 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/request.go @@ -0,0 +1,104 @@ +package scw + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/url" + + "github.com/scaleway/scaleway-sdk-go/internal/auth" + "github.com/scaleway/scaleway-sdk-go/internal/errors" +) + +// ScalewayRequest contains all the contents related to performing a request on the Scaleway API. +type ScalewayRequest struct { + Method string + Path string + Headers http.Header + Query url.Values + Body io.Reader + + // request options + ctx context.Context + auth auth.Auth + allPages bool +} + +// getAllHeaders constructs a http.Header object and aggregates all headers into the object. +func (req *ScalewayRequest) getAllHeaders(token auth.Auth, userAgent string, anonymized bool) http.Header { + var allHeaders http.Header + if anonymized { + allHeaders = token.AnonymizedHeaders() + } else { + allHeaders = token.Headers() + } + + allHeaders.Set("User-Agent", userAgent) + if req.Body != nil { + allHeaders.Set("Content-Type", "application/json") + } + for key, value := range req.Headers { + allHeaders.Del(key) + for _, v := range value { + allHeaders.Add(key, v) + } + } + + return allHeaders +} + +// getURL constructs a URL based on the base url and the client. +func (req *ScalewayRequest) getURL(baseURL string) (*url.URL, error) { + url, err := url.Parse(baseURL + req.Path) + if err != nil { + return nil, errors.New("invalid url %s: %s", baseURL+req.Path, err) + } + url.RawQuery = req.Query.Encode() + + return url, nil +} + +// SetBody json marshal the given body and write the json content type +// to the request. It also catches when body is a file. +func (req *ScalewayRequest) SetBody(body interface{}) error { + var contentType string + var content io.Reader + + switch b := body.(type) { + case *File: + contentType = b.ContentType + content = b.Content + case io.Reader: + contentType = "text/plain" + content = b + default: + buf, err := json.Marshal(body) + if err != nil { + return err + } + contentType = "application/json" + content = bytes.NewReader(buf) + } + + if req.Headers == nil { + req.Headers = http.Header{} + } + + req.Headers.Set("Content-Type", contentType) + req.Body = content + + return nil +} + +func (req *ScalewayRequest) apply(opts []RequestOption) { + for _, opt := range opts { + opt(req) + } +} + +func (req *ScalewayRequest) validate() error { + // nothing so far + return nil +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/request_option.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/request_option.go new file mode 100644 index 000000000..a5ff37663 --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/request_option.go @@ -0,0 +1,32 @@ +package scw + +import ( + "context" + + "github.com/scaleway/scaleway-sdk-go/internal/auth" +) + +// RequestOption is a function that applies options to a ScalewayRequest. +type RequestOption func(*ScalewayRequest) + +// WithContext request option sets the context of a ScalewayRequest +func WithContext(ctx context.Context) RequestOption { + return func(s *ScalewayRequest) { + s.ctx = ctx + } +} + +// WithAllPages aggregate all pages in the response of a List request. +// Will error when pagination is not supported on the request. +func WithAllPages() RequestOption { + return func(s *ScalewayRequest) { + s.allPages = true + } +} + +// WithAuthRequest overwrites the client access key and secret key used in the request. +func WithAuthRequest(accessKey, secretKey string) RequestOption { + return func(s *ScalewayRequest) { + s.auth = auth.NewToken(accessKey, secretKey) + } +} diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/scw/version.go b/vendor/github.com/scaleway/scaleway-sdk-go/scw/version.go new file mode 100644 index 000000000..22bdfa2fc --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/scw/version.go @@ -0,0 +1,11 @@ +package scw + +import ( + "fmt" + "runtime" +) + +// TODO: versioning process +const version = "v1.0.0-beta.6+dev" + +var userAgent = fmt.Sprintf("scaleway-sdk-go/%s (%s; %s; %s)", version, runtime.Version(), runtime.GOOS, runtime.GOARCH) diff --git a/vendor/github.com/scaleway/scaleway-sdk-go/validation/is.go b/vendor/github.com/scaleway/scaleway-sdk-go/validation/is.go new file mode 100644 index 000000000..a7e52d0bd --- /dev/null +++ b/vendor/github.com/scaleway/scaleway-sdk-go/validation/is.go @@ -0,0 +1,61 @@ +// Package validation provides format validation functions. +package validation + +import ( + "net/url" + "regexp" +) + +var ( + isUUIDRegexp = regexp.MustCompile("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$") + isRegionRegex = regexp.MustCompile("^[a-z]{2}-[a-z]{3}$") + isZoneRegex = regexp.MustCompile("^[a-z]{2}-[a-z]{3}-[1-9]$") + isAccessKey = regexp.MustCompile("^SCW[A-Z0-9]{17}$") + isEmailRegexp = regexp.MustCompile("^.+@.+$") +) + +// IsUUID returns true if the given string has a valid UUID format. +func IsUUID(s string) bool { + return isUUIDRegexp.MatchString(s) +} + +// IsAccessKey returns true if the given string has a valid Scaleway access key format. +func IsAccessKey(s string) bool { + return isAccessKey.MatchString(s) +} + +// IsSecretKey returns true if the given string has a valid Scaleway secret key format. +func IsSecretKey(s string) bool { + return IsUUID(s) +} + +// IsOrganizationID returns true if the given string has a valid Scaleway organization ID format. +func IsOrganizationID(s string) bool { + return IsUUID(s) +} + +// IsProjectID returns true if the given string has a valid Scaleway project ID format. +func IsProjectID(s string) bool { + return IsUUID(s) +} + +// IsRegion returns true if the given string has a valid region format. +func IsRegion(s string) bool { + return isRegionRegex.MatchString(s) +} + +// IsZone returns true if the given string has a valid zone format. +func IsZone(s string) bool { + return isZoneRegex.MatchString(s) +} + +// IsURL returns true if the given string has a valid URL format. +func IsURL(s string) bool { + _, err := url.Parse(s) + return err == nil +} + +// IsEmail returns true if the given string has an email format. +func IsEmail(v string) bool { + return isEmailRegexp.MatchString(v) +} diff --git a/vendor/golang.org/x/net/websocket/client.go b/vendor/golang.org/x/net/websocket/client.go new file mode 100644 index 000000000..69a4ac7ee --- /dev/null +++ b/vendor/golang.org/x/net/websocket/client.go @@ -0,0 +1,106 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package websocket + +import ( + "bufio" + "io" + "net" + "net/http" + "net/url" +) + +// DialError is an error that occurs while dialling a websocket server. +type DialError struct { + *Config + Err error +} + +func (e *DialError) Error() string { + return "websocket.Dial " + e.Config.Location.String() + ": " + e.Err.Error() +} + +// NewConfig creates a new WebSocket config for client connection. +func NewConfig(server, origin string) (config *Config, err error) { + config = new(Config) + config.Version = ProtocolVersionHybi13 + config.Location, err = url.ParseRequestURI(server) + if err != nil { + return + } + config.Origin, err = url.ParseRequestURI(origin) + if err != nil { + return + } + config.Header = http.Header(make(map[string][]string)) + return +} + +// NewClient creates a new WebSocket client connection over rwc. +func NewClient(config *Config, rwc io.ReadWriteCloser) (ws *Conn, err error) { + br := bufio.NewReader(rwc) + bw := bufio.NewWriter(rwc) + err = hybiClientHandshake(config, br, bw) + if err != nil { + return + } + buf := bufio.NewReadWriter(br, bw) + ws = newHybiClientConn(config, buf, rwc) + return +} + +// Dial opens a new client connection to a WebSocket. +func Dial(url_, protocol, origin string) (ws *Conn, err error) { + config, err := NewConfig(url_, origin) + if err != nil { + return nil, err + } + if protocol != "" { + config.Protocol = []string{protocol} + } + return DialConfig(config) +} + +var portMap = map[string]string{ + "ws": "80", + "wss": "443", +} + +func parseAuthority(location *url.URL) string { + if _, ok := portMap[location.Scheme]; ok { + if _, _, err := net.SplitHostPort(location.Host); err != nil { + return net.JoinHostPort(location.Host, portMap[location.Scheme]) + } + } + return location.Host +} + +// DialConfig opens a new client connection to a WebSocket with a config. +func DialConfig(config *Config) (ws *Conn, err error) { + var client net.Conn + if config.Location == nil { + return nil, &DialError{config, ErrBadWebSocketLocation} + } + if config.Origin == nil { + return nil, &DialError{config, ErrBadWebSocketOrigin} + } + dialer := config.Dialer + if dialer == nil { + dialer = &net.Dialer{} + } + client, err = dialWithDialer(dialer, config) + if err != nil { + goto Error + } + ws, err = NewClient(config, client) + if err != nil { + client.Close() + goto Error + } + return + +Error: + return nil, &DialError{config, err} +} diff --git a/vendor/golang.org/x/net/websocket/dial.go b/vendor/golang.org/x/net/websocket/dial.go new file mode 100644 index 000000000..2dab943a4 --- /dev/null +++ b/vendor/golang.org/x/net/websocket/dial.go @@ -0,0 +1,24 @@ +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package websocket + +import ( + "crypto/tls" + "net" +) + +func dialWithDialer(dialer *net.Dialer, config *Config) (conn net.Conn, err error) { + switch config.Location.Scheme { + case "ws": + conn, err = dialer.Dial("tcp", parseAuthority(config.Location)) + + case "wss": + conn, err = tls.DialWithDialer(dialer, "tcp", parseAuthority(config.Location), config.TlsConfig) + + default: + err = ErrBadScheme + } + return +} diff --git a/vendor/golang.org/x/net/websocket/hybi.go b/vendor/golang.org/x/net/websocket/hybi.go new file mode 100644 index 000000000..8cffdd16c --- /dev/null +++ b/vendor/golang.org/x/net/websocket/hybi.go @@ -0,0 +1,583 @@ +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package websocket + +// This file implements a protocol of hybi draft. +// http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17 + +import ( + "bufio" + "bytes" + "crypto/rand" + "crypto/sha1" + "encoding/base64" + "encoding/binary" + "fmt" + "io" + "io/ioutil" + "net/http" + "net/url" + "strings" +) + +const ( + websocketGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + + closeStatusNormal = 1000 + closeStatusGoingAway = 1001 + closeStatusProtocolError = 1002 + closeStatusUnsupportedData = 1003 + closeStatusFrameTooLarge = 1004 + closeStatusNoStatusRcvd = 1005 + closeStatusAbnormalClosure = 1006 + closeStatusBadMessageData = 1007 + closeStatusPolicyViolation = 1008 + closeStatusTooBigData = 1009 + closeStatusExtensionMismatch = 1010 + + maxControlFramePayloadLength = 125 +) + +var ( + ErrBadMaskingKey = &ProtocolError{"bad masking key"} + ErrBadPongMessage = &ProtocolError{"bad pong message"} + ErrBadClosingStatus = &ProtocolError{"bad closing status"} + ErrUnsupportedExtensions = &ProtocolError{"unsupported extensions"} + ErrNotImplemented = &ProtocolError{"not implemented"} + + handshakeHeader = map[string]bool{ + "Host": true, + "Upgrade": true, + "Connection": true, + "Sec-Websocket-Key": true, + "Sec-Websocket-Origin": true, + "Sec-Websocket-Version": true, + "Sec-Websocket-Protocol": true, + "Sec-Websocket-Accept": true, + } +) + +// A hybiFrameHeader is a frame header as defined in hybi draft. +type hybiFrameHeader struct { + Fin bool + Rsv [3]bool + OpCode byte + Length int64 + MaskingKey []byte + + data *bytes.Buffer +} + +// A hybiFrameReader is a reader for hybi frame. +type hybiFrameReader struct { + reader io.Reader + + header hybiFrameHeader + pos int64 + length int +} + +func (frame *hybiFrameReader) Read(msg []byte) (n int, err error) { + n, err = frame.reader.Read(msg) + if frame.header.MaskingKey != nil { + for i := 0; i < n; i++ { + msg[i] = msg[i] ^ frame.header.MaskingKey[frame.pos%4] + frame.pos++ + } + } + return n, err +} + +func (frame *hybiFrameReader) PayloadType() byte { return frame.header.OpCode } + +func (frame *hybiFrameReader) HeaderReader() io.Reader { + if frame.header.data == nil { + return nil + } + if frame.header.data.Len() == 0 { + return nil + } + return frame.header.data +} + +func (frame *hybiFrameReader) TrailerReader() io.Reader { return nil } + +func (frame *hybiFrameReader) Len() (n int) { return frame.length } + +// A hybiFrameReaderFactory creates new frame reader based on its frame type. +type hybiFrameReaderFactory struct { + *bufio.Reader +} + +// NewFrameReader reads a frame header from the connection, and creates new reader for the frame. +// See Section 5.2 Base Framing protocol for detail. +// http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5.2 +func (buf hybiFrameReaderFactory) NewFrameReader() (frame frameReader, err error) { + hybiFrame := new(hybiFrameReader) + frame = hybiFrame + var header []byte + var b byte + // First byte. FIN/RSV1/RSV2/RSV3/OpCode(4bits) + b, err = buf.ReadByte() + if err != nil { + return + } + header = append(header, b) + hybiFrame.header.Fin = ((header[0] >> 7) & 1) != 0 + for i := 0; i < 3; i++ { + j := uint(6 - i) + hybiFrame.header.Rsv[i] = ((header[0] >> j) & 1) != 0 + } + hybiFrame.header.OpCode = header[0] & 0x0f + + // Second byte. Mask/Payload len(7bits) + b, err = buf.ReadByte() + if err != nil { + return + } + header = append(header, b) + mask := (b & 0x80) != 0 + b &= 0x7f + lengthFields := 0 + switch { + case b <= 125: // Payload length 7bits. + hybiFrame.header.Length = int64(b) + case b == 126: // Payload length 7+16bits + lengthFields = 2 + case b == 127: // Payload length 7+64bits + lengthFields = 8 + } + for i := 0; i < lengthFields; i++ { + b, err = buf.ReadByte() + if err != nil { + return + } + if lengthFields == 8 && i == 0 { // MSB must be zero when 7+64 bits + b &= 0x7f + } + header = append(header, b) + hybiFrame.header.Length = hybiFrame.header.Length*256 + int64(b) + } + if mask { + // Masking key. 4 bytes. + for i := 0; i < 4; i++ { + b, err = buf.ReadByte() + if err != nil { + return + } + header = append(header, b) + hybiFrame.header.MaskingKey = append(hybiFrame.header.MaskingKey, b) + } + } + hybiFrame.reader = io.LimitReader(buf.Reader, hybiFrame.header.Length) + hybiFrame.header.data = bytes.NewBuffer(header) + hybiFrame.length = len(header) + int(hybiFrame.header.Length) + return +} + +// A HybiFrameWriter is a writer for hybi frame. +type hybiFrameWriter struct { + writer *bufio.Writer + + header *hybiFrameHeader +} + +func (frame *hybiFrameWriter) Write(msg []byte) (n int, err error) { + var header []byte + var b byte + if frame.header.Fin { + b |= 0x80 + } + for i := 0; i < 3; i++ { + if frame.header.Rsv[i] { + j := uint(6 - i) + b |= 1 << j + } + } + b |= frame.header.OpCode + header = append(header, b) + if frame.header.MaskingKey != nil { + b = 0x80 + } else { + b = 0 + } + lengthFields := 0 + length := len(msg) + switch { + case length <= 125: + b |= byte(length) + case length < 65536: + b |= 126 + lengthFields = 2 + default: + b |= 127 + lengthFields = 8 + } + header = append(header, b) + for i := 0; i < lengthFields; i++ { + j := uint((lengthFields - i - 1) * 8) + b = byte((length >> j) & 0xff) + header = append(header, b) + } + if frame.header.MaskingKey != nil { + if len(frame.header.MaskingKey) != 4 { + return 0, ErrBadMaskingKey + } + header = append(header, frame.header.MaskingKey...) + frame.writer.Write(header) + data := make([]byte, length) + for i := range data { + data[i] = msg[i] ^ frame.header.MaskingKey[i%4] + } + frame.writer.Write(data) + err = frame.writer.Flush() + return length, err + } + frame.writer.Write(header) + frame.writer.Write(msg) + err = frame.writer.Flush() + return length, err +} + +func (frame *hybiFrameWriter) Close() error { return nil } + +type hybiFrameWriterFactory struct { + *bufio.Writer + needMaskingKey bool +} + +func (buf hybiFrameWriterFactory) NewFrameWriter(payloadType byte) (frame frameWriter, err error) { + frameHeader := &hybiFrameHeader{Fin: true, OpCode: payloadType} + if buf.needMaskingKey { + frameHeader.MaskingKey, err = generateMaskingKey() + if err != nil { + return nil, err + } + } + return &hybiFrameWriter{writer: buf.Writer, header: frameHeader}, nil +} + +type hybiFrameHandler struct { + conn *Conn + payloadType byte +} + +func (handler *hybiFrameHandler) HandleFrame(frame frameReader) (frameReader, error) { + if handler.conn.IsServerConn() { + // The client MUST mask all frames sent to the server. + if frame.(*hybiFrameReader).header.MaskingKey == nil { + handler.WriteClose(closeStatusProtocolError) + return nil, io.EOF + } + } else { + // The server MUST NOT mask all frames. + if frame.(*hybiFrameReader).header.MaskingKey != nil { + handler.WriteClose(closeStatusProtocolError) + return nil, io.EOF + } + } + if header := frame.HeaderReader(); header != nil { + io.Copy(ioutil.Discard, header) + } + switch frame.PayloadType() { + case ContinuationFrame: + frame.(*hybiFrameReader).header.OpCode = handler.payloadType + case TextFrame, BinaryFrame: + handler.payloadType = frame.PayloadType() + case CloseFrame: + return nil, io.EOF + case PingFrame, PongFrame: + b := make([]byte, maxControlFramePayloadLength) + n, err := io.ReadFull(frame, b) + if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF { + return nil, err + } + io.Copy(ioutil.Discard, frame) + if frame.PayloadType() == PingFrame { + if _, err := handler.WritePong(b[:n]); err != nil { + return nil, err + } + } + return nil, nil + } + return frame, nil +} + +func (handler *hybiFrameHandler) WriteClose(status int) (err error) { + handler.conn.wio.Lock() + defer handler.conn.wio.Unlock() + w, err := handler.conn.frameWriterFactory.NewFrameWriter(CloseFrame) + if err != nil { + return err + } + msg := make([]byte, 2) + binary.BigEndian.PutUint16(msg, uint16(status)) + _, err = w.Write(msg) + w.Close() + return err +} + +func (handler *hybiFrameHandler) WritePong(msg []byte) (n int, err error) { + handler.conn.wio.Lock() + defer handler.conn.wio.Unlock() + w, err := handler.conn.frameWriterFactory.NewFrameWriter(PongFrame) + if err != nil { + return 0, err + } + n, err = w.Write(msg) + w.Close() + return n, err +} + +// newHybiConn creates a new WebSocket connection speaking hybi draft protocol. +func newHybiConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn { + if buf == nil { + br := bufio.NewReader(rwc) + bw := bufio.NewWriter(rwc) + buf = bufio.NewReadWriter(br, bw) + } + ws := &Conn{config: config, request: request, buf: buf, rwc: rwc, + frameReaderFactory: hybiFrameReaderFactory{buf.Reader}, + frameWriterFactory: hybiFrameWriterFactory{ + buf.Writer, request == nil}, + PayloadType: TextFrame, + defaultCloseStatus: closeStatusNormal} + ws.frameHandler = &hybiFrameHandler{conn: ws} + return ws +} + +// generateMaskingKey generates a masking key for a frame. +func generateMaskingKey() (maskingKey []byte, err error) { + maskingKey = make([]byte, 4) + if _, err = io.ReadFull(rand.Reader, maskingKey); err != nil { + return + } + return +} + +// generateNonce generates a nonce consisting of a randomly selected 16-byte +// value that has been base64-encoded. +func generateNonce() (nonce []byte) { + key := make([]byte, 16) + if _, err := io.ReadFull(rand.Reader, key); err != nil { + panic(err) + } + nonce = make([]byte, 24) + base64.StdEncoding.Encode(nonce, key) + return +} + +// removeZone removes IPv6 zone identifer from host. +// E.g., "[fe80::1%en0]:8080" to "[fe80::1]:8080" +func removeZone(host string) string { + if !strings.HasPrefix(host, "[") { + return host + } + i := strings.LastIndex(host, "]") + if i < 0 { + return host + } + j := strings.LastIndex(host[:i], "%") + if j < 0 { + return host + } + return host[:j] + host[i:] +} + +// getNonceAccept computes the base64-encoded SHA-1 of the concatenation of +// the nonce ("Sec-WebSocket-Key" value) with the websocket GUID string. +func getNonceAccept(nonce []byte) (expected []byte, err error) { + h := sha1.New() + if _, err = h.Write(nonce); err != nil { + return + } + if _, err = h.Write([]byte(websocketGUID)); err != nil { + return + } + expected = make([]byte, 28) + base64.StdEncoding.Encode(expected, h.Sum(nil)) + return +} + +// Client handshake described in draft-ietf-hybi-thewebsocket-protocol-17 +func hybiClientHandshake(config *Config, br *bufio.Reader, bw *bufio.Writer) (err error) { + bw.WriteString("GET " + config.Location.RequestURI() + " HTTP/1.1\r\n") + + // According to RFC 6874, an HTTP client, proxy, or other + // intermediary must remove any IPv6 zone identifier attached + // to an outgoing URI. + bw.WriteString("Host: " + removeZone(config.Location.Host) + "\r\n") + bw.WriteString("Upgrade: websocket\r\n") + bw.WriteString("Connection: Upgrade\r\n") + nonce := generateNonce() + if config.handshakeData != nil { + nonce = []byte(config.handshakeData["key"]) + } + bw.WriteString("Sec-WebSocket-Key: " + string(nonce) + "\r\n") + bw.WriteString("Origin: " + strings.ToLower(config.Origin.String()) + "\r\n") + + if config.Version != ProtocolVersionHybi13 { + return ErrBadProtocolVersion + } + + bw.WriteString("Sec-WebSocket-Version: " + fmt.Sprintf("%d", config.Version) + "\r\n") + if len(config.Protocol) > 0 { + bw.WriteString("Sec-WebSocket-Protocol: " + strings.Join(config.Protocol, ", ") + "\r\n") + } + // TODO(ukai): send Sec-WebSocket-Extensions. + err = config.Header.WriteSubset(bw, handshakeHeader) + if err != nil { + return err + } + + bw.WriteString("\r\n") + if err = bw.Flush(); err != nil { + return err + } + + resp, err := http.ReadResponse(br, &http.Request{Method: "GET"}) + if err != nil { + return err + } + if resp.StatusCode != 101 { + return ErrBadStatus + } + if strings.ToLower(resp.Header.Get("Upgrade")) != "websocket" || + strings.ToLower(resp.Header.Get("Connection")) != "upgrade" { + return ErrBadUpgrade + } + expectedAccept, err := getNonceAccept(nonce) + if err != nil { + return err + } + if resp.Header.Get("Sec-WebSocket-Accept") != string(expectedAccept) { + return ErrChallengeResponse + } + if resp.Header.Get("Sec-WebSocket-Extensions") != "" { + return ErrUnsupportedExtensions + } + offeredProtocol := resp.Header.Get("Sec-WebSocket-Protocol") + if offeredProtocol != "" { + protocolMatched := false + for i := 0; i < len(config.Protocol); i++ { + if config.Protocol[i] == offeredProtocol { + protocolMatched = true + break + } + } + if !protocolMatched { + return ErrBadWebSocketProtocol + } + config.Protocol = []string{offeredProtocol} + } + + return nil +} + +// newHybiClientConn creates a client WebSocket connection after handshake. +func newHybiClientConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser) *Conn { + return newHybiConn(config, buf, rwc, nil) +} + +// A HybiServerHandshaker performs a server handshake using hybi draft protocol. +type hybiServerHandshaker struct { + *Config + accept []byte +} + +func (c *hybiServerHandshaker) ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) { + c.Version = ProtocolVersionHybi13 + if req.Method != "GET" { + return http.StatusMethodNotAllowed, ErrBadRequestMethod + } + // HTTP version can be safely ignored. + + if strings.ToLower(req.Header.Get("Upgrade")) != "websocket" || + !strings.Contains(strings.ToLower(req.Header.Get("Connection")), "upgrade") { + return http.StatusBadRequest, ErrNotWebSocket + } + + key := req.Header.Get("Sec-Websocket-Key") + if key == "" { + return http.StatusBadRequest, ErrChallengeResponse + } + version := req.Header.Get("Sec-Websocket-Version") + switch version { + case "13": + c.Version = ProtocolVersionHybi13 + default: + return http.StatusBadRequest, ErrBadWebSocketVersion + } + var scheme string + if req.TLS != nil { + scheme = "wss" + } else { + scheme = "ws" + } + c.Location, err = url.ParseRequestURI(scheme + "://" + req.Host + req.URL.RequestURI()) + if err != nil { + return http.StatusBadRequest, err + } + protocol := strings.TrimSpace(req.Header.Get("Sec-Websocket-Protocol")) + if protocol != "" { + protocols := strings.Split(protocol, ",") + for i := 0; i < len(protocols); i++ { + c.Protocol = append(c.Protocol, strings.TrimSpace(protocols[i])) + } + } + c.accept, err = getNonceAccept([]byte(key)) + if err != nil { + return http.StatusInternalServerError, err + } + return http.StatusSwitchingProtocols, nil +} + +// Origin parses the Origin header in req. +// If the Origin header is not set, it returns nil and nil. +func Origin(config *Config, req *http.Request) (*url.URL, error) { + var origin string + switch config.Version { + case ProtocolVersionHybi13: + origin = req.Header.Get("Origin") + } + if origin == "" { + return nil, nil + } + return url.ParseRequestURI(origin) +} + +func (c *hybiServerHandshaker) AcceptHandshake(buf *bufio.Writer) (err error) { + if len(c.Protocol) > 0 { + if len(c.Protocol) != 1 { + // You need choose a Protocol in Handshake func in Server. + return ErrBadWebSocketProtocol + } + } + buf.WriteString("HTTP/1.1 101 Switching Protocols\r\n") + buf.WriteString("Upgrade: websocket\r\n") + buf.WriteString("Connection: Upgrade\r\n") + buf.WriteString("Sec-WebSocket-Accept: " + string(c.accept) + "\r\n") + if len(c.Protocol) > 0 { + buf.WriteString("Sec-WebSocket-Protocol: " + c.Protocol[0] + "\r\n") + } + // TODO(ukai): send Sec-WebSocket-Extensions. + if c.Header != nil { + err := c.Header.WriteSubset(buf, handshakeHeader) + if err != nil { + return err + } + } + buf.WriteString("\r\n") + return buf.Flush() +} + +func (c *hybiServerHandshaker) NewServerConn(buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn { + return newHybiServerConn(c.Config, buf, rwc, request) +} + +// newHybiServerConn returns a new WebSocket connection speaking hybi draft protocol. +func newHybiServerConn(config *Config, buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) *Conn { + return newHybiConn(config, buf, rwc, request) +} diff --git a/vendor/golang.org/x/net/websocket/server.go b/vendor/golang.org/x/net/websocket/server.go new file mode 100644 index 000000000..0895dea19 --- /dev/null +++ b/vendor/golang.org/x/net/websocket/server.go @@ -0,0 +1,113 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package websocket + +import ( + "bufio" + "fmt" + "io" + "net/http" +) + +func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Request, config *Config, handshake func(*Config, *http.Request) error) (conn *Conn, err error) { + var hs serverHandshaker = &hybiServerHandshaker{Config: config} + code, err := hs.ReadHandshake(buf.Reader, req) + if err == ErrBadWebSocketVersion { + fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) + fmt.Fprintf(buf, "Sec-WebSocket-Version: %s\r\n", SupportedProtocolVersion) + buf.WriteString("\r\n") + buf.WriteString(err.Error()) + buf.Flush() + return + } + if err != nil { + fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) + buf.WriteString("\r\n") + buf.WriteString(err.Error()) + buf.Flush() + return + } + if handshake != nil { + err = handshake(config, req) + if err != nil { + code = http.StatusForbidden + fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) + buf.WriteString("\r\n") + buf.Flush() + return + } + } + err = hs.AcceptHandshake(buf.Writer) + if err != nil { + code = http.StatusBadRequest + fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code)) + buf.WriteString("\r\n") + buf.Flush() + return + } + conn = hs.NewServerConn(buf, rwc, req) + return +} + +// Server represents a server of a WebSocket. +type Server struct { + // Config is a WebSocket configuration for new WebSocket connection. + Config + + // Handshake is an optional function in WebSocket handshake. + // For example, you can check, or don't check Origin header. + // Another example, you can select config.Protocol. + Handshake func(*Config, *http.Request) error + + // Handler handles a WebSocket connection. + Handler +} + +// ServeHTTP implements the http.Handler interface for a WebSocket +func (s Server) ServeHTTP(w http.ResponseWriter, req *http.Request) { + s.serveWebSocket(w, req) +} + +func (s Server) serveWebSocket(w http.ResponseWriter, req *http.Request) { + rwc, buf, err := w.(http.Hijacker).Hijack() + if err != nil { + panic("Hijack failed: " + err.Error()) + } + // The server should abort the WebSocket connection if it finds + // the client did not send a handshake that matches with protocol + // specification. + defer rwc.Close() + conn, err := newServerConn(rwc, buf, req, &s.Config, s.Handshake) + if err != nil { + return + } + if conn == nil { + panic("unexpected nil conn") + } + s.Handler(conn) +} + +// Handler is a simple interface to a WebSocket browser client. +// It checks if Origin header is valid URL by default. +// You might want to verify websocket.Conn.Config().Origin in the func. +// If you use Server instead of Handler, you could call websocket.Origin and +// check the origin in your Handshake func. So, if you want to accept +// non-browser clients, which do not send an Origin header, set a +// Server.Handshake that does not check the origin. +type Handler func(*Conn) + +func checkOrigin(config *Config, req *http.Request) (err error) { + config.Origin, err = Origin(config, req) + if err == nil && config.Origin == nil { + return fmt.Errorf("null origin") + } + return err +} + +// ServeHTTP implements the http.Handler interface for a WebSocket +func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) { + s := Server{Handler: h, Handshake: checkOrigin} + s.serveWebSocket(w, req) +} diff --git a/vendor/golang.org/x/net/websocket/websocket.go b/vendor/golang.org/x/net/websocket/websocket.go new file mode 100644 index 000000000..6c45c7352 --- /dev/null +++ b/vendor/golang.org/x/net/websocket/websocket.go @@ -0,0 +1,451 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package websocket implements a client and server for the WebSocket protocol +// as specified in RFC 6455. +// +// This package currently lacks some features found in alternative +// and more actively maintained WebSocket packages: +// +// https://godoc.org/github.com/gorilla/websocket +// https://godoc.org/nhooyr.io/websocket +package websocket // import "golang.org/x/net/websocket" + +import ( + "bufio" + "crypto/tls" + "encoding/json" + "errors" + "io" + "io/ioutil" + "net" + "net/http" + "net/url" + "sync" + "time" +) + +const ( + ProtocolVersionHybi13 = 13 + ProtocolVersionHybi = ProtocolVersionHybi13 + SupportedProtocolVersion = "13" + + ContinuationFrame = 0 + TextFrame = 1 + BinaryFrame = 2 + CloseFrame = 8 + PingFrame = 9 + PongFrame = 10 + UnknownFrame = 255 + + DefaultMaxPayloadBytes = 32 << 20 // 32MB +) + +// ProtocolError represents WebSocket protocol errors. +type ProtocolError struct { + ErrorString string +} + +func (err *ProtocolError) Error() string { return err.ErrorString } + +var ( + ErrBadProtocolVersion = &ProtocolError{"bad protocol version"} + ErrBadScheme = &ProtocolError{"bad scheme"} + ErrBadStatus = &ProtocolError{"bad status"} + ErrBadUpgrade = &ProtocolError{"missing or bad upgrade"} + ErrBadWebSocketOrigin = &ProtocolError{"missing or bad WebSocket-Origin"} + ErrBadWebSocketLocation = &ProtocolError{"missing or bad WebSocket-Location"} + ErrBadWebSocketProtocol = &ProtocolError{"missing or bad WebSocket-Protocol"} + ErrBadWebSocketVersion = &ProtocolError{"missing or bad WebSocket Version"} + ErrChallengeResponse = &ProtocolError{"mismatch challenge/response"} + ErrBadFrame = &ProtocolError{"bad frame"} + ErrBadFrameBoundary = &ProtocolError{"not on frame boundary"} + ErrNotWebSocket = &ProtocolError{"not websocket protocol"} + ErrBadRequestMethod = &ProtocolError{"bad method"} + ErrNotSupported = &ProtocolError{"not supported"} +) + +// ErrFrameTooLarge is returned by Codec's Receive method if payload size +// exceeds limit set by Conn.MaxPayloadBytes +var ErrFrameTooLarge = errors.New("websocket: frame payload size exceeds limit") + +// Addr is an implementation of net.Addr for WebSocket. +type Addr struct { + *url.URL +} + +// Network returns the network type for a WebSocket, "websocket". +func (addr *Addr) Network() string { return "websocket" } + +// Config is a WebSocket configuration +type Config struct { + // A WebSocket server address. + Location *url.URL + + // A Websocket client origin. + Origin *url.URL + + // WebSocket subprotocols. + Protocol []string + + // WebSocket protocol version. + Version int + + // TLS config for secure WebSocket (wss). + TlsConfig *tls.Config + + // Additional header fields to be sent in WebSocket opening handshake. + Header http.Header + + // Dialer used when opening websocket connections. + Dialer *net.Dialer + + handshakeData map[string]string +} + +// serverHandshaker is an interface to handle WebSocket server side handshake. +type serverHandshaker interface { + // ReadHandshake reads handshake request message from client. + // Returns http response code and error if any. + ReadHandshake(buf *bufio.Reader, req *http.Request) (code int, err error) + + // AcceptHandshake accepts the client handshake request and sends + // handshake response back to client. + AcceptHandshake(buf *bufio.Writer) (err error) + + // NewServerConn creates a new WebSocket connection. + NewServerConn(buf *bufio.ReadWriter, rwc io.ReadWriteCloser, request *http.Request) (conn *Conn) +} + +// frameReader is an interface to read a WebSocket frame. +type frameReader interface { + // Reader is to read payload of the frame. + io.Reader + + // PayloadType returns payload type. + PayloadType() byte + + // HeaderReader returns a reader to read header of the frame. + HeaderReader() io.Reader + + // TrailerReader returns a reader to read trailer of the frame. + // If it returns nil, there is no trailer in the frame. + TrailerReader() io.Reader + + // Len returns total length of the frame, including header and trailer. + Len() int +} + +// frameReaderFactory is an interface to creates new frame reader. +type frameReaderFactory interface { + NewFrameReader() (r frameReader, err error) +} + +// frameWriter is an interface to write a WebSocket frame. +type frameWriter interface { + // Writer is to write payload of the frame. + io.WriteCloser +} + +// frameWriterFactory is an interface to create new frame writer. +type frameWriterFactory interface { + NewFrameWriter(payloadType byte) (w frameWriter, err error) +} + +type frameHandler interface { + HandleFrame(frame frameReader) (r frameReader, err error) + WriteClose(status int) (err error) +} + +// Conn represents a WebSocket connection. +// +// Multiple goroutines may invoke methods on a Conn simultaneously. +type Conn struct { + config *Config + request *http.Request + + buf *bufio.ReadWriter + rwc io.ReadWriteCloser + + rio sync.Mutex + frameReaderFactory + frameReader + + wio sync.Mutex + frameWriterFactory + + frameHandler + PayloadType byte + defaultCloseStatus int + + // MaxPayloadBytes limits the size of frame payload received over Conn + // by Codec's Receive method. If zero, DefaultMaxPayloadBytes is used. + MaxPayloadBytes int +} + +// Read implements the io.Reader interface: +// it reads data of a frame from the WebSocket connection. +// if msg is not large enough for the frame data, it fills the msg and next Read +// will read the rest of the frame data. +// it reads Text frame or Binary frame. +func (ws *Conn) Read(msg []byte) (n int, err error) { + ws.rio.Lock() + defer ws.rio.Unlock() +again: + if ws.frameReader == nil { + frame, err := ws.frameReaderFactory.NewFrameReader() + if err != nil { + return 0, err + } + ws.frameReader, err = ws.frameHandler.HandleFrame(frame) + if err != nil { + return 0, err + } + if ws.frameReader == nil { + goto again + } + } + n, err = ws.frameReader.Read(msg) + if err == io.EOF { + if trailer := ws.frameReader.TrailerReader(); trailer != nil { + io.Copy(ioutil.Discard, trailer) + } + ws.frameReader = nil + goto again + } + return n, err +} + +// Write implements the io.Writer interface: +// it writes data as a frame to the WebSocket connection. +func (ws *Conn) Write(msg []byte) (n int, err error) { + ws.wio.Lock() + defer ws.wio.Unlock() + w, err := ws.frameWriterFactory.NewFrameWriter(ws.PayloadType) + if err != nil { + return 0, err + } + n, err = w.Write(msg) + w.Close() + return n, err +} + +// Close implements the io.Closer interface. +func (ws *Conn) Close() error { + err := ws.frameHandler.WriteClose(ws.defaultCloseStatus) + err1 := ws.rwc.Close() + if err != nil { + return err + } + return err1 +} + +// IsClientConn reports whether ws is a client-side connection. +func (ws *Conn) IsClientConn() bool { return ws.request == nil } + +// IsServerConn reports whether ws is a server-side connection. +func (ws *Conn) IsServerConn() bool { return ws.request != nil } + +// LocalAddr returns the WebSocket Origin for the connection for client, or +// the WebSocket location for server. +func (ws *Conn) LocalAddr() net.Addr { + if ws.IsClientConn() { + return &Addr{ws.config.Origin} + } + return &Addr{ws.config.Location} +} + +// RemoteAddr returns the WebSocket location for the connection for client, or +// the Websocket Origin for server. +func (ws *Conn) RemoteAddr() net.Addr { + if ws.IsClientConn() { + return &Addr{ws.config.Location} + } + return &Addr{ws.config.Origin} +} + +var errSetDeadline = errors.New("websocket: cannot set deadline: not using a net.Conn") + +// SetDeadline sets the connection's network read & write deadlines. +func (ws *Conn) SetDeadline(t time.Time) error { + if conn, ok := ws.rwc.(net.Conn); ok { + return conn.SetDeadline(t) + } + return errSetDeadline +} + +// SetReadDeadline sets the connection's network read deadline. +func (ws *Conn) SetReadDeadline(t time.Time) error { + if conn, ok := ws.rwc.(net.Conn); ok { + return conn.SetReadDeadline(t) + } + return errSetDeadline +} + +// SetWriteDeadline sets the connection's network write deadline. +func (ws *Conn) SetWriteDeadline(t time.Time) error { + if conn, ok := ws.rwc.(net.Conn); ok { + return conn.SetWriteDeadline(t) + } + return errSetDeadline +} + +// Config returns the WebSocket config. +func (ws *Conn) Config() *Config { return ws.config } + +// Request returns the http request upgraded to the WebSocket. +// It is nil for client side. +func (ws *Conn) Request() *http.Request { return ws.request } + +// Codec represents a symmetric pair of functions that implement a codec. +type Codec struct { + Marshal func(v interface{}) (data []byte, payloadType byte, err error) + Unmarshal func(data []byte, payloadType byte, v interface{}) (err error) +} + +// Send sends v marshaled by cd.Marshal as single frame to ws. +func (cd Codec) Send(ws *Conn, v interface{}) (err error) { + data, payloadType, err := cd.Marshal(v) + if err != nil { + return err + } + ws.wio.Lock() + defer ws.wio.Unlock() + w, err := ws.frameWriterFactory.NewFrameWriter(payloadType) + if err != nil { + return err + } + _, err = w.Write(data) + w.Close() + return err +} + +// Receive receives single frame from ws, unmarshaled by cd.Unmarshal and stores +// in v. The whole frame payload is read to an in-memory buffer; max size of +// payload is defined by ws.MaxPayloadBytes. If frame payload size exceeds +// limit, ErrFrameTooLarge is returned; in this case frame is not read off wire +// completely. The next call to Receive would read and discard leftover data of +// previous oversized frame before processing next frame. +func (cd Codec) Receive(ws *Conn, v interface{}) (err error) { + ws.rio.Lock() + defer ws.rio.Unlock() + if ws.frameReader != nil { + _, err = io.Copy(ioutil.Discard, ws.frameReader) + if err != nil { + return err + } + ws.frameReader = nil + } +again: + frame, err := ws.frameReaderFactory.NewFrameReader() + if err != nil { + return err + } + frame, err = ws.frameHandler.HandleFrame(frame) + if err != nil { + return err + } + if frame == nil { + goto again + } + maxPayloadBytes := ws.MaxPayloadBytes + if maxPayloadBytes == 0 { + maxPayloadBytes = DefaultMaxPayloadBytes + } + if hf, ok := frame.(*hybiFrameReader); ok && hf.header.Length > int64(maxPayloadBytes) { + // payload size exceeds limit, no need to call Unmarshal + // + // set frameReader to current oversized frame so that + // the next call to this function can drain leftover + // data before processing the next frame + ws.frameReader = frame + return ErrFrameTooLarge + } + payloadType := frame.PayloadType() + data, err := ioutil.ReadAll(frame) + if err != nil { + return err + } + return cd.Unmarshal(data, payloadType, v) +} + +func marshal(v interface{}) (msg []byte, payloadType byte, err error) { + switch data := v.(type) { + case string: + return []byte(data), TextFrame, nil + case []byte: + return data, BinaryFrame, nil + } + return nil, UnknownFrame, ErrNotSupported +} + +func unmarshal(msg []byte, payloadType byte, v interface{}) (err error) { + switch data := v.(type) { + case *string: + *data = string(msg) + return nil + case *[]byte: + *data = msg + return nil + } + return ErrNotSupported +} + +/* +Message is a codec to send/receive text/binary data in a frame on WebSocket connection. +To send/receive text frame, use string type. +To send/receive binary frame, use []byte type. + +Trivial usage: + + import "websocket" + + // receive text frame + var message string + websocket.Message.Receive(ws, &message) + + // send text frame + message = "hello" + websocket.Message.Send(ws, message) + + // receive binary frame + var data []byte + websocket.Message.Receive(ws, &data) + + // send binary frame + data = []byte{0, 1, 2} + websocket.Message.Send(ws, data) + +*/ +var Message = Codec{marshal, unmarshal} + +func jsonMarshal(v interface{}) (msg []byte, payloadType byte, err error) { + msg, err = json.Marshal(v) + return msg, TextFrame, err +} + +func jsonUnmarshal(msg []byte, payloadType byte, v interface{}) (err error) { + return json.Unmarshal(msg, v) +} + +/* +JSON is a codec to send/receive JSON data in a frame from a WebSocket connection. + +Trivial usage: + + import "websocket" + + type T struct { + Msg string + Count int + } + + // receive JSON type T + var data T + websocket.JSON.Receive(ws, &data) + + // send JSON type T + websocket.JSON.Send(ws, data) +*/ +var JSON = Codec{jsonMarshal, jsonUnmarshal} diff --git a/vendor/modules.txt b/vendor/modules.txt index 7c7461859..ffb04b950 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -104,7 +104,7 @@ github.com/approvals/go-approval-tests/utils github.com/armon/go-metrics # github.com/armon/go-radix v1.0.0 github.com/armon/go-radix -# github.com/aws/aws-sdk-go v1.30.8 +# github.com/aws/aws-sdk-go v1.34.26 github.com/aws/aws-sdk-go/aws github.com/aws/aws-sdk-go/aws/arn github.com/aws/aws-sdk-go/aws/awserr @@ -134,6 +134,7 @@ github.com/aws/aws-sdk-go/internal/sdkuri github.com/aws/aws-sdk-go/internal/shareddefaults github.com/aws/aws-sdk-go/internal/strings github.com/aws/aws-sdk-go/internal/sync/singleflight +github.com/aws/aws-sdk-go/private/checksum github.com/aws/aws-sdk-go/private/protocol github.com/aws/aws-sdk-go/private/protocol/ec2query github.com/aws/aws-sdk-go/private/protocol/eventstream @@ -173,8 +174,6 @@ github.com/c2h5oh/datasize github.com/cheggaaa/pb # github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e github.com/chzyer/readline -# github.com/creack/goselect v0.1.0 -github.com/creack/goselect # github.com/davecgh/go-spew v1.1.1 github.com/davecgh/go-spew/spew # github.com/dgrijalva/jwt-go v3.2.0+incompatible @@ -189,10 +188,6 @@ github.com/digitalocean/go-qemu/qmp github.com/digitalocean/godo # github.com/dimchansky/utfbom v1.1.0 github.com/dimchansky/utfbom -# github.com/docker/docker v0.0.0-20180422163414-57142e89befe -github.com/docker/docker/pkg/namesgenerator -# github.com/dustin/go-humanize v1.0.0 -github.com/dustin/go-humanize # github.com/dylanmei/iso8601 v0.1.0 github.com/dylanmei/iso8601 # github.com/dylanmei/winrmtest v0.0.0-20170819153634-c2fbb09e6c08 @@ -279,6 +274,7 @@ github.com/gophercloud/gophercloud/openstack/identity/v2/tokens github.com/gophercloud/gophercloud/openstack/identity/v3/extensions/ec2tokens github.com/gophercloud/gophercloud/openstack/identity/v3/extensions/oauth1 github.com/gophercloud/gophercloud/openstack/identity/v3/tokens +github.com/gophercloud/gophercloud/openstack/imageservice/v2/imageimport github.com/gophercloud/gophercloud/openstack/imageservice/v2/images github.com/gophercloud/gophercloud/openstack/imageservice/v2/members github.com/gophercloud/gophercloud/openstack/networking/v2/extensions/external @@ -291,12 +287,13 @@ github.com/gophercloud/gophercloud/pagination github.com/gophercloud/utils/env github.com/gophercloud/utils/openstack/clientconfig github.com/gophercloud/utils/openstack/compute/v2/flavors -# github.com/gorilla/websocket v0.0.0-20170319172727-a91eba7f9777 -github.com/gorilla/websocket # github.com/grpc-ecosystem/go-grpc-middleware v1.1.0 github.com/grpc-ecosystem/go-grpc-middleware # github.com/hako/durafmt v0.0.0-20200710122514-c0fb7b4da026 github.com/hako/durafmt +# github.com/hashicorp/aws-sdk-go-base v0.6.0 +github.com/hashicorp/aws-sdk-go-base +github.com/hashicorp/aws-sdk-go-base/tfawserr # github.com/hashicorp/consul/api v1.4.0 github.com/hashicorp/consul/api # github.com/hashicorp/errwrap v1.0.0 @@ -305,8 +302,9 @@ github.com/hashicorp/errwrap github.com/hashicorp/go-checkpoint # github.com/hashicorp/go-cleanhttp v0.5.1 github.com/hashicorp/go-cleanhttp -# github.com/hashicorp/go-cty-funcs v0.0.0-20200520133146-0d04eb807361 +# github.com/hashicorp/go-cty-funcs v0.0.0-20200930094925-2721b1e36840 github.com/hashicorp/go-cty-funcs/cidr +github.com/hashicorp/go-cty-funcs/collection github.com/hashicorp/go-cty-funcs/crypto github.com/hashicorp/go-cty-funcs/encoding github.com/hashicorp/go-cty-funcs/filesystem @@ -468,10 +466,6 @@ github.com/mitchellh/reflectwalk github.com/modern-go/concurrent # github.com/modern-go/reflect2 v1.0.1 github.com/modern-go/reflect2 -# github.com/moul/anonuuid v0.0.0-20160222162117-609b752a95ef -github.com/moul/anonuuid -# github.com/moul/gotty-client v0.0.0-20180327180212-b26a57ebc215 -github.com/moul/gotty-client # github.com/nu7hatch/gouuid v0.0.0-20131221200532-179d4d0c4d8d github.com/nu7hatch/gouuid # github.com/olekukonko/tablewriter v0.0.0-20180105111133-96aac992fc8b @@ -500,16 +494,22 @@ github.com/posener/complete/cmd github.com/posener/complete/cmd/install # github.com/profitbricks/profitbricks-sdk-go v4.0.2+incompatible github.com/profitbricks/profitbricks-sdk-go -# github.com/renstrom/fuzzysearch v0.0.0-20160331204855-2d205ac6ec17 -github.com/renstrom/fuzzysearch/fuzzy # github.com/ryanuber/go-glob v1.0.0 github.com/ryanuber/go-glob # github.com/satori/go.uuid v1.2.0 github.com/satori/go.uuid -# github.com/scaleway/scaleway-cli v0.0.0-20180921094345-7b12c9699d70 -github.com/scaleway/scaleway-cli/pkg/api -github.com/scaleway/scaleway-cli/pkg/sshcommand -github.com/scaleway/scaleway-cli/pkg/utils +# github.com/scaleway/scaleway-sdk-go v1.0.0-beta.6.0.20200903143645-c0ce17a0443d +github.com/scaleway/scaleway-sdk-go/api/instance/v1 +github.com/scaleway/scaleway-sdk-go/api/marketplace/v1 +github.com/scaleway/scaleway-sdk-go/internal/async +github.com/scaleway/scaleway-sdk-go/internal/auth +github.com/scaleway/scaleway-sdk-go/internal/errors +github.com/scaleway/scaleway-sdk-go/internal/marshaler +github.com/scaleway/scaleway-sdk-go/internal/parameter +github.com/scaleway/scaleway-sdk-go/logger +github.com/scaleway/scaleway-sdk-go/namegenerator +github.com/scaleway/scaleway-sdk-go/scw +github.com/scaleway/scaleway-sdk-go/validation # github.com/shirou/gopsutil v2.18.12+incompatible github.com/shirou/gopsutil/cpu github.com/shirou/gopsutil/host @@ -728,6 +728,7 @@ golang.org/x/net/internal/timeseries golang.org/x/net/proxy golang.org/x/net/publicsuffix golang.org/x/net/trace +golang.org/x/net/websocket # golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d golang.org/x/oauth2 golang.org/x/oauth2/google diff --git a/version/version.go b/version/version.go index 4f62d4e32..3052e1e50 100644 --- a/version/version.go +++ b/version/version.go @@ -9,7 +9,7 @@ import ( var GitCommit string // The main version number that is being run at the moment. -const Version = "1.6.3" +const Version = "1.6.5" // 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 diff --git a/website/data/version.js b/website/data/version.js index b6bb9b08e..357c07a43 100644 --- a/website/data/version.js +++ b/website/data/version.js @@ -1 +1 @@ -export default '1.6.2' +export default '1.6.4' diff --git a/website/package-lock.json b/website/package-lock.json index 1e76d3e79..9fb53e60e 100644 --- a/website/package-lock.json +++ b/website/package-lock.json @@ -1710,14 +1710,20 @@ } }, "@hashicorp/react-search": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@hashicorp/react-search/-/react-search-2.0.0.tgz", - "integrity": "sha512-nMH0pUPNEOEcuIcQ/NRiqlZOXJkK7XnIs+KcwFoRxX6UyWSUUkhHPUU+TGy4Wgs8T65tFl5y4Ksnv+za+3CdPQ==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@hashicorp/react-search/-/react-search-2.1.0.tgz", + "integrity": "sha512-vaTht+2G9ipsVyusK3b3TtUpuy9ccsxj3NMSWXJyGsoT39K1Oovb8aLiIlbUU5Ll72KEi5yq5OS3WAJDdSqW+g==", "requires": { "@hashicorp/react-inline-svg": "^1.0.2", "@hashicorp/remark-plugins": "^3.0.0", + "algoliasearch": "^4.4.0", + "dotenv": "^8.2.0", + "glob": "^7.1.6", + "gray-matter": "^4.0.2", "react-instantsearch-dom": "^6.7.0", - "search-insights": "^1.6.0" + "remark": "^12.0.1", + "search-insights": "^1.6.0", + "unist-util-visit": "^2.0.3" }, "dependencies": { "@hashicorp/react-inline-svg": { diff --git a/website/package.json b/website/package.json index c96e35bb5..010ee2cdb 100644 --- a/website/package.json +++ b/website/package.json @@ -13,20 +13,14 @@ "@hashicorp/react-head": "1.1.1", "@hashicorp/react-mega-nav": "4.0.1-2", "@hashicorp/react-product-downloader": "4.0.2", - "@hashicorp/react-search": "^2.0.0", + "@hashicorp/react-search": "^2.1.0", "@hashicorp/react-section-header": "2.0.0", "@hashicorp/react-subnav": "3.2.3", "@hashicorp/react-vertical-text-block-list": "2.0.1", - "algoliasearch": "^4.4.0", "babel-plugin-import-glob-array": "0.2.0", - "dotenv": "8.2.0", - "glob": "^7.1.6", - "gray-matter": "4.0.2", "next": "9.4.4", "react": "16.13.1", - "react-dom": "16.13.1", - "remark": "^12.0.1", - "unist-util-visit": "^2.0.3" + "react-dom": "16.13.1" }, "devDependencies": { "dart-linkcheck": "2.0.15", diff --git a/website/pages/docs/builders/alicloud-ecs.mdx b/website/pages/docs/builders/alicloud-ecs.mdx index e05510cce..5a6306517 100644 --- a/website/pages/docs/builders/alicloud-ecs.mdx +++ b/website/pages/docs/builders/alicloud-ecs.mdx @@ -41,9 +41,13 @@ builder. @include 'builder/alicloud/ecs/AlicloudImageConfig-not-required.mdx' -- `temporary_key_pair_name` (string) - The name of the temporary key pair to - generate. By default, Packer generates a name that looks like - `packer_`, where <UUID> is a 36 character unique identifier. +@include 'helper/communicator/SSH-Temporary-Key-Pair-not-required.mdx' + +@include 'helper/communicator/SSH-Key-Pair-Name-not-required.mdx' + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' + +@include 'helper/communicator/SSH-Agent-Auth-not-required.mdx' ## Basic Example diff --git a/website/pages/docs/builders/amazon/chroot.mdx b/website/pages/docs/builders/amazon/chroot.mdx index 0e93abd61..fcef9e70b 100644 --- a/website/pages/docs/builders/amazon/chroot.mdx +++ b/website/pages/docs/builders/amazon/chroot.mdx @@ -106,6 +106,12 @@ Block devices can be nested in the @include 'builder/amazon/common/AccessConfig-not-required.mdx' +### Assume Role Configuration + +@include 'builder/amazon/common/AssumeRoleConfig.mdx' + +@include 'builder/amazon/common/AssumeRoleConfig-not-required.mdx' + ### Polling Configuration @include 'builder/amazon/common/AWSPollingConfig.mdx' diff --git a/website/pages/docs/builders/amazon/ebs.mdx b/website/pages/docs/builders/amazon/ebs.mdx index 376068081..dfa879976 100644 --- a/website/pages/docs/builders/amazon/ebs.mdx +++ b/website/pages/docs/builders/amazon/ebs.mdx @@ -69,6 +69,12 @@ necessary for this build to succeed and can be found further down the page. @include 'builder/amazon/common/AccessConfig-not-required.mdx' +### Assume Role Configuration + +@include 'builder/amazon/common/AssumeRoleConfig.mdx' + +@include 'builder/amazon/common/AssumeRoleConfig-not-required.mdx' + ### Polling Configuration @include 'builder/amazon/common/AWSPollingConfig.mdx' diff --git a/website/pages/docs/builders/amazon/ebssurrogate.mdx b/website/pages/docs/builders/amazon/ebssurrogate.mdx index b6b7fe7d7..f9ca263e7 100644 --- a/website/pages/docs/builders/amazon/ebssurrogate.mdx +++ b/website/pages/docs/builders/amazon/ebssurrogate.mdx @@ -65,6 +65,12 @@ necessary for this build to succeed and can be found further down the page. @include 'builder/amazon/common/AccessConfig-not-required.mdx' +### Assume Role Configuration + +@include 'builder/amazon/common/AssumeRoleConfig.mdx' + +@include 'builder/amazon/common/AssumeRoleConfig-not-required.mdx' + ### Polling Configuration @include 'builder/amazon/common/AWSPollingConfig.mdx' diff --git a/website/pages/docs/builders/amazon/ebsvolume.mdx b/website/pages/docs/builders/amazon/ebsvolume.mdx index c7faadf14..e104e670a 100644 --- a/website/pages/docs/builders/amazon/ebsvolume.mdx +++ b/website/pages/docs/builders/amazon/ebsvolume.mdx @@ -57,6 +57,12 @@ necessary for this build to succeed and can be found further down the page. @include 'builder/amazon/common/AccessConfig-not-required.mdx' +### Assume Role Configuration + +@include 'builder/amazon/common/AssumeRoleConfig.mdx' + +@include 'builder/amazon/common/AssumeRoleConfig-not-required.mdx' + ### Polling Configuration @include 'builder/amazon/common/AWSPollingConfig.mdx' diff --git a/website/pages/docs/builders/amazon/index.mdx b/website/pages/docs/builders/amazon/index.mdx index e7d8af6c4..f35f1dbd4 100644 --- a/website/pages/docs/builders/amazon/index.mdx +++ b/website/pages/docs/builders/amazon/index.mdx @@ -93,6 +93,16 @@ source "amazon-ebs" "basic-example" { +If you would like, you may also assume a role using the assume_role +configuration option. You must still have one of the valid credential resources +explained above, and your user must have permission to assume the role in +question. This is a way of running Packer with a more restrictive set of +permissions than your user. + +@include 'builder/amazon/common/AssumeRoleConfig.mdx' + +@include 'builder/amazon/common/AssumeRoleConfig-not-required.mdx' + ### Environment variables You can provide your credentials via the `AWS_ACCESS_KEY_ID` and diff --git a/website/pages/docs/builders/amazon/instance.mdx b/website/pages/docs/builders/amazon/instance.mdx index 76686ce95..9894993ca 100644 --- a/website/pages/docs/builders/amazon/instance.mdx +++ b/website/pages/docs/builders/amazon/instance.mdx @@ -85,6 +85,12 @@ necessary for this build to succeed and can be found further down the page. @include 'builder/amazon/common/AccessConfig-not-required.mdx' +### Assume Role Configuration + +@include 'builder/amazon/common/AssumeRoleConfig.mdx' + +@include 'builder/amazon/common/AssumeRoleConfig-not-required.mdx' + ### Polling Configuration @include 'builder/amazon/common/AWSPollingConfig.mdx' diff --git a/website/pages/docs/builders/azure/arm.mdx b/website/pages/docs/builders/azure/arm.mdx index 5cb0a1b3f..be2d84905 100644 --- a/website/pages/docs/builders/azure/arm.mdx +++ b/website/pages/docs/builders/azure/arm.mdx @@ -147,6 +147,16 @@ Providing `temp_resource_group_name` or `location` in combination with @include 'builder/azure/common/client/Config-not-required.mdx' +### Communicator Config + +In addition to the builder options, a communicator may also be defined: + +@include 'helper/communicator/Config-not-required.mdx' + +@include 'helper/communicator/SSH-not-required.mdx' + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' + ## Basic Example Here is a basic example for Azure. diff --git a/website/pages/docs/builders/cloudstack.mdx b/website/pages/docs/builders/cloudstack.mdx index e09986034..0557dedde 100644 --- a/website/pages/docs/builders/cloudstack.mdx +++ b/website/pages/docs/builders/cloudstack.mdx @@ -145,14 +145,6 @@ builder. - `security_groups` (array of strings) - A list of security group IDs or names to associate the instance with. -- `ssh_agent_auth` (boolean) - If true, the local SSH agent will be used to - authenticate connections to the source instance. No temporary keypair will - be created, and the values of `ssh_password` and `ssh_private_key_file` - will be ignored. To use this option with a key pair already configured in - the source image, leave the `keypair` blank. To associate an existing key - pair with the source instance, set the `keypair` field to the name of the - key pair. - - `ssl_no_verify` (boolean) - Set to `true` to skip SSL verification. Defaults to `false`. @@ -205,6 +197,30 @@ The available variables are: configuration parameter. If `http_directory` isn't specified, these will be blank. Example: `{{.HTTPIP}}:{{.HTTPPort}}/path/to/a/file/in/http_directory` +### Communicator Configuration + +#### Optional: + +@include 'helper/communicator/Config-not-required.mdx' + +@include 'helper/communicator/SSH-not-required.mdx' + +@include 'helper/communicator/SSH-Temporary-Key-Pair-not-required.mdx' + +@include 'helper/communicator/SSH-Key-Pair-Name-not-required.mdx' + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' + +@include 'helper/communicator/SSH-Agent-Auth-not-required.mdx' + +## Http directory configuration + +@include 'common/HTTPConfig.mdx' + +### Optional: + +@include 'common/HTTPConfig-not-required.mdx' + ## Basic Example Here is a basic example. diff --git a/website/pages/docs/builders/digitalocean.mdx b/website/pages/docs/builders/digitalocean.mdx index c7cc74427..8125b0a17 100644 --- a/website/pages/docs/builders/digitalocean.mdx +++ b/website/pages/docs/builders/digitalocean.mdx @@ -34,9 +34,16 @@ There are many configuration options available for the builder. They are segmented below into two categories: required and optional parameters. Within each category, the available configuration keys are alphabetized. -In addition to the options listed here, a -[communicator](/docs/templates/communicator) can be configured for this -builder. +### Communicator Config + +In addition to the builder options, a +[communicator](/docs/templates/communicator) can be configured for this builder. + +@include 'helper/communicator/Config-not-required.mdx' + +@include 'helper/communicator/SSH-not-required.mdx' + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' ### Required: diff --git a/website/pages/docs/builders/docker.mdx b/website/pages/docs/builders/docker.mdx index 2c33dff3b..f62cae8da 100644 --- a/website/pages/docs/builders/docker.mdx +++ b/website/pages/docs/builders/docker.mdx @@ -215,6 +215,16 @@ You must specify (only) one of `commit`, `discard`, or `export_path`. @include 'builder/docker/Config-not-required.mdx' +## Build Shared Information Variables + +This build shares generated data with provisioners and post-processors via [template engines](/docs/templates/engine) +for JSON and [contextual variables](/docs/from-1.5/contextual-variables) for HCL2. + +The generated variable available for this builder is: + +- `ImageSha256` - When committing a container to an image, this will give the image SHA256. Because the image is not available at the provision step, +this variable is only available for post-processors. + ## Using the Artifact: Export Once the tar artifact has been generated, you will likely want to import, tag, diff --git a/website/pages/docs/builders/googlecompute.mdx b/website/pages/docs/builders/googlecompute.mdx index 89b49204d..3982fb01d 100644 --- a/website/pages/docs/builders/googlecompute.mdx +++ b/website/pages/docs/builders/googlecompute.mdx @@ -346,6 +346,16 @@ In addition to the options listed here, a [communicator](/docs/templates/communicator) can be configured for this builder. +### Communicator Configuration + +#### Optional: + +@include 'helper/communicator/Config-not-required.mdx' + +@include 'helper/communicator/SSH-not-required.mdx' + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' + ### Required: @include 'builder/googlecompute/Config-required.mdx' diff --git a/website/pages/docs/builders/hetzner-cloud.mdx b/website/pages/docs/builders/hetzner-cloud.mdx index 2d6e43016..88dc055d8 100644 --- a/website/pages/docs/builders/hetzner-cloud.mdx +++ b/website/pages/docs/builders/hetzner-cloud.mdx @@ -33,7 +33,7 @@ In addition to the options listed here, a [communicator](/docs/templates/communicator) can be configured for this builder. -### Required: +### Required Builder Configuration options: - `token` (string) - The client TOKEN to use to access your account. It can also be specified via environment variable `HCLOUD_TOKEN`, if set. diff --git a/website/pages/docs/builders/hyperv/iso.mdx b/website/pages/docs/builders/hyperv/iso.mdx index d5c7eef18..af78850d4 100644 --- a/website/pages/docs/builders/hyperv/iso.mdx +++ b/website/pages/docs/builders/hyperv/iso.mdx @@ -105,6 +105,10 @@ builder. @include 'common/FloppyConfig-not-required.mdx' +### CD configuration reference + +@include 'common/CDConfig-not-required.mdx' + ## Communicator configuration reference ### Optional common fields: @@ -115,6 +119,8 @@ builder. @include 'helper/communicator/SSH-not-required.mdx' +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' + ### Optional WinRM fields: @include 'helper/communicator/WinRM-not-required.mdx' @@ -136,8 +142,8 @@ for the version of Hyper-V that is running. Floppy drives are no longer supported by generation 2 machines. This requires you to take another approach when dealing with preseed or answer files. Two -possible options are using virtual DVD drives or using Packers built in web -server. +possible options are using your own virtual DVD drives, the cd_files option, +or using Packer's built in web server. When dealing with Windows you need to enable UEFI drives for generation 2 virtual machines. @@ -852,4 +858,4 @@ is actually installed and ready to be connected to. For more information about the hyper-v daemons and supported distributions, see the Microsoft docs at -https://docs.microsoft.com/en-us/windows-server/virtualization/hyper-v/supported-linux-and-freebsd-virtual-machines-for-hyper-v-on-windows \ No newline at end of file +https://docs.microsoft.com/en-us/windows-server/virtualization/hyper-v/supported-linux-and-freebsd-virtual-machines-for-hyper-v-on-windows diff --git a/website/pages/docs/builders/hyperv/vmcx.mdx b/website/pages/docs/builders/hyperv/vmcx.mdx index 390bb6d92..6ee142587 100644 --- a/website/pages/docs/builders/hyperv/vmcx.mdx +++ b/website/pages/docs/builders/hyperv/vmcx.mdx @@ -113,10 +113,20 @@ builder. @include 'helper/communicator/SSH-not-required.mdx' +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' + ### Optional WinRM fields: @include 'helper/communicator/WinRM-not-required.mdx' +### CD configuration + +@include 'common/CDConfig.mdx' + +#### Optional: + +@include 'common/CDConfig-not-required.mdx' + ## Boot Command The `boot_command` configuration is very important: it specifies the keys to @@ -153,6 +163,14 @@ The example shown below is a working boot command used to start an Ubuntu For more examples of various boot commands, see the sample projects from our [community templates page](/community-tools#templates). +## Http directory configuration + +@include 'common/HTTPConfig.mdx' + +### Optional: + +@include 'common/HTTPConfig-not-required.mdx' + ## Integration Services Packer will automatically attach the integration services ISO as a DVD drive @@ -162,7 +180,7 @@ for the version of Hyper-V that is running. Floppy drives are no longer supported by generation 2 machines. This requires you to take another approach when dealing with preseed or answer files. Two -possible options are using virtual DVD drives or using Packers built in web +possible options are using the `cd_files` option or using Packer's built in web server. When dealing with Windows you need to enable UEFI drives for generation 2 diff --git a/website/pages/docs/builders/jdcloud.mdx b/website/pages/docs/builders/jdcloud.mdx index 9fee82a46..dd82fa829 100644 --- a/website/pages/docs/builders/jdcloud.mdx +++ b/website/pages/docs/builders/jdcloud.mdx @@ -36,6 +36,21 @@ are given below: - `subnet_id` (string) - An instance is supposed to exists in an subnet, if not specified , we will create new one for you +In addition to the above configuration options, a communicator can be configured for this builder: +### Communicator Configuration + +#### Optional: + +@include 'helper/communicator/Config-not-required.mdx' + +@include 'helper/communicator/SSH-not-required.mdx' + +@include 'helper/communicator/SSH-Temporary-Key-Pair-not-required.mdx' + +@include 'helper/communicator/SSH-Key-Pair-Name-not-required.mdx' + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' + ## Examples Here is a basic example for JDCloud. diff --git a/website/pages/docs/builders/linode.mdx b/website/pages/docs/builders/linode.mdx index a3f471c53..bc63e04ce 100644 --- a/website/pages/docs/builders/linode.mdx +++ b/website/pages/docs/builders/linode.mdx @@ -37,7 +37,10 @@ each category, the available configuration keys are alphabetized. In addition to the options listed here, a [communicator](/docs/templates/communicator) can be configured for this -builder. +builder. In addition to the options defined there, a private key file +can also be supplied to override the typical auto-generated key: + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' ### Required diff --git a/website/pages/docs/builders/oneandone.mdx b/website/pages/docs/builders/oneandone.mdx index e82c41279..7262037a5 100644 --- a/website/pages/docs/builders/oneandone.mdx +++ b/website/pages/docs/builders/oneandone.mdx @@ -20,7 +20,10 @@ each category, the available configuration keys are alphabetized. In addition to the options listed here, a [communicator](/docs/templates/communicator) can be configured for this -builder. +builder. In addition to the options defined there, a private key file +can also be supplied to override the typical auto-generated key: + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' ### Required diff --git a/website/pages/docs/builders/oracle/classic.mdx b/website/pages/docs/builders/oracle/classic.mdx index 06adc9254..13ba6078e 100644 --- a/website/pages/docs/builders/oracle/classic.mdx +++ b/website/pages/docs/builders/oracle/classic.mdx @@ -159,6 +159,8 @@ If this is set, a few more options become available. } ``` + See below for more details on configuring this communicator. + - `builder_image_list` (string) - This is the image to use for the builder instance. This _must_ be a linux image, and Oracle Linux is recommended. Default: `/oracle/public/OL_7.2_UEKR4_x86_64`. @@ -181,6 +183,19 @@ If this is set, a few more options become available. variables: `{{ .Username }}`, `{{ .Password }}`, `{{ .AccountID }}`, `{{ .ImageFile }}`, and `{{ .SegmentPath }}`. + +### Communicator Configuration + +The `builder_communicator` has the following options: + +#### Optional: + +@include 'helper/communicator/Config-not-required.mdx' + +@include 'helper/communicator/SSH-not-required.mdx' + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' + ## Basic Example Here is a basic example. Note that account specific configuration has been diff --git a/website/pages/docs/builders/oracle/oci.mdx b/website/pages/docs/builders/oracle/oci.mdx index 209282f43..9e9b7a82b 100644 --- a/website/pages/docs/builders/oracle/oci.mdx +++ b/website/pages/docs/builders/oracle/oci.mdx @@ -44,6 +44,11 @@ addition to the options listed here, a [communicator](/docs/templates/communicator) can be configured for this builder. +In addition to the options defined there, a private key file +can also be supplied to override the typical auto-generated key: + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' + ### Required - `availability_domain` (string) - The name of the [Availability @@ -66,7 +71,7 @@ builder. operation available in the Core Services API. - `compartment_ocid` (string) - The OCID of the - [compartment](https://docs.us-phoenix-1.oraclecloud.com/Content/GSG/Tasks/choosingcompartments.htm) + [compartment](https://docs.us-phoenix-1.oraclecloud.com/Content/GSG/Tasks/choosingcompartments.htm) that the instance will run in. - `shape` (string) - The template that determines the number of CPUs, amount of memory, and other resources allocated to a newly created instance. @@ -131,15 +136,29 @@ builder. - `image_name` (string) - The name to assign to the resulting custom image. +- `image_compartment_ocid` (string) - The OCID of the target compartment for the resulting image. Defaults to `compartment_ocid`. + - `instance_name` (string) - The name to assign to the instance used for the image creation process. If not set a name of the form `instanceYYYYMMDDhhmmss` will be used. -- `instance_tags` (map of strings) - Add one or more freeform tags to the instance used for the +- `instance_tags` (map of strings) - Add one or more freeform tags to the instance used for the image creation process. - `instance_defined_tags` (map of maps of strings) - Add one or more defined tags for a given namespace to the instance used for the image creation process. +- `create_vnic_details` (map of strings) - Specify details for the virtual network interface card (VNIC) + that is attached to the instance. Possible keys (all optional) are: `assign_public_ip` (bool), + `display_name` (string), `hostname_lable` (string), `nsg_ids` (list), `private_ip` (string), + `skip_source_dest_check` (bool), `subnet_id` (string), `tags` (map of string), and `defined_tags` + (map of maps of strings). See + [the Oracle docs](https://docs.cloud.oracle.com/en-us/iaas/Content/Network/Tasks/managingVNICs.htm) + for more information about VNICs. + +- `disk_size` (int64) - The size of the boot volume in GBs. Minimum value is 50 and maximum value is 16384 (16TB). + Sets the [BootVolumeSizeInGBs](https://godoc.org/github.com/oracle/oci-go-sdk/core#InstanceConfigurationInstanceSourceViaImageDetails) + when launching the instance. Defaults to `50`. + - `use_private_ip` (boolean) - Use private ip addresses to connect to the instance via ssh. @@ -244,3 +263,43 @@ Build 'oracle-oci' finished. --> oracle-oci: An image was created: 'ExampleImage' (OCID: ocid1.image.oc1.phx.aaa) in region 'us-phoenix-1' [opc@packerhost ~]$ ``` + +## Assigning Tags and Network Security Groups to the Instance +Tags are useful for breaking down costs and usage. The keys `instance_tags` +and `instance_defined_tags` are assigned to the temporary instance, +whereas `tags` and `defined_tags` are assigned to the resulting image. + +Network Security Groups (NSGs) are used for granting networking permissions +to the instance. Depending on network (VCN and subnet) setup, this may be +required for Packer to successfully SSH into the instance. NSGs are a property +of the virtual network interface card (VNIC) attached to the instance, and +are listed in `nsg_ids` under `create_vnic_details`. +``` +{ + "name": "base-image-{{isotime \"20060102030405\"}}", + "type": "oracle-oci", + "availability_domain": "aaaa:PHX-AD-1", + "base_image_ocid": "ocid1.image.oc1.iad.aaa", + "compartment_ocid": "ocid1.compartment.oc1..aaa", + "image_name": "my-image-{{isotime \"20060102030405\"}}", + "shape": "VM.Standard.E2.1", + "subnet_ocid": "ocid1.subnet.oc1.iad.aaa", + "use_private_ip": "true", + "instance_name": "packer-build-{{isotime \"20060102030405\"}}", + "instance_tags": { "testing": "yes" }, + "instance_defined_tags": { + "Operations": { + "Team": "CostCenter", + "Environment": "prod" + } + }, + "create_vnic_details": { + "assign_public_ip": "false", + "display_name": "testing-123", + "nsg_ids": ["ocid1.networksecuritygroup.oc1.iad.aaa"] + }, + "tags": { + "CreationDate": "{{isotime \"20060102 03:04:05 MST\"}}" + } +} +``` diff --git a/website/pages/docs/builders/outscale/bsu.mdx b/website/pages/docs/builders/outscale/bsu.mdx index 0fd7b4c53..a6135d93e 100644 --- a/website/pages/docs/builders/outscale/bsu.mdx +++ b/website/pages/docs/builders/outscale/bsu.mdx @@ -197,9 +197,11 @@ builder. This will fail unless _exactly_ one OMIS is returned. In the above example, `most_recent` will cause this to succeed by selecting the newest image. -- `ssh_keypair_name` (string) - If specified, this is the key that will be used for SSH with the machine. The key must match a key pair name loaded up into Outscale. By default, this is blank, and Packer will generate a temporary keypair unless [`ssh_password`](/docs/communicators/ssh#ssh_password) is used. [`ssh_private_key_file`](/docs/communicators/ssh#ssh_private_key_file) or `ssh_agent_auth` must be specified when `ssh_keypair_name` is utilized. +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' -- `ssh_agent_auth` (boolean) - If true, the local SSH agent will be used to authenticate connections to the source VM. No temporary keypair will be created, and the values of `ssh_password` and `ssh_private_key_file` will be ignored. To use this option with a key pair already configured in the source OMI, leave the `ssh_keypair_name` blank. To associate an existing key pair in Outscale with the source VM, set the `ssh_keypair_name` field to the name of the key pair. +@include 'helper/communicator/SSH-Key-Pair-Name-not-required.mdx' + +@include 'helper/communicator/SSH-Agent-Auth-not-required.mdx' - `ssh_interface` (string) - One of `public_ip`, `private_ip`, `public_dns`, or `private_dns`. If set, either the public IP address, private IP address, public DNS name or private DNS name will used as the host for SSH. The default behaviour if inside a Net is to use the public IP address if available, otherwise the private IP address will be used. If not in a Net the public DNS name will be used. Also works for WinRM. diff --git a/website/pages/docs/builders/parallels/iso.mdx b/website/pages/docs/builders/parallels/iso.mdx index 248537434..ed5d0e519 100644 --- a/website/pages/docs/builders/parallels/iso.mdx +++ b/website/pages/docs/builders/parallels/iso.mdx @@ -55,7 +55,10 @@ category, the available options are alphabetized and described. In addition to the options listed here, a [communicator](/docs/templates/communicator) can be configured for this -builder. +builder. In addition to the options defined there, a private key file +can also be supplied to override the typical auto-generated key: + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' ## ISO Configuration Reference diff --git a/website/pages/docs/builders/parallels/pvm.mdx b/website/pages/docs/builders/parallels/pvm.mdx index 175b0c99f..5dbf79025 100644 --- a/website/pages/docs/builders/parallels/pvm.mdx +++ b/website/pages/docs/builders/parallels/pvm.mdx @@ -52,7 +52,10 @@ category, the available options are alphabetized and described. In addition to the options listed here, a [communicator](/docs/templates/communicator) can be configured for this -builder. +builder. In addition to the options defined there, a private key file +can also be supplied to override the typical auto-generated key: + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' ### Required: diff --git a/website/pages/docs/builders/profitbricks.mdx b/website/pages/docs/builders/profitbricks.mdx index 98f423455..216db8c99 100644 --- a/website/pages/docs/builders/profitbricks.mdx +++ b/website/pages/docs/builders/profitbricks.mdx @@ -20,7 +20,10 @@ each category, the available configuration keys are alphabetized. In addition to the options listed here, a [communicator](/docs/templates/communicator) can be configured for this -builder. +builder. In addition to the options defined there, a private key file +can also be supplied to override the typical auto-generated key: + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' ### Required diff --git a/website/pages/docs/builders/proxmox/iso.mdx b/website/pages/docs/builders/proxmox/iso.mdx index 4305be528..b290b5937 100644 --- a/website/pages/docs/builders/proxmox/iso.mdx +++ b/website/pages/docs/builders/proxmox/iso.mdx @@ -185,6 +185,11 @@ builder. `raw`, `cow`, `qcow`, `qed`, `qcow2`, `vmdk` or `cloop`. Defaults to `raw`. + - `io_thread` (bool) - Create one I/O thread per storage controller, rather + than a single thread for all I/O. This can increase performance when + multiple disks are used. Requires `virtio-scsi-single` controller and a + `scsi` or `virtio` disk. Defaults to `false`. + - `template_name` (string) - Name of the template. Defaults to the generated name used during creation. @@ -245,6 +250,56 @@ builder. - `iso_checksum` (string) - Checksum of the ISO file. - `unmount` (bool) - If true, remove the mounted ISO from the template after finishing. Defaults to `false`. +- `http_interface` - (string) - Name of the network interface that Packer gets + `HTTPIP` from. Defaults to the first non loopback interface. + +- `vm_interface` - (string) - Name of the network interface that Packer gets + the VMs IP from. Defaults to the first non loopback interface. + +## Boot Command + +The `boot_command` configuration is very important: it specifies the keys to +type when the virtual machine is first booted in order to start the OS +installer. This command is typed after `boot_wait`, which gives the virtual +machine some time to actually load the ISO. + +As documented above, the `boot_command` is an array of strings. The strings +are all typed in sequence. It is an array only to improve readability within +the template. + +The boot command is "typed" character for character over the virtual keyboard +to the machine, simulating a human actually typing the keyboard. + +@include 'builders/boot-command.mdx' + +The example shown below is a working boot command used to start an Ubuntu +12.04 installer: + +```json +[ + "", + "/install/vmlinuz noapic ", + "preseed/url=http://{{ .HTTPIP }}:{{ .HTTPPort }}/preseed.cfg ", + "debian-installer=en_US auto locale=en_US kbd-chooser/method=us ", + "hostname={{ .Name }} ", + "fb=false debconf/frontend=noninteractive ", + "keyboard-configuration/modelcode=SKIP keyboard-configuration/layout=USA ", + "keyboard-configuration/variant=USA console-setup/ask_detect=false ", + "initrd=/install/initrd.gz -- " +] +``` + +For more examples of various boot commands, see the sample projects from our +[community templates page](/community-tools#templates). + +## Http directory configuration + +@include 'common/HTTPConfig.mdx' + +### Optional: + +@include 'common/HTTPConfig-not-required.mdx' + ## Example: Fedora with kickstart Here is a basic example creating a Fedora 29 server image with a Kickstart diff --git a/website/pages/docs/builders/qemu.mdx b/website/pages/docs/builders/qemu.mdx index 584010a9a..d81fb3e50 100644 --- a/website/pages/docs/builders/qemu.mdx +++ b/website/pages/docs/builders/qemu.mdx @@ -2,7 +2,7 @@ modeline: | vim: set ft=pandoc: description: | - The Qemu Packer builder is able to create KVM and Xen virtual machine images. + The Qemu Packer builder is able to create KVM virtual machine images. layout: docs page_title: QEMU - Builders sidebar_title: QEMU @@ -12,14 +12,14 @@ sidebar_title: QEMU Type: `qemu` -The Qemu Packer builder is able to create [KVM](http://www.linux-kvm.org) and -[Xen](http://www.xenproject.org) virtual machine images. +The Qemu Packer builder is able to create [KVM](http://www.linux-kvm.org) virtual +machine images. The builder builds a virtual machine by creating a new virtual machine from scratch, booting it, installing an OS, rebooting the machine with the boot media as the virtual hard drive, provisioning software within the OS, then shutting it down. The result of the Qemu builder is a directory containing the image file -necessary to run the virtual machine on KVM or Xen. +necessary to run the virtual machine on KVM. ## Basic Example @@ -144,6 +144,14 @@ necessary for this build to succeed and can be found further down the page. @include 'common/FloppyConfig-not-required.mdx' +### CD configuration + +@include 'common/CDConfig.mdx' + +#### Optional: + +@include 'common/CDConfig-not-required.mdx' + ## Shutdown configuration ### Optional: @@ -162,6 +170,8 @@ necessary for this build to succeed and can be found further down the page. @include 'helper/communicator/SSH-not-required.mdx' +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' + ### Optional WinRM fields: @include 'helper/communicator/WinRM-not-required.mdx' @@ -186,6 +196,8 @@ necessary for this build to succeed and can be found further down the page. ### Troubleshooting +#### Invalid Keymaps + Some users have experienced errors complaining about invalid keymaps. This seems to be related to having a `common` directory or file in the directory they've run Packer in, like the packer source directory. This appears to be an @@ -195,3 +207,14 @@ file/directory or run in another directory. Some users have reported issues with incorrect keymaps using qemu version 2.11. This is a bug with qemu, and the solution is to upgrade, or downgrade to 2.10.1 or earlier. + +#### Corrupted image after Packer calls qemu-img convert on OSX + +Due to an upstream bug with `qemu-img convert` on OSX, sometimes the qemu-img +convert call will create a corrupted image. If this is an issue for you, make +sure that the the output format (provided using the option `format`) matches +the input file's format and file extension, and Packer will +perform a simple copy operation instead. You will also want to set +`"skip_compaction": true,` and `"disk_compression": false` to skip a final +image conversion at the end of the build. See +https://bugs.launchpad.net/qemu/+bug/1776920 for more details. \ No newline at end of file diff --git a/website/pages/docs/builders/scaleway.mdx b/website/pages/docs/builders/scaleway.mdx index 3872b19e2..a93fbdbaf 100644 --- a/website/pages/docs/builders/scaleway.mdx +++ b/website/pages/docs/builders/scaleway.mdx @@ -36,7 +36,10 @@ each category, the available configuration keys are alphabetized. In addition to the options listed here, a [communicator](/docs/templates/communicator) can be configured for this -builder. +builder. In addition to the options defined there, a private key file +can also be supplied to override the typical auto-generated key: + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' ### Required: @@ -105,6 +108,6 @@ access tokens: } ``` -When you do not specified the `ssh_private_key_file`, a temporarily SSH keypair +When you do not specify the `ssh_private_key_file`, a temporary SSH keypair is generated to connect the server. This key will only allow the `root` user to connect the server. diff --git a/website/pages/docs/builders/tencentcloud-cvm.mdx b/website/pages/docs/builders/tencentcloud-cvm.mdx index c4e3777df..b03c17cb0 100644 --- a/website/pages/docs/builders/tencentcloud-cvm.mdx +++ b/website/pages/docs/builders/tencentcloud-cvm.mdx @@ -125,6 +125,25 @@ a [communicator](/docs/templates/communicator) can be configured for this builde - `run_tags` (map of strings) - Tags to apply to the instance that is _launched_ to create the image. These tags are _not_ applied to the resulting image. +### Communicator Configuration + +In addition to the above options, a communicator can be configured +for this builder. + +#### Optional: + +@include 'helper/communicator/Config-not-required.mdx' + +@include 'helper/communicator/SSH-not-required.mdx' + +@include 'helper/communicator/SSH-Temporary-Key-Pair-not-required.mdx' + +@include 'helper/communicator/SSH-Key-Pair-Name-not-required.mdx' + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' + +@include 'helper/communicator/SSH-Agent-Auth-not-required.mdx' + ## Basic Example Here is a basic example for Tencentcloud. diff --git a/website/pages/docs/builders/triton.mdx b/website/pages/docs/builders/triton.mdx index a458a76e4..bd822de30 100644 --- a/website/pages/docs/builders/triton.mdx +++ b/website/pages/docs/builders/triton.mdx @@ -49,7 +49,12 @@ segmented below into two categories: required and optional parameters. In addition to the options listed here, a [communicator](/docs/templates/communicator) can be configured for this -builder. +builder. In addition to the options defined there, a private key file +can also be supplied to override the typical auto-generated key: + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' + +@include 'helper/communicator/SSH-Agent-Auth-not-required.mdx' ### Required: diff --git a/website/pages/docs/builders/virtualbox/iso.mdx b/website/pages/docs/builders/virtualbox/iso.mdx index 086732ac6..0aac5181e 100644 --- a/website/pages/docs/builders/virtualbox/iso.mdx +++ b/website/pages/docs/builders/virtualbox/iso.mdx @@ -121,6 +121,14 @@ necessary for this build to succeed and can be found further down the page. @include 'common/FloppyConfig-not-required.mdx' +### CD configuration + +@include 'common/CDConfig.mdx' + +#### Optional: + +@include 'common/CDConfig-not-required.mdx' + ### Export configuration #### Optional: @@ -171,10 +179,6 @@ necessary for this build to succeed and can be found further down the page. @include 'helper/communicator/SSH-not-required.mdx' -@include 'helper/communicator/SSH-Temporary-Key-Pair-not-required.mdx' - -@include 'helper/communicator/SSH-Key-Pair-Name-not-required.mdx' - @include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' @include 'helper/communicator/SSH-Agent-Auth-not-required.mdx' diff --git a/website/pages/docs/builders/virtualbox/ovf.mdx b/website/pages/docs/builders/virtualbox/ovf.mdx index 876fdd43a..21eade0e9 100644 --- a/website/pages/docs/builders/virtualbox/ovf.mdx +++ b/website/pages/docs/builders/virtualbox/ovf.mdx @@ -123,6 +123,14 @@ necessary for this build to succeed and can be found further down the page. @include 'common/FloppyConfig-not-required.mdx' +### CD configuration + +@include 'common/CDConfig.mdx' + +#### Optional: + +@include 'common/CDConfig-not-required.mdx' + ### Export configuration #### Optional: diff --git a/website/pages/docs/builders/virtualbox/vm.mdx b/website/pages/docs/builders/virtualbox/vm.mdx index 200b4aede..f189e0a68 100644 --- a/website/pages/docs/builders/virtualbox/vm.mdx +++ b/website/pages/docs/builders/virtualbox/vm.mdx @@ -92,6 +92,7 @@ the items listed here, you will want to look at the general configuration references for [ISO](#iso-configuration), [HTTP](#http-directory-configuration), [Floppy](#floppy-configuration), +[CD](#CD-configuration), [Export](#export-configuration), [Boot](#boot-configuration), [Shutdown](#shutdown-configuration), @@ -133,6 +134,14 @@ builder. @include 'common/FloppyConfig-not-required.mdx' +### CD configuration + +@include 'common/CDConfig.mdx' + +#### Optional: + +@include 'common/CDConfig-not-required.mdx' + ### Export configuration #### Optional: diff --git a/website/pages/docs/builders/vmware/iso.mdx b/website/pages/docs/builders/vmware/iso.mdx index 12b447add..ea21ed1bb 100644 --- a/website/pages/docs/builders/vmware/iso.mdx +++ b/website/pages/docs/builders/vmware/iso.mdx @@ -78,6 +78,7 @@ the items listed here, you will want to look at the general configuration references for [ISO](#iso-configuration), [HTTP](#http-directory-configuration), [Floppy](#floppy-configuration), +[CD](#cd-configuration), [Boot](#boot-configuration), [Driver](#driver-configuration), [Hardware](#hardware-configuration), @@ -129,6 +130,9 @@ necessary for this build to succeed and can be found further down the page. @include 'common/FloppyConfig-not-required.mdx' +### CD configuration +@include 'common/CDConfig-not-required.mdx' + ### Shutdown configuration #### Optional: @@ -155,6 +159,8 @@ necessary for this build to succeed and can be found further down the page. ### Run configuration +@include 'builder/vmware/common/RunConfig.mdx' + #### Optional: @include 'builder/vmware/common/RunConfig-not-required.mdx' diff --git a/website/pages/docs/builders/vmware/vmx.mdx b/website/pages/docs/builders/vmware/vmx.mdx index 71fad1a0f..f7efbc017 100644 --- a/website/pages/docs/builders/vmware/vmx.mdx +++ b/website/pages/docs/builders/vmware/vmx.mdx @@ -119,6 +119,14 @@ necessary for this build to succeed and can be found further down the page. @include 'common/FloppyConfig-not-required.mdx' +### CD configuration + +@include 'common/CDConfig.mdx' + +#### Optional: + +@include 'common/CDConfig-not-required.mdx' + ### Export configuration #### Optional: @@ -133,6 +141,8 @@ necessary for this build to succeed and can be found further down the page. ### Run configuration +@include 'builder/vmware/common/RunConfig.mdx' + #### Optional: @include 'builder/vmware/common/RunConfig-not-required.mdx' @@ -188,6 +198,7 @@ to modify the network configuration after the VM is done building. #### Optional: @include 'common/bootcommand/VNCConfig-not-required.mdx' + @include 'common/bootcommand/BootConfig-not-required.mdx' For more examples of various boot commands, see the sample projects from our @@ -198,7 +209,7 @@ For more examples of various boot commands, see the sample projects from our "builders": [ { "type": "vmware-vmx", - "boot_key_interval": "10ms" + "boot_key_interval": "10ms", ... } ] diff --git a/website/pages/docs/builders/vmware/vsphere-clone.mdx b/website/pages/docs/builders/vmware/vsphere-clone.mdx index b6d4d0c4b..588ceca9a 100644 --- a/website/pages/docs/builders/vmware/vsphere-clone.mdx +++ b/website/pages/docs/builders/vmware/vsphere-clone.mdx @@ -168,6 +168,10 @@ can be done via environment variable: @include 'common/HTTPConfig-not-required.mdx' +### Floppy configuration + +@include 'builder/vsphere/common/FloppyConfig-not-required.mdx' + ### Connection Configuration @include 'builder/vsphere/common/ConnectConfig-not-required.mdx' @@ -192,6 +196,18 @@ can be done via environment variable: @include 'builder/vsphere/common/WaitIpConfig-not-required.mdx' +### CDRom Configuration + +@include 'common/CDConfig.mdx' + +#### Optional: + +@include 'common/CDConfig-not-required.mdx' + +@include 'builder/vsphere/common/CDRomConfig-not-required.mdx' + +@include 'builder/vsphere/common/RemoveCDRomConfig-not-required.mdx' + ### Communicator configuration #### Optional common fields: diff --git a/website/pages/docs/builders/vmware/vsphere-iso.mdx b/website/pages/docs/builders/vmware/vsphere-iso.mdx index d88be5cda..c43d006de 100644 --- a/website/pages/docs/builders/vmware/vsphere-iso.mdx +++ b/website/pages/docs/builders/vmware/vsphere-iso.mdx @@ -97,7 +97,7 @@ source "vsphere-iso" "example" { ### Floppy configuration -@include 'builder/vsphere/iso/FloppyConfig-not-required.mdx' +@include 'builder/vsphere/common/FloppyConfig-not-required.mdx' ### Connection Configuration @@ -172,7 +172,15 @@ iso_paths = [ -@include 'builder/vsphere/iso/CDRomConfig-not-required.mdx' +@include 'builder/vsphere/common/CDRomConfig-not-required.mdx' + +@include 'builder/vsphere/common/RemoveCDRomConfig-not-required.mdx' + +@include 'common/CDConfig.mdx' + +#### Optional: + +@include 'common/CDConfig-not-required.mdx' ### Create Configuration diff --git a/website/pages/docs/builders/yandex.mdx b/website/pages/docs/builders/yandex.mdx index 331342c7a..7f8f51df3 100644 --- a/website/pages/docs/builders/yandex.mdx +++ b/website/pages/docs/builders/yandex.mdx @@ -63,7 +63,10 @@ optional. Within each category, the available options are alphabetized and described. In addition to the options listed here, a [communicator](/docs/templates/communicator) -can be configured for this builder. +can be configured for this builder. In addition to the options defined there, a private key file +can also be supplied to override the typical auto-generated key: + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' ### Required: diff --git a/website/pages/docs/commands/build.mdx b/website/pages/docs/commands/build.mdx index b1589ea15..98a4d68fe 100644 --- a/website/pages/docs/commands/build.mdx +++ b/website/pages/docs/commands/build.mdx @@ -48,11 +48,6 @@ artifacts that are created will be outputted at the end of the build. - `run-cleanup-provisioner` aborts and exits without any cleanup besides the [error-cleanup-provisioner](/docs/templates/provisioners#on-error-provisioner) if one is defined. -- `-only=foo,bar,baz` - Only run the builds with the given comma-separated - names. Build names by default are their type, unless a specific `name` - attribute is specified within the configuration. `-only` does not apply to - post-processors. - `@include 'commands/only.mdx'` - `-parallel-builds=N` - Limit the number of builds to run in parallel, 0 diff --git a/website/pages/docs/from-1.5/blocks/variable.mdx b/website/pages/docs/from-1.5/blocks/variable.mdx index 16bf86f0f..e7af7093a 100644 --- a/website/pages/docs/from-1.5/blocks/variable.mdx +++ b/website/pages/docs/from-1.5/blocks/variable.mdx @@ -30,6 +30,8 @@ Example of a variable assignment from a file: `@include 'from-1.5/variables/must-be-set.mdx'` +`@include 'from-1.5/variables/sensitive.mdx'` + # More on variables - Read the [full variables](/docs/from-1.5/variables) description for a more diff --git a/website/pages/docs/from-1.5/variables.mdx b/website/pages/docs/from-1.5/variables.mdx index 934f87447..1cd2eb260 100644 --- a/website/pages/docs/from-1.5/variables.mdx +++ b/website/pages/docs/from-1.5/variables.mdx @@ -356,3 +356,5 @@ other variables: the last value found overrides the previous values. | `var.bar` in .pkr.hcl file | error, "bar undeclared" | error, "bar undeclared" | | `-var bar=yz` argument | error, "bar undeclared" | error, "bar undeclared" | | `export PKR_VAR_bar=yz` | - | - | + +`@include 'from-1.5/variables/sensitive.mdx'` diff --git a/website/pages/docs/post-processors/vagrant.mdx b/website/pages/docs/post-processors/vagrant.mdx index b06441a29..9c718c5a0 100644 --- a/website/pages/docs/post-processors/vagrant.mdx +++ b/website/pages/docs/post-processors/vagrant.mdx @@ -102,7 +102,8 @@ more details about certain options in following sections. `lxc`, `scaleway`, `hyperv`, `parallels`, `aws`, or `google`. - `vagrantfile_template` (string) - Path to a template to use for the - Vagrantfile that is packaged with the box. + Vagrantfile that is packaged with the box. This option supports the usage of the [template engine](/docs/templates/engine) + for JSON and the [contextual variables](/docs/from-1.5/contextual-variables) for HCL2. - `vagrantfile_template_generated` (boolean) - By default, Packer will exit with an error if the file specified using the diff --git a/website/pages/partials/builder/amazon/common/AccessConfig-not-required.mdx b/website/pages/partials/builder/amazon/common/AccessConfig-not-required.mdx index faadd849b..17872ddf5 100644 --- a/website/pages/partials/builder/amazon/common/AccessConfig-not-required.mdx +++ b/website/pages/partials/builder/amazon/common/AccessConfig-not-required.mdx @@ -1,9 +1,16 @@ +- `assume_role` (AssumeRoleConfig) - If provided with a role ARN, Packer will attempt to assume this role + using the supplied credentials. See + [AssumeRoleConfig](#assume-role-configuration) below for more + details on all of the options available, and for a usage example. + - `custom_endpoint_ec2` (string) - This option is useful if you use a cloud provider whose API is compatible with aws EC2. Specify another endpoint like this https://ec2.custom.endpoint.com. +- `shared_credentials_file` (string) - Path to a credentials file to load credentials from + - `decode_authorization_messages` (bool) - Enable automatic decoding of any encoded authorization (error) messages using the `sts:DecodeAuthorizationMessage` API. Note: requires that the effective user/role have permissions to `sts:DecodeAuthorizationMessage` @@ -31,6 +38,8 @@ - `skip_metadata_api_check` (bool) - Skip Metadata Api Check +- `skip_credential_validation` (bool) - Set to true if you want to skip validating AWS credentials before runtime. + - `token` (string) - The access token to use. This is different from the access key and secret key. If you're not sure what this is, then you probably don't need it. This will also be read from the AWS_SESSION_TOKEN diff --git a/website/pages/partials/builder/amazon/common/AssumeRoleConfig-not-required.mdx b/website/pages/partials/builder/amazon/common/AssumeRoleConfig-not-required.mdx new file mode 100644 index 000000000..b330b6f09 --- /dev/null +++ b/website/pages/partials/builder/amazon/common/AssumeRoleConfig-not-required.mdx @@ -0,0 +1,20 @@ + + +- `role_arn` (string) - Amazon Resource Name (ARN) of the IAM Role to assume. + +- `duration_seconds` (int) - Number of seconds to restrict the assume role session duration. + +- `external_id` (string) - The external ID to use when assuming the role. If omitted, no external + ID is passed to the AssumeRole call. + +- `policy` (string) - IAM Policy JSON describing further restricting permissions for the IAM + Role being assumed. + +- `policy_arns` ([]string) - Set of Amazon Resource Names (ARNs) of IAM Policies describing further + restricting permissions for the IAM Role being + +- `session_name` (string) - Session name to use when assuming the role. + +- `tags` (map[string]string) - Map of assume role session tags. + +- `transitive_tag_keys` ([]string) - Set of assume role session tag keys to pass to any subsequent sessions. diff --git a/website/pages/partials/builder/amazon/common/AssumeRoleConfig.mdx b/website/pages/partials/builder/amazon/common/AssumeRoleConfig.mdx new file mode 100644 index 000000000..6eb7bb362 --- /dev/null +++ b/website/pages/partials/builder/amazon/common/AssumeRoleConfig.mdx @@ -0,0 +1,31 @@ + + +AssumeRoleConfig lets users set configuration options for assuming a special +role when executing Packer. + +Usage example: + +HCL config example: + +```HCL +source "example" "amazon-ebs"{ + assume_role { + role_arn = "arn:aws:iam::ACCOUNT_ID:role/ROLE_NAME" + session_name = "SESSION_NAME" + external_id = "EXTERNAL_ID" + } +} +``` + +JSON config example: + +```json +builder{ + "type": "amazon-ebs", + "assume_role": { + "role_arn" : "arn:aws:iam::ACCOUNT_ID:role/ROLE_NAME", + "session_name": "SESSION_NAME", + "external_id" : "EXTERNAL_ID" + } +} +``` diff --git a/website/pages/partials/builder/amazon/common/RunConfig-not-required.mdx b/website/pages/partials/builder/amazon/common/RunConfig-not-required.mdx index 6c3a3afd6..4d66cb0e1 100644 --- a/website/pages/partials/builder/amazon/common/RunConfig-not-required.mdx +++ b/website/pages/partials/builder/amazon/common/RunConfig-not-required.mdx @@ -383,6 +383,12 @@ - Upon termination the secure tunnel will be terminated automatically, if however there is a failure in terminating the tunnel it will automatically terminate itself after 20 minutes of inactivity. +- `pause_before_ssm` (duration string | ex: "1h5m2s") - The time to wait before establishing the Session Manager session. + The value of this should be a duration. Examples are + `5s` and `1m30s` which will cause Packer to wait five seconds and one + minute 30 seconds, respectively. If no set, defaults to 10 seconds. + This option is useful when the remote port takes longer to become available. + - `session_manager_port` (int) - Which port to connect the local end of the session tunnel to. If left blank, Packer will choose a port for you from available ports. This option is only used when `ssh_interface` is set `session_manager`. diff --git a/website/pages/partials/builder/azure/arm/Config-not-required.mdx b/website/pages/partials/builder/azure/arm/Config-not-required.mdx index 4f2330308..f1bfc1ec9 100644 --- a/website/pages/partials/builder/azure/arm/Config-not-required.mdx +++ b/website/pages/partials/builder/azure/arm/Config-not-required.mdx @@ -137,7 +137,7 @@ region that supports [availability zones](https://docs.microsoft.com/en-us/azure/availability-zones/az-overview). -- `azure_tags` (map[string]\*string) - Name/value pair tags to apply to every resource deployed i.e. Resource +- `azure_tags` (map[string]string) - Name/value pair tags to apply to every resource deployed i.e. Resource Group, VM, NIC, VNET, Public IP, KeyVault, etc. The user can define up to 15 tags. Tag names cannot exceed 512 characters, and tag values cannot exceed 256 characters. diff --git a/website/pages/partials/builder/openstack/RunConfig-not-required.mdx b/website/pages/partials/builder/openstack/RunConfig-not-required.mdx index ad6073e40..c5035abd8 100644 --- a/website/pages/partials/builder/openstack/RunConfig-not-required.mdx +++ b/website/pages/partials/builder/openstack/RunConfig-not-required.mdx @@ -9,6 +9,8 @@ connect via whichever IP address is returned first from the OpenStack API. +- `external_source_image_format` (string) - The format of the external source image to use, e.g. qcow2, raw. + - `availability_zone` (string) - The availability zone to launch the server in. If this isn't specified, the default enforced by your OpenStack cluster will be used. This may be required for some OpenStack clusters. diff --git a/website/pages/partials/builder/openstack/RunConfig-required.mdx b/website/pages/partials/builder/openstack/RunConfig-required.mdx index 3e50ce947..7351dcd8b 100644 --- a/website/pages/partials/builder/openstack/RunConfig-required.mdx +++ b/website/pages/partials/builder/openstack/RunConfig-required.mdx @@ -8,6 +8,9 @@ - `source_image_name` (string) - The name of the base image to use. This is an alternative way of providing source_image and only either of them can be specified. +- `external_source_image_url` (string) - The URL of an external base image to use. This is an alternative way of + providing source_image and only either of them can be specified. + - `source_image_filter` (ImageFilter) - Filters used to populate filter options. Example: ```json diff --git a/website/pages/partials/builder/qemu/Config-not-required.mdx b/website/pages/partials/builder/qemu/Config-not-required.mdx index 892b8e312..9b5b140de 100644 --- a/website/pages/partials/builder/qemu/Config-not-required.mdx +++ b/website/pages/partials/builder/qemu/Config-not-required.mdx @@ -1,4 +1,4 @@ - + - `iso_skip_cache` (bool) - Use iso from provided url. Qemu must support curl block device. This defaults to `false`. @@ -53,6 +53,10 @@ for disk_size, Packer uses a default of `40960M` (40 GB). If a disk_size number is provided with no units, Packer will default to Megabytes. +- `skip_resize_disk` (bool) - Packer resizes the QCOW2 image using + qemu-img resize. Set this option to true to disable resizing. + Defaults to false. + - `disk_cache` (string) - The cache mode to use for disk. Allowed values include any of `writethrough`, `writeback`, `none`, `unsafe` or `directsync`. By default, this is set to `writeback`. @@ -73,7 +77,12 @@ using qemu-img convert. Defaults to false. - `format` (string) - Either `qcow2` or `raw`, this specifies the output format of the virtual - machine image. This defaults to `qcow2`. + machine image. This defaults to `qcow2`. Due to a long-standing bug with + `qemu-img convert` on OSX, sometimes the qemu-img convert call will + create a corrupted image. If this is an issue for you, make sure that the + the output format matches the input file's format, and Packer will + perform a simple copy operation instead. See + https://bugs.launchpad.net/qemu/+bug/1776920 for more details. - `headless` (bool) - Packer defaults to building QEMU virtual machines by launching a GUI that shows the console of the machine being built. When this @@ -92,7 +101,9 @@ and format is qcow2, set this option to true to create a new QCOW2 file that uses the file located at iso_url as a backing file. The new file will only contain blocks that have changed compared to the backing file, so - enabling this option can significantly reduce disk usage. + enabling this option can significantly reduce disk usage. If true, Packer + will force the `skip_compaction` also to be true as well to skip disk + conversion which would render the backing file feature useless. - `machine_type` (string) - The type of machine emulation to use. Run your qemu binary with the flags `-machine help` to list available types for your system. This @@ -220,6 +231,36 @@ `{{ .HTTPIP }}`, `{{ .HTTPPort }}`, `{{ .HTTPDir }}`, `{{ .OutputDir }}`, `{{ .Name }}`, and `{{ .SSHHostPort }}` +- `qemu_img_args` (QemuImgArgs) - A map of custom arguments to pass to qemu-img commands, where the key + is the subcommand, and the values are lists of strings for each flag. + Example: + + In JSON: + ```json + { + "qemu_img_args": { + "convert": ["-o", "preallocation=full"], + "resize": ["-foo", "bar"] + } + ``` + Please note + that unlike qemuargs, these commands are not split into switch-value + sub-arrays, because the basic elements in qemu-img calls are unlikely + to need an actual override. + The arguments will be constructed as follows: + - Convert: + Default is `qemu-img convert -O $format $sourcepath $targetpath`. Adding + arguments ["-foo", "bar"] to qemu_img_args.convert will change this to + `qemu-img convert -foo bar -O $format $sourcepath $targetpath` + - Create: + Default is `create -f $format $targetpath $size`. Adding arguments + ["-foo", "bar"] to qemu_img_args.create will change this to + "create -f qcow2 -foo bar target.qcow2 1234M" + - Resize: + Default is `qemu-img resize -f $format $sourcepath $size`. Adding + arguments ["-foo", "bar"] to qemu_img_args.resize will change this to + `qemu-img resize -f $format -foo bar $sourcepath $size` + - `qemu_binary` (string) - The name of the Qemu binary to look for. This defaults to qemu-system-x86_64, but may need to be changed for some platforms. For example qemu-kvm, or qemu-system-i386 may be a diff --git a/website/pages/partials/builder/qemu/QemuImgArgs-not-required.mdx b/website/pages/partials/builder/qemu/QemuImgArgs-not-required.mdx new file mode 100644 index 000000000..7507e54a0 --- /dev/null +++ b/website/pages/partials/builder/qemu/QemuImgArgs-not-required.mdx @@ -0,0 +1,7 @@ + + +- `convert` ([]string) - Convert + +- `create` ([]string) - Create + +- `resize` ([]string) - Resize diff --git a/website/pages/partials/builder/scaleway/Config-not-required.mdx b/website/pages/partials/builder/scaleway/Config-not-required.mdx index 20a417b83..47c8b3e7b 100644 --- a/website/pages/partials/builder/scaleway/Config-not-required.mdx +++ b/website/pages/partials/builder/scaleway/Config-not-required.mdx @@ -1,5 +1,8 @@ +- `api_url` (string) - The Scaleway API URL to use + It can also be specified via the environment variable SCW_API_URL + - `snapshot_name` (string) - The name of the resulting snapshot that will appear in your account. Default packer-TIMESTAMP @@ -16,3 +19,22 @@ bootscript, Default bootscript - `remove_volume` (bool) - Remove Volume + +- `api_token` (string) - The token to use to authenticate with your account. + It can also be specified via environment variable SCALEWAY_API_TOKEN. You + can see and generate tokens in the "Credentials" + section of the control panel. + Deprecated, use SecretKey instead + +- `organization_id` (string) - The organization id to use to identify your + organization. It can also be specified via environment variable + SCALEWAY_ORGANIZATION. Your organization id is available in the + "Account" section of the + control panel. + Previously named: api_access_key with environment variable: SCALEWAY_API_ACCESS_KEY + Deprecated, use ProjectID instead + +- `region` (string) - The name of the region to launch the server in (par1 + or ams1). Consequently, this is the region where the snapshot will be + available. + Deprecated, use Zone instead diff --git a/website/pages/partials/builder/scaleway/Config-required.mdx b/website/pages/partials/builder/scaleway/Config-required.mdx index cafb63def..f3a641d37 100644 --- a/website/pages/partials/builder/scaleway/Config-required.mdx +++ b/website/pages/partials/builder/scaleway/Config-required.mdx @@ -1,20 +1,16 @@ -- `api_token` (string) - The token to use to authenticate with your account. - It can also be specified via environment variable SCALEWAY_API_TOKEN. You - can see and generate tokens in the "Credentials" - section of the control panel. +- `access_key` (string) - The AccessKey corresponding to the secret key. + It can also be specified via the environment variable SCW_ACCESS_KEY. -- `organization_id` (string) - The organization id to use to identify your - organization. It can also be specified via environment variable - SCALEWAY_ORGANIZATION. Your organization id is available in the - "Account" section of the - control panel. - Previously named: api_access_key with environment variable: SCALEWAY_API_ACCESS_KEY +- `secret_key` (string) - The SecretKey to authenticate against the Scaleway API. + It can also be specified via the environment variable SCW_SECRET_KEY. -- `region` (string) - The name of the region to launch the server in (par1 - or ams1). Consequently, this is the region where the snapshot will be - available. +- `project_id` (string) - The Project ID in which the instances, volumes and snapshots will be created. + It can also be specified via the environment variable SCW_DEFAULT_PROJECT_ID. + +- `zone` (string) - The Zone in which the instances, volumes and snapshots will be created. + It can also be specified via the environment variable SCW_DEFAULT_ZONE - `image` (string) - The UUID of the base image to use. This is the image that will be used to launch a new server and provision it. See diff --git a/website/pages/partials/builder/virtualbox/common/GuestAdditionsConfig-not-required.mdx b/website/pages/partials/builder/virtualbox/common/GuestAdditionsConfig-not-required.mdx index 7fbe8a29c..0c57a3f70 100644 --- a/website/pages/partials/builder/virtualbox/common/GuestAdditionsConfig-not-required.mdx +++ b/website/pages/partials/builder/virtualbox/common/GuestAdditionsConfig-not-required.mdx @@ -3,9 +3,32 @@ - `communicator` (string) - Communicator - `guest_additions_mode` (string) - The method by which guest additions are - made available to the guest for installation. Valid options are upload, - attach, or disable. If the mode is attach the guest additions ISO will - be attached as a CD device to the virtual machine. If the mode is upload + made available to the guest for installation. Valid options are `upload`, + `attach`, or `disable`. If the mode is `attach` the guest additions ISO will + be attached as a CD device to the virtual machine. If the mode is `upload` the guest additions ISO will be uploaded to the path specified by - guest_additions_path. The default value is upload. If disable is used, + `guest_additions_path`. The default value is `upload`. If `disable` is used, guest additions won't be downloaded, either. + +- `guest_additions_interface` (string) - The interface type to use to mount guest additions when + guest_additions_mode is set to attach. Will default to the value set in + iso_interface, if iso_interface is set. Will default to "ide", if + iso_interface is not set. Options are "ide" and "sata". + +- `guest_additions_path` (string) - The path on the guest virtual machine + where the VirtualBox guest additions ISO will be uploaded. By default this + is `VBoxGuestAdditions.iso` which should upload into the login directory of + the user. This is a [configuration + template](/docs/templates/engine) where the `Version` + variable is replaced with the VirtualBox version. + +- `guest_additions_sha256` (string) - The SHA256 checksum of the guest + additions ISO that will be uploaded to the guest VM. By default the + checksums will be downloaded from the VirtualBox website, so this only needs + to be set if you want to be explicit about the checksum. + +- `guest_additions_url` (string) - The URL of the guest additions ISO + to upload. This can also be a file URL if the ISO is at a local path. By + default, the VirtualBox builder will attempt to find the guest additions ISO + on the local file system. If it is not available locally, the builder will + download the proper guest additions ISO from the internet. diff --git a/website/pages/partials/builder/virtualbox/iso/Config-not-required.mdx b/website/pages/partials/builder/virtualbox/iso/Config-not-required.mdx index 89b15859b..55e348ac2 100644 --- a/website/pages/partials/builder/virtualbox/iso/Config-not-required.mdx +++ b/website/pages/partials/builder/virtualbox/iso/Config-not-required.mdx @@ -3,29 +3,6 @@ - `disk_size` (uint) - The size, in megabytes, of the hard disk to create for the VM. By default, this is 40000 (about 40 GB). -- `guest_additions_path` (string) - The path on the guest virtual machine where the VirtualBox guest - additions ISO will be uploaded. By default this is - VBoxGuestAdditions.iso which should upload into the login directory of - the user. This is a configuration template where the `{{ .Version }}` - variable is replaced with the VirtualBox version. - -- `guest_additions_sha256` (string) - The SHA256 checksum of the guest additions ISO that will be uploaded to - the guest VM. By default the checksums will be downloaded from the - VirtualBox website, so this only needs to be set if you want to be - explicit about the checksum. - -- `guest_additions_url` (string) - The URL to the guest additions ISO to upload. This can also be a file - URL if the ISO is at a local path. By default, the VirtualBox builder - will attempt to find the guest additions ISO on the local file system. - If it is not available locally, the builder will download the proper - guest additions ISO from the internet. This is a template engine, and you - have access to the variable `{{ .Version }}`. - -- `guest_additions_interface` (string) - The interface type to use to mount guest additions when - guest_additions_mode is set to attach. Will default to the value set in - iso_interface, if iso_interface is set. Will default to "ide", if - iso_interface is not set. Options are "ide" and "sata". - - `guest_os_type` (string) - The guest OS type being installed. By default this is other, but you can get dramatic performance improvements by setting this to the proper value. To view all available values for this run VBoxManage list diff --git a/website/pages/partials/builder/virtualbox/ovf/Config-not-required.mdx b/website/pages/partials/builder/virtualbox/ovf/Config-not-required.mdx index a565af078..a5bd3d5f9 100644 --- a/website/pages/partials/builder/virtualbox/ovf/Config-not-required.mdx +++ b/website/pages/partials/builder/virtualbox/ovf/Config-not-required.mdx @@ -1,37 +1,5 @@ -- `guest_additions_mode` (string) - The method by which guest additions are - made available to the guest for installation. Valid options are upload, - attach, or disable. If the mode is attach the guest additions ISO will - be attached as a CD device to the virtual machine. If the mode is upload - the guest additions ISO will be uploaded to the path specified by - guest_additions_path. The default value is upload. If disable is used, - guest additions won't be downloaded, either. - -- `guest_additions_path` (string) - The path on the guest virtual machine - where the VirtualBox guest additions ISO will be uploaded. By default this - is VBoxGuestAdditions.iso which should upload into the login directory of - the user. This is a configuration - template where the Version - variable is replaced with the VirtualBox version. - -- `guest_additions_interface` (string) - The interface type to use to mount - guest additions when guest_additions_mode is set to attach. Will - default to the value set in iso_interface, if iso_interface is set. - Will default to "ide", if iso_interface is not set. Options are "ide" and - "sata". - -- `guest_additions_sha256` (string) - The SHA256 checksum of the guest - additions ISO that will be uploaded to the guest VM. By default the - checksums will be downloaded from the VirtualBox website, so this only needs - to be set if you want to be explicit about the checksum. - -- `guest_additions_url` (string) - The URL to the guest additions ISO - to upload. This can also be a file URL if the ISO is at a local path. By - default, the VirtualBox builder will attempt to find the guest additions ISO - on the local file system. If it is not available locally, the builder will - download the proper guest additions ISO from the internet. - - `import_flags` ([]string) - Additional flags to pass to VBoxManage import. This can be used to add additional command-line flags such as --eula-accept to accept a EULA in the OVF. diff --git a/website/pages/partials/builder/virtualbox/vm/Config-not-required.mdx b/website/pages/partials/builder/virtualbox/vm/Config-not-required.mdx index 2318c7817..2990f94a8 100644 --- a/website/pages/partials/builder/virtualbox/vm/Config-not-required.mdx +++ b/website/pages/partials/builder/virtualbox/vm/Config-not-required.mdx @@ -1,31 +1,5 @@ -- `guest_additions_mode` (string) - The method by which guest additions are - made available to the guest for installation. Valid options are `upload`, - `attach`, or `disable`. If the mode is `attach` the guest additions ISO will - be attached as a CD device to the virtual machine. If the mode is `upload` - the guest additions ISO will be uploaded to the path specified by - `guest_additions_path`. The default value is `upload`. If `disable` is used, - guest additions won't be downloaded, either. - -- `guest_additions_path` (string) - The path on the guest virtual machine - where the VirtualBox guest additions ISO will be uploaded. By default this - is `VBoxGuestAdditions.iso` which should upload into the login directory of - the user. This is a [configuration - template](/docs/templates/engine) where the `Version` - variable is replaced with the VirtualBox version. - -- `guest_additions_sha256` (string) - The SHA256 checksum of the guest - additions ISO that will be uploaded to the guest VM. By default the - checksums will be downloaded from the VirtualBox website, so this only needs - to be set if you want to be explicit about the checksum. - -- `guest_additions_url` (string) - The URL to the guest additions ISO - to upload. This can also be a file URL if the ISO is at a local path. By - default, the VirtualBox builder will attempt to find the guest additions ISO - on the local file system. If it is not available locally, the builder will - download the proper guest additions ISO from the internet. - - `attach_snapshot` (string) - Default to `null/empty`. The name of an **existing** snapshot to which the builder shall attach the VM before starting it. If no snapshot is specified the builder will simply start the diff --git a/website/pages/partials/builder/vmware/common/RunConfig-not-required.mdx b/website/pages/partials/builder/vmware/common/RunConfig-not-required.mdx index b1ff38515..dd096f7d1 100644 --- a/website/pages/partials/builder/vmware/common/RunConfig-not-required.mdx +++ b/website/pages/partials/builder/vmware/common/RunConfig-not-required.mdx @@ -28,3 +28,10 @@ is used to secure the VNC communication with the VM. This must be set to true if building on ESXi 6.5 and 6.7 with VNC enabled. Defaults to false. + +- `vnc_over_websocket` (bool) - When set to true, Packer will connect to the remote VNC server over a websocket connection + and any other VNC configuration option will be ignored. + Remote builds using ESXi 6.7+ allows to connect to the VNC server only over websocket, + for these the `vnc_over_websocket` must be set to true. + +- `insecure_connection` (bool) - Do not validate VNC over websocket server's TLS certificate. Defaults to `false`. diff --git a/website/pages/partials/builder/vmware/common/RunConfig.mdx b/website/pages/partials/builder/vmware/common/RunConfig.mdx new file mode 100644 index 000000000..44e675944 --- /dev/null +++ b/website/pages/partials/builder/vmware/common/RunConfig.mdx @@ -0,0 +1,3 @@ + + +~> **Note:** If [vnc_over_websocket](#vnc_over_websocket) is set to true, any other VNC configuration will be ignored. diff --git a/website/pages/partials/builder/vmware/common/ToolsConfig-not-required.mdx b/website/pages/partials/builder/vmware/common/ToolsConfig-not-required.mdx index eda25becc..6e3d1b06a 100644 --- a/website/pages/partials/builder/vmware/common/ToolsConfig-not-required.mdx +++ b/website/pages/partials/builder/vmware/common/ToolsConfig-not-required.mdx @@ -10,3 +10,7 @@ `Flavor`, which will be the value of `tools_upload_flavor`. By default the upload path is set to `{{.Flavor}}.iso`. This setting is not used when `remote_type` is `esx5`. + +- `tools_source_path` (string) - The path on your local machine to fetch the vmware tools from. If this + is not set but the tools_upload_flavor is set, then Packer will try to + load the VMWare tools from the VMWare installation directory. diff --git a/website/pages/partials/builder/vsphere/clone/CloneConfig-not-required.mdx b/website/pages/partials/builder/vsphere/clone/CloneConfig-not-required.mdx index 804237daa..d9ffbd790 100644 --- a/website/pages/partials/builder/vsphere/clone/CloneConfig-not-required.mdx +++ b/website/pages/partials/builder/vsphere/clone/CloneConfig-not-required.mdx @@ -11,6 +11,8 @@ available network. If the network is inside a network folder in vCenter, you need to provide the full path to the network. +- `mac_address` (string) - Sets a custom Mac Address to the network adapter. If set, the [network](#network) must be also specified. + - `notes` (string) - VM notes. - `vapp` (vAppConfig) - Set the vApp Options to a virtual machine. diff --git a/website/pages/partials/builder/vsphere/iso/CDRomConfig-not-required.mdx b/website/pages/partials/builder/vsphere/common/CDRomConfig-not-required.mdx similarity index 86% rename from website/pages/partials/builder/vsphere/iso/CDRomConfig-not-required.mdx rename to website/pages/partials/builder/vsphere/common/CDRomConfig-not-required.mdx index b72e5de01..e225b4820 100644 --- a/website/pages/partials/builder/vsphere/iso/CDRomConfig-not-required.mdx +++ b/website/pages/partials/builder/vsphere/common/CDRomConfig-not-required.mdx @@ -1,4 +1,4 @@ - + - `cdrom_type` (string) - Which controller to use. Example: `sata`. Defaults to `ide`. diff --git a/website/pages/partials/builder/vsphere/iso/FloppyConfig-not-required.mdx b/website/pages/partials/builder/vsphere/common/FloppyConfig-not-required.mdx similarity index 91% rename from website/pages/partials/builder/vsphere/iso/FloppyConfig-not-required.mdx rename to website/pages/partials/builder/vsphere/common/FloppyConfig-not-required.mdx index 0e83366ed..fc41e65e1 100644 --- a/website/pages/partials/builder/vsphere/iso/FloppyConfig-not-required.mdx +++ b/website/pages/partials/builder/vsphere/common/FloppyConfig-not-required.mdx @@ -1,4 +1,4 @@ - + - `floppy_img_path` (string) - Datastore path to a floppy image that will be mounted to the VM. Example: `[datastore1] ISO/pvscsi-Windows8.flp`. diff --git a/website/pages/partials/builder/vsphere/common/HardwareConfig-not-required.mdx b/website/pages/partials/builder/vsphere/common/HardwareConfig-not-required.mdx index 1d1ae824f..ccc4f5e90 100644 --- a/website/pages/partials/builder/vsphere/common/HardwareConfig-not-required.mdx +++ b/website/pages/partials/builder/vsphere/common/HardwareConfig-not-required.mdx @@ -1,6 +1,6 @@ -- `CPUs` (int32) - Number of CPU sockets. +- `CPUs` (int32) - Number of CPU cores. - `cpu_cores` (int32) - Number of CPU cores per socket. diff --git a/website/pages/partials/builder/vsphere/iso/RemoveCDRomConfig-not-required.mdx b/website/pages/partials/builder/vsphere/common/RemoveCDRomConfig-not-required.mdx similarity index 65% rename from website/pages/partials/builder/vsphere/iso/RemoveCDRomConfig-not-required.mdx rename to website/pages/partials/builder/vsphere/common/RemoveCDRomConfig-not-required.mdx index 9e3dd3d20..651bffa6e 100644 --- a/website/pages/partials/builder/vsphere/iso/RemoveCDRomConfig-not-required.mdx +++ b/website/pages/partials/builder/vsphere/common/RemoveCDRomConfig-not-required.mdx @@ -1,3 +1,3 @@ - + - `remove_cdrom` (bool) - Remove CD-ROM devices from template. Defaults to `false`. diff --git a/website/pages/partials/builders/virtualbox-ssh-key-pair.mdx b/website/pages/partials/builders/virtualbox-ssh-key-pair.mdx index a61ef5e2d..8fc1a78e9 100644 --- a/website/pages/partials/builders/virtualbox-ssh-key-pair.mdx +++ b/website/pages/partials/builders/virtualbox-ssh-key-pair.mdx @@ -1,17 +1,17 @@ ### SSH key pair automation The VirtualBox builders can inject the current SSH key pair's public key into -the template using the following variable: - -- `SSHPublicKey` (_VirtualBox builders only_) - This is the SSH public key - as a line in OpenSSH authorized_keys format. +the template using the `SSHPublicKey` template engine. This is the SSH public +key as a line in OpenSSH authorized_keys format. When a private key is provided using `ssh_private_key_file`, the key's -corresponding public key can be accessed using the above variables. +corresponding public key can be accessed using the above engine. + +@include 'helper/communicator/SSH-Private-Key-File-not-required.mdx' If `ssh_password` and `ssh_private_key_file` are not specified, Packer will automatically generate en ephemeral key pair. The key pair's public key can -be accessed using the template variables. +be accessed using the template engine. For example, the public key can be provided in the boot command as a URL encoded string by appending `| urlquery` to the variable: diff --git a/website/pages/partials/common/CDConfig-not-required.mdx b/website/pages/partials/common/CDConfig-not-required.mdx new file mode 100644 index 000000000..11e4b8fc6 --- /dev/null +++ b/website/pages/partials/common/CDConfig-not-required.mdx @@ -0,0 +1,47 @@ + + +- `cd_files` ([]string) - A list of files to place onto a CD that is attached when the VM is + booted. This can include either files or directories; any directories + will be copied onto the CD recursively, preserving directory structure + hierarchy. Symlinks will have the link's target copied into the directory + tree on the CD where the symlink was. File globbing is allowed. + + Usage example (JSON): + + ```json + "cd_files": ["./somedirectory/meta-data", "./somedirectory/user-data"], + "cd_label": "cidata", + ``` + + Usage example (HCL): + + ```hcl + cd_files = ["./somedirectory/meta-data", "./somedirectory/user-data"] + cd_label = "cidata" + ``` + + The above will create a CD with two files, user-data and meta-data in the + CD root. This specific example is how you would create a CD that can be + used for an Ubuntu 20.04 autoinstall. + + Since globbing is also supported, + + ```hcl + cd_files = ["./somedirectory/*"] + cd_label = "cidata" + ``` + + Would also be an acceptable way to define the above cd. The difference + between providing the directory with or without the glob is whether the + directory itself or its contents will be at the CD root. + + Use of this option assumes that you have a command line tool installed + that can handle the iso creation. Packer will use one of the following + tools: + + * xorriso + * mkisofs + * hdiutil (normally found in macOS) + * oscdimg (normally found in Windows as part of the Windows ADK) + +- `cd_label` (string) - CD Label diff --git a/website/pages/partials/common/CDConfig.mdx b/website/pages/partials/common/CDConfig.mdx new file mode 100644 index 000000000..b234df3eb --- /dev/null +++ b/website/pages/partials/common/CDConfig.mdx @@ -0,0 +1,11 @@ + + +An iso (CD) containing custom files can be made available for your build. + +By default, no extra CD will be attached. All files listed in this setting +get placed into the root directory of the CD and the CD is attached as the +second CD device. + +This config exists to work around modern operating systems that have no +way to mount floppy disks, which was our previous go-to for adding files at +boot time. diff --git a/website/pages/partials/from-1.5/variables/foo-block.mdx b/website/pages/partials/from-1.5/variables/foo-block.mdx index 63cb2351d..5b68c1c08 100644 --- a/website/pages/partials/from-1.5/variables/foo-block.mdx +++ b/website/pages/partials/from-1.5/variables/foo-block.mdx @@ -1,8 +1,11 @@ ```hcl # variables.pkr.hcl variable "foo" { - type = string - default = "the default value of the `foo` variable" + type = string + default = "the default value of the `foo` variable" description = "description of the `foo` variable" + sensitive = false + # When a variable is sensitive all string-values from that variable will be + # obfuscated from Packer's output. } ``` diff --git a/website/pages/partials/from-1.5/variables/sensitive.mdx b/website/pages/partials/from-1.5/variables/sensitive.mdx new file mode 100644 index 000000000..bc5ec3066 --- /dev/null +++ b/website/pages/partials/from-1.5/variables/sensitive.mdx @@ -0,0 +1,23 @@ +## A variable can be sensitive + +When a variable is sensitive all string-values from that variable will be +obfuscated from Packer's output : + +```hcl +# var-foo.pkr.hcl +variable "foo" { + sensitive = true + default = { + key = "SECR3TP4SSW0RD" + } +} +``` + +```shell-session +$ packer inspect var-foo.pkr.hcl +Packer Inspect: HCL2 mode + +> input-variables: +var.foo: "{\n \"key\" = \"\"\n }" +... +``` diff --git a/website/pages/partials/provisioner/ansible/Config-not-required.mdx b/website/pages/partials/provisioner/ansible/Config-not-required.mdx index 751649e99..99d0df0f5 100644 --- a/website/pages/partials/provisioner/ansible/Config-not-required.mdx +++ b/website/pages/partials/provisioner/ansible/Config-not-required.mdx @@ -120,8 +120,8 @@ test your playbook. this option is not used if you set an `inventory_file`. - `galaxy_file` (string) - A requirements file which provides a way to - install roles with the [ansible-galaxy - cli](http://docs.ansible.com/ansible/galaxy.html#the-ansible-galaxy-command-line-tool) + install roles or collections with the [ansible-galaxy + cli](https://docs.ansible.com/ansible/latest/galaxy/user_guide.html#the-ansible-galaxy-command-line-tool) on the local machine before executing `ansible-playbook`. By default, this is empty. - `galaxy_command` (string) - The command to invoke ansible-galaxy. By default, this is @@ -131,11 +131,16 @@ Adds `--force` option to `ansible-galaxy` command. By default, this is `false`. -- `roles_path` (string) - The path to the directory on your local system to - install the roles in. Adds `--roles-path /path/to/your/roles` to +- `roles_path` (string) - The path to the directory on your local system in which to + install the roles. Adds `--roles-path /path/to/your/roles` to `ansible-galaxy` command. By default, this is empty, and thus `--roles-path` option is not added to the command. +- `collections_path` (string) - The path to the directory on your local system in which to + install the collections. Adds `--collections-path /path/to/your/collections` to + `ansible-galaxy` command. By default, this is empty, and thus `--collections-path` + option is not added to the command. + - `use_proxy` (boolean) - When `true`, set up a localhost proxy adapter so that Ansible has an IP address to connect to, even if your guest does not have an IP address. For example, the adapter is necessary for Docker builds diff --git a/website/scripts/index_search_content.js b/website/scripts/index_search_content.js index 480c0ca27..f853b4ddf 100644 --- a/website/scripts/index_search_content.js +++ b/website/scripts/index_search_content.js @@ -1,129 +1,3 @@ -require('dotenv').config() +const { indexDocsContent } = require('@hashicorp/react-search/tools') -const algoliasearch = require('algoliasearch') -const glob = require('glob') -const matter = require('gray-matter') -const path = require('path') -const remark = require('remark') -const visit = require('unist-util-visit') - -// In addition to the content of the page, -// define additional front matter attributes that will be search-indexable -const SEARCH_DIMENSIONS = ['page_title', 'description'] - -main() - -async function main() { - const pagesFolder = path.join(__dirname, '../pages') - - // Grab all search-indexable content and format for Algolia - const searchObjects = await Promise.all( - glob - .sync(path.join(pagesFolder, '**/*.mdx'), { - ignore: path.join(pagesFolder, 'partials/**/*'), - }) - .map(async (fullPath) => { - const { content, data } = matter.read(fullPath) - - const searchableDimensions = SEARCH_DIMENSIONS.reduce( - (acc, dimension) => { - return { ...acc, [dimension]: data[dimension] } - }, - {} - ) - - const headings = await collectHeadings(content) - - // Get path relative to `pages` - const __resourcePath = fullPath.replace(`${pagesFolder}/`, '') - - // Use clean URL for Algolia id - const objectID = __resourcePath.replace('.mdx', '') - - return { - ...searchableDimensions, - headings, - objectID, - } - }) - ) - - try { - await indexSearchContent(searchObjects) - } catch (e) { - console.error(e) - process.exit(1) - } -} - -async function indexSearchContent(objects) { - const { - NEXT_PUBLIC_ALGOLIA_APP_ID: appId, - NEXT_PUBLIC_ALGOLIA_INDEX: index, - ALGOLIA_API_KEY: apiKey, - } = process.env - - if (!apiKey || !appId || !index) { - throw new Error( - `[*** Algolia Search Indexing Error ***] Received: ALGOLIA_API_KEY=${apiKey} ALGOLIA_APP_ID=${appId} ALGOLIA_INDEX=${index} \n Please ensure all Algolia Search-related environment vars are set in CI settings.` - ) - } - - console.log(`updating ${objects.length} indices...`) - - try { - const searchClient = algoliasearch(appId, apiKey) - const searchIndex = searchClient.initIndex(index) - - const { objectIDs } = await searchIndex.partialUpdateObjects(objects, { - createIfNotExists: true, - }) - - let staleIds = [] - - await searchIndex.browseObjects({ - query: '', - batch: (batch) => { - staleIds = staleIds.concat( - batch - .filter(({ objectID }) => !objectIDs.includes(objectID)) - .map(({ objectID }) => objectID) - ) - }, - }) - - if (staleIds.length > 0) { - console.log(`deleting ${staleIds.length} stale indices:`) - console.log(staleIds) - - await searchIndex.deleteObjects(staleIds) - } - - console.log('done') - process.exit(0) - } catch (error) { - throw new Error(error) - } -} - -async function collectHeadings(mdxContent) { - const headings = [] - - const headingMapper = () => (tree) => { - visit(tree, 'heading', (node) => { - const title = node.children.reduce((m, n) => { - if (n.value) m += n.value - return m - }, '') - // Only include level 1 or level 2 headings - if (node.depth < 3) { - headings.push(title) - } - }) - } - - return remark() - .use(headingMapper) - .process(mdxContent) - .then(() => headings) -} +indexDocsContent()